// Marsan Properties — Listings

const ListingsPage = () => {
  const { Icon, Header, Footer, PropertyCard } = window.MarsanComponents;
  const { PROPERTIES, CATEGORIES } = window.MARSAN_DATA;

  const params = new URLSearchParams(window.location.search);
  const initialCat = params.get('cat') || 'All';
  const initialBudget = params.get('budget') || '';
  const initialQuery = params.get('q') || '';

  const [view, setView] = React.useState('grid');
  const [activeCat, setActiveCat] = React.useState(initialCat);
  const [statusFilter, setStatusFilter] = React.useState({ Available: true, 'Few Left': true, Upcoming: true, 'Sold Out': false });
  const [facingFilter, setFacingFilter] = React.useState({});
  const [approvalsRera, setApprovalsRera] = React.useState(false);
  const [approvalsHmda, setApprovalsHmda] = React.useState(false);
  const [approvalsLoan, setApprovalsLoan] = React.useState(false);
  const [sort, setSort] = React.useState('Featured');
  const [budget] = React.useState(initialBudget);
  const [query, setQuery] = React.useState(initialQuery);
  const [page, setPage] = React.useState(1);
  const PAGE_SIZE = 6;

  let list = PROPERTIES.filter(p => activeCat === 'All' || p.category === activeCat);
  list = list.filter(p => statusFilter[p.status]);

  // Text search — name, location, address.
  if (query.trim()) {
    const q = query.trim().toLowerCase();
    list = list.filter(p => p.name.toLowerCase().includes(q) || p.location.toLowerCase().includes(q) || (p.address || '').toLowerCase().includes(q));
  }

  // Facing chips
  const activeFacings = Object.entries(facingFilter).filter(([_, v]) => v).map(([k]) => k);
  if (activeFacings.length) {
    list = list.filter(p => (p.facing || []).some(f => activeFacings.some(af => f.toUpperCase().includes(af.toUpperCase()))));
  }

  // Approvals — RERA must have a non-dash code; HMDA & loan-ready apply to all our seeded properties.
  if (approvalsRera) list = list.filter(p => p.rera && p.rera !== '—');

  if (budget) {
    const [lo, hi] = budget.split('-').map(Number);
    list = list.filter(p => {
      const min = p.priceUnit === 'Cr' ? p.priceMin * 100 : p.priceMin;
      return min >= lo && min <= hi;
    });
  }
  if (sort === 'Newest first') list = [...list].reverse();
  if (sort === 'Price: Low to High') list = [...list].sort((a, b) => (a.priceMin * (a.priceUnit === 'Cr' ? 100 : 1)) - (b.priceMin * (b.priceUnit === 'Cr' ? 100 : 1)));
  if (sort === 'Price: High to Low') list = [...list].sort((a, b) => (b.priceMin * (b.priceUnit === 'Cr' ? 100 : 1)) - (a.priceMin * (a.priceUnit === 'Cr' ? 100 : 1)));

  const total = list.length;
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const filtered = view === 'map' ? list : list.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const cats = CATEGORIES.length ? CATEGORIES : [];

  const resetAll = () => {
    setActiveCat('All');
    setStatusFilter({ Available: true, 'Few Left': true, Upcoming: true, 'Sold Out': false });
    setFacingFilter({});
    setApprovalsRera(false); setApprovalsHmda(false); setApprovalsLoan(false);
    setQuery('');
    setSort('Featured'); setPage(1);
  };

  return (
    <div className="ms-root" style={{ width: '100%', background: '#f6f1e6' }}>
      <div style={{ background: '#0a1f17' }}><Header active="Properties" light /></div>

      <section style={{ background: '#0a1f17', padding: '60px 56px 80px', position: 'relative' }} className="ms-grain">
        <div style={{ maxWidth: 1440, margin: '0 auto', position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.55)', marginBottom: 24 }}>
            <a href="/" style={{ color: 'inherit', textDecoration: 'none' }}>Home</a>
            <Icon name="chevron" size={12} />
            <span style={{ color: '#e2bd6b' }}>Properties</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24 }}>
            <div>
              <h1 className="ms-h1" style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 300, fontSize: 72, color: '#f6f1e6', margin: '0 0 16px', lineHeight: 1 }}>
                The full <em style={{ color: '#e2bd6b' }}>portfolio</em>.
              </h1>
              <p style={{ fontSize: 16, color: 'rgba(232,220,193,0.7)', maxWidth: 580, margin: 0 }}>
                {PROPERTIES.length} active developments across Hyderabad — every one with a clear title, an approved master plan, and an advisor at your call.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end' }}>
              <span className="ms-meta" style={{ color: 'rgba(232,220,193,0.55)' }}>SHOWING</span>
              <span style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 28, color: '#e2bd6b' }}>{total}</span>
              <span className="ms-meta" style={{ color: 'rgba(232,220,193,0.55)' }}>OF {PROPERTIES.length}</span>
            </div>
          </div>
        </div>
      </section>

      <div style={{ maxWidth: 1440, margin: '0 auto', padding: '40px 56px 120px', display: 'grid', gridTemplateColumns: '300px 1fr', gap: 40 }} className="ms-collapse-mobile">

        <aside style={{ position: 'sticky', top: 24, alignSelf: 'start' }}>
          <div style={{ background: '#fff', border: '1px solid #d9cfb8', padding: 28 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28 }}>
              <span className="ms-eyebrow">Refine</span>
              <button onClick={resetAll} style={{ fontSize: 11, color: '#a88841', cursor: 'pointer', background: 'none', border: 'none', padding: 0 }}>Reset all</button>
            </div>

            <div style={{ marginBottom: 28 }}>
              <div className="ms-label">Category</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {['All', ...cats.map(c => c.name)].map(c => (
                  <label key={c} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#0a1f17', cursor: 'pointer' }}>
                    <input type="radio" checked={activeCat === c} onChange={() => { setActiveCat(c); setPage(1); }} style={{ accentColor: '#c9a55c' }} />
                    {c}
                    <span style={{ marginLeft: 'auto', fontSize: 11, color: '#8c857b' }}>
                      {c === 'All' ? PROPERTIES.length : (cats.find(x => x.name === c)?.count || PROPERTIES.filter(p => p.category === c).length)}
                    </span>
                  </label>
                ))}
              </div>
            </div>

            <div style={{ height: 1, background: '#d9cfb8', margin: '24px 0' }} />

            <div style={{ marginBottom: 28 }}>
              <div className="ms-label">Availability</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {['Available', 'Few Left', 'Upcoming', 'Sold Out'].map(s => (
                  <label key={s} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#0a1f17', cursor: 'pointer' }}>
                    <input type="checkbox" checked={statusFilter[s]}
                      onChange={(e) => { setStatusFilter(p => ({ ...p, [s]: e.target.checked })); setPage(1); }}
                      style={{ accentColor: '#c9a55c' }} /> {s}
                  </label>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 28 }}>
              <div className="ms-label">Search</div>
              <input className="ms-input" value={query} onChange={(e) => { setQuery(e.target.value); setPage(1); }} placeholder="Project, area…" style={{ padding: 10, fontSize: 13 }} />
            </div>

            <div style={{ marginBottom: 28 }}>
              <div className="ms-label">Facing</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {['East', 'West', 'North', 'South', 'NE', 'NW'].map(f => (
                  <button key={f} type="button"
                    onClick={() => { setFacingFilter(s => ({ ...s, [f]: !s[f] })); setPage(1); }}
                    className="ms-chip" style={{
                      cursor: 'pointer',
                      background: facingFilter[f] ? 'linear-gradient(135deg, #c9a55c, #e2bd6b)' : '#fff',
                      color: facingFilter[f] ? '#0a1f17' : '#4a4540',
                      borderColor: facingFilter[f] ? '#a88841' : '#d9cfb8',
                    }}>{f}</button>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 28 }}>
              <div className="ms-label">Approvals</div>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#0a1f17', marginBottom: 10, cursor: 'pointer' }}>
                <input type="checkbox" checked={approvalsRera} onChange={(e) => { setApprovalsRera(e.target.checked); setPage(1); }} style={{ accentColor: '#c9a55c' }} /> RERA Approved
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#0a1f17', marginBottom: 10, cursor: 'pointer' }}>
                <input type="checkbox" checked={approvalsHmda} onChange={(e) => setApprovalsHmda(e.target.checked)} style={{ accentColor: '#c9a55c' }} /> HMDA / DTCP
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#0a1f17', marginBottom: 10, cursor: 'pointer' }}>
                <input type="checkbox" checked={approvalsLoan} onChange={(e) => setApprovalsLoan(e.target.checked)} style={{ accentColor: '#c9a55c' }} /> Bank-loan ready
              </label>
            </div>

            <button onClick={resetAll} className="ms-btn ms-btn-ghost-dark" style={{ width: '100%' }}>Reset filters</button>
          </div>
        </aside>

        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, padding: '16px 24px', background: '#fff', border: '1px solid #d9cfb8' }} className="ms-mobile-stack">
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <span className="ms-meta">SORT BY</span>
              <select value={sort} onChange={e => setSort(e.target.value)} className="ms-select" style={{ width: 200, padding: '8px 12px', fontSize: 13, border: '1px solid #d9cfb8' }}>
                <option>Featured</option><option>Newest first</option><option>Price: Low to High</option><option>Price: High to Low</option>
              </select>
            </div>
            <div style={{ display: 'flex', gap: 4, border: '1px solid #d9cfb8' }}>
              {[
                { id: 'grid', icon: 'grid' },
                { id: 'list', icon: 'list' },
                { id: 'map', icon: 'map' },
              ].map(v => (
                <button key={v.id} onClick={() => setView(v.id)} style={{
                  padding: '10px 16px', border: 'none', cursor: 'pointer',
                  background: view === v.id ? '#0a1f17' : '#fff',
                  color: view === v.id ? '#e2bd6b' : '#0a1f17',
                  display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
                }}><Icon name={v.icon} size={14} /> {v.id}</button>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 8, marginBottom: 24, flexWrap: 'wrap' }}>
            {[activeCat !== 'All' ? activeCat : null, 'Hyderabad', ...Object.entries(statusFilter).filter(([_, v]) => v).map(([k]) => k)]
              .filter(Boolean).map(c => (
                <span key={c} className="ms-chip" style={{ background: '#fff', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  {c} <span style={{ color: '#a88841', cursor: 'pointer' }}
                    onClick={() => { if (c === activeCat) setActiveCat('All'); else if (statusFilter[c] !== undefined) setStatusFilter(p => ({ ...p, [c]: false })); }}>×</span>
                </span>
              ))}
          </div>

          {view === 'map' ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 24, height: 720 }} className="ms-collapse-mobile">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16, overflow: 'auto' }} className="ms-scroll">
                {list.map(p => (
                  <a key={p.id} href={'/property.html?slug=' + encodeURIComponent(p.slug)} style={{ background: '#fff', border: '1px solid #d9cfb8', display: 'grid', gridTemplateColumns: '120px 1fr', gap: 16, padding: 12, textDecoration: 'none', color: 'inherit' }}>
                    <div className="ms-img-ph" style={{ height: 120 }}><span>{p.image}</span></div>
                    <div style={{ padding: '4px 0' }}>
                      <span className="ms-eyebrow" style={{ fontSize: 9 }}>{p.category}</span>
                      <h4 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, margin: '4px 0', color: '#0a1f17' }}>{p.name}</h4>
                      <div style={{ fontSize: 11, color: '#8c857b' }}>{p.location}</div>
                      <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 16, color: '#a88841', marginTop: 6 }}>₹{p.priceMin}–{p.priceMax} {p.priceUnit}</div>
                    </div>
                  </a>
                ))}
              </div>
              <div style={{ background: '#143a2a', position: 'relative', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0,
                  backgroundImage: `linear-gradient(rgba(201,165,92,0.08) 1px, transparent 1px),
                                    linear-gradient(90deg, rgba(201,165,92,0.08) 1px, transparent 1px)`,
                  backgroundSize: '40px 40px',
                }} />
                <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
                  <path d="M0,200 Q200,180 400,260 T800,300" stroke="rgba(201,165,92,0.4)" strokeWidth="2" fill="none" />
                  <path d="M150,0 Q200,300 350,500 T550,720" stroke="rgba(201,165,92,0.3)" strokeWidth="1.5" fill="none" />
                  <path d="M0,500 L800,520" stroke="rgba(201,165,92,0.25)" strokeWidth="1" fill="none" />
                </svg>
                {list.slice(0, 6).map((p, i) => {
                  const positions = [[180, 220], [340, 180], [500, 320], [220, 420], [620, 250], [400, 540]];
                  const [x, y] = positions[i] || [100, 100];
                  return (
                    <a key={p.id} href={'/property.html?slug=' + encodeURIComponent(p.slug)} style={{ position: 'absolute', left: x, top: y, transform: 'translate(-50%, -100%)', textDecoration: 'none' }}>
                      <div style={{ position: 'relative', display: 'inline-block' }}>
                        <div style={{ background: '#c9a55c', color: '#0a1f17', padding: '6px 12px', fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', boxShadow: '0 4px 12px rgba(0,0,0,0.3)', position: 'relative', zIndex: 1 }}>
                          ₹{p.priceMin}{p.priceUnit === 'Cr' ? 'Cr' : 'L'}+
                        </div>
                        <span className="ms-pin-pulse__ring" style={{ inset: -6 }} />
                      </div>
                      <div style={{ width: 0, height: 0, borderLeft: '6px solid transparent', borderRight: '6px solid transparent', borderTop: '8px solid #c9a55c', margin: '0 auto' }} />
                    </a>
                  );
                })}
                <div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(10,31,23,0.85)', backdropFilter: 'blur(10px)', padding: '10px 16px', color: '#e2bd6b', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                  Hyderabad · Live Map
                </div>
              </div>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: view === 'grid' ? 'repeat(2, 1fr)' : '1fr', gap: 24 }} className="ms-collapse-mobile">
              {filtered.map(p => <PropertyCard key={p.id} p={p} />)}
              {!filtered.length && <div style={{ padding: '60px 0', textAlign: 'center', color: '#8c857b' }}>No properties match these filters.</div>}
            </div>
          )}

          {view !== 'map' && totalPages > 1 && (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, marginTop: 56 }}>
              {Array.from({ length: totalPages }).map((_, i) => (
                <button key={i} onClick={() => setPage(i + 1)} style={{
                  width: 40, height: 40, border: '1px solid #d9cfb8',
                  background: page === i + 1 ? '#0a1f17' : '#fff', color: page === i + 1 ? '#e2bd6b' : '#0a1f17',
                  cursor: 'pointer', fontSize: 13,
                }}>{i + 1}</button>
              ))}
              {page < totalPages && (
                <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} style={{ padding: '0 16px', height: 40, border: '1px solid #d9cfb8', background: '#fff', color: '#0a1f17', cursor: 'pointer', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
                  Next <Icon name="chevron" size={12} />
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      <Footer />
    </div>
  );
};

window.ListingsPage = ListingsPage;
