// Listings index — filters + grid + map toggle

const ListingsPage = ({ openListing, faves, toggleFav }) => {
  useLucide();
  const [view, setView] = React.useState('grid'); // grid | map
  const [filters, setFilters] = React.useState({
    type: 'all',     // House, Townhouse, Condo
    minBeds: 0,
    priceBand: 'all',
    sort: 'newest',
  });

  const filtered = SITE_DATA.listings.filter(l => {
    if (filters.type !== 'all' && l.type !== filters.type) return false;
    if (l.beds < filters.minBeds) return false;
    if (filters.priceBand === 'u750' && l.price >= 750000) return false;
    if (filters.priceBand === '750-1.2' && (l.price < 750000 || l.price >= 1200000)) return false;
    if (filters.priceBand === '1.2-2' && (l.price < 1200000 || l.price >= 2000000)) return false;
    if (filters.priceBand === '2+' && l.price < 2000000) return false;
    return true;
  });

  const sorted = [...filtered].sort((a, b) => {
    if (filters.sort === 'price-asc') return a.price - b.price;
    if (filters.sort === 'price-desc') return b.price - a.price;
    if (filters.sort === 'beds') return b.beds - a.beds;
    return 0;
  });

  return (
    <div className="page">
      <div className="page-head container">
        <span className="eyebrow">Currently for sale</span>
        <h1 style={{ marginTop: 14 }}>Active listings</h1>
        <p className="lead">The properties I'm currently representing across Metro Vancouver. Filter by type, beds, or budget — or switch to map view to explore by location.</p>
      </div>

      <section className="section container">
        <div className="filter-bar">
          <button className={`filter-chip ${filters.type === 'all' ? 'active' : ''}`} onClick={() => setFilters({ ...filters, type: 'all' })}>All</button>
          <button className={`filter-chip ${filters.type === 'House' ? 'active' : ''}`} onClick={() => setFilters({ ...filters, type: 'House' })}>House</button>
          <button className={`filter-chip ${filters.type === 'Townhouse' ? 'active' : ''}`} onClick={() => setFilters({ ...filters, type: 'Townhouse' })}>Townhouse</button>
          <button className={`filter-chip ${filters.type === 'Condo' ? 'active' : ''}`} onClick={() => setFilters({ ...filters, type: 'Condo' })}>Condo</button>
          <div className="sep"></div>
          <select className="select-sm" value={filters.minBeds} onChange={(e) => setFilters({ ...filters, minBeds: +e.target.value })}>
            <option value="0">Any beds</option>
            <option value="1">1+ bed</option>
            <option value="2">2+ beds</option>
            <option value="3">3+ beds</option>
            <option value="4">4+ beds</option>
          </select>
          <select className="select-sm" value={filters.priceBand} onChange={(e) => setFilters({ ...filters, priceBand: e.target.value })}>
            <option value="all">Any price</option>
            <option value="u750">Under $750K</option>
            <option value="750-1.2">$750K – $1.2M</option>
            <option value="1.2-2">$1.2M – $2M</option>
            <option value="2+">$2M+</option>
          </select>
          <div className="sep"></div>
          <select className="select-sm" value={filters.sort} onChange={(e) => setFilters({ ...filters, sort: e.target.value })}>
            <option value="newest">Newest</option>
            <option value="price-asc">Price: low to high</option>
            <option value="price-desc">Price: high to low</option>
            <option value="beds">Most bedrooms</option>
          </select>
          <span className="filter-results">{sorted.length} homes</span>
          <div className="view-toggle">
            <button className={view === 'grid' ? 'active' : ''} onClick={() => setView('grid')}>
              <Icon name="grid-3x3" size={14} /> Grid
            </button>
            <button className={view === 'map' ? 'active' : ''} onClick={() => setView('map')}>
              <Icon name="map" size={14} /> Map
            </button>
          </div>
        </div>

        {sorted.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-3)' }}>
            <Icon name="search-x" size={32} />
            <p style={{ marginTop: 12 }}>No homes match these filters. Try widening your search.</p>
          </div>
        )}

        {view === 'grid' && sorted.length > 0 && (
          <div className="listing-grid">
            {sorted.map(l => (
              <ListingCard key={l.id} listing={l} onClick={openListing} faved={faves.includes(l.id)} onFav={toggleFav} />
            ))}
          </div>
        )}

        {view === 'map' && sorted.length > 0 && <MapPane listings={sorted} openListing={openListing} />}
      </section>
    </div>
  );
};

// Decorative "map" — gives the right interaction without needing real maps
const MapPane = ({ listings, openListing }) => {
  const [activeId, setActiveId] = React.useState(null);
  // Deterministic positions across the canvas based on listing id
  const positions = listings.map((l, i) => {
    const seed = l.id.charCodeAt(1) + l.id.charCodeAt(2) + i * 13;
    return {
      top:  20 + (seed * 7) % 60,
      left: 12 + (seed * 11) % 76,
    };
  });
  return (
    <div className="map-pane">
      <div className="map-canvas">
        {/* Decorative road lines */}
        <svg width="100%" height="100%" viewBox="0 0 800 600" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, opacity: 0.25 }}>
          <path d="M0,200 Q200,180 400,260 T800,300" stroke="#4D6149" strokeWidth="3" fill="none" />
          <path d="M0,420 Q300,400 500,440 T800,480" stroke="#4D6149" strokeWidth="2" fill="none" />
          <path d="M150,0 Q200,200 240,400 T280,600" stroke="#4D6149" strokeWidth="2" fill="none" />
          <path d="M580,0 Q540,200 560,400 T600,600" stroke="#4D6149" strokeWidth="2" fill="none" />
          <circle cx="180" cy="240" r="70" fill="#4D6149" opacity="0.05" />
          <circle cx="520" cy="420" r="100" fill="#4D6149" opacity="0.05" />
        </svg>
        {listings.map((l, i) => (
          <button
            key={l.id}
            className={`map-pin ${activeId === l.id ? 'active' : ''}`}
            style={{ top: `${positions[i].top}%`, left: `${positions[i].left}%` }}
            onMouseEnter={() => setActiveId(l.id)}
            onClick={() => openListing(l)}
          >
            {formatPrice(l.price)}
          </button>
        ))}
        <div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(255,255,255,0.92)', padding: '6px 12px', borderRadius: 999, fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>
          <Icon name="map-pin" size={12} /> Metro Vancouver
        </div>
      </div>
      <div className="map-list">
        {listings.map(l => (
          <div
            key={l.id}
            onMouseEnter={() => setActiveId(l.id)}
            style={{
              display: 'grid',
              gridTemplateColumns: '120px 1fr',
              gap: 16,
              padding: 12,
              borderRadius: 'var(--radius-md)',
              border: '1px solid ' + (activeId === l.id ? 'var(--accent)' : 'var(--line)'),
              background: 'var(--bg-card)',
              cursor: 'pointer',
              transition: 'border-color var(--dur) var(--ease)',
            }}
            onClick={() => openListing(l)}
          >
            <div style={{ width: 120, height: 80, borderRadius: 6, overflow: 'hidden', background: 'var(--bg-soft)' }}>
              <img src={l.images[0]} alt={l.address} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
            <div>
              <div className="serif" style={{ fontSize: 19 }}>{formatFullPrice(l.price)}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{l.address}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{l.neighbourhood} · {l.city}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6 }}>
                {l.beds} bed · {l.baths} bath · {l.sqft.toLocaleString()} sqft
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
window.MapPane = MapPane;

window.ListingsPage = ListingsPage;
