// Agora Browse — dense filter rail + product grid.

const Browse = ({ route, setRoute, watchlist, toggleWatch }) => {
  const data = window.AG_DATA;
  const [sort, setSort] = useState('newest');
  const [view, setView] = useState('grid');
  const [activeCat, setActiveCat] = useState(route.cat || 'all');
  const [activeBrands, setActiveBrands] = useState(new Set(route.brand ? [route.brand] : []));
  const [conds, setConds] = useState(new Set());
  const [cities, setCities] = useState(new Set());
  const [priceRange, setPriceRange] = useState([0, 20000]);
  const [offersOnly, setOffersOnly] = useState(false);
  const [newOnly, setNewOnly] = useState(false);

  useEffect(()=>{ setActiveCat(route.cat || 'all'); }, [route.cat]);

  const cat = data.categories.find(c => c.id === activeCat);

  // Filter
  let items = data.items;
  if (activeCat !== 'all') items = items.filter(i => i.cat === activeCat);
  if (activeBrands.size) items = items.filter(i => activeBrands.has(i.brand));
  if (conds.size) items = items.filter(i => conds.has(i.cond));
  if (cities.size) items = items.filter(i => cities.has(i.city));
  if (offersOnly) items = items.filter(i => i.acceptOffers);
  if (newOnly) items = items.filter(i => i.new);
  items = items.filter(i => i.eur >= priceRange[0] && i.eur <= priceRange[1]);

  // Sort
  const sorted = [...items].sort((a,b)=>{
    if (sort==='price-low') return a.eur - b.eur;
    if (sort==='price-high') return b.eur - a.eur;
    if (sort==='watched') return b.watchers - a.watchers;
    return 0; // newest = original order
  });

  const allCities = [...new Set(data.items.map(i => i.city))];
  const allConds  = ['New','Excellent','Very Good','Good'];

  return (
    <div className="ag-shell ag-shell--wide" style={{ display:'flex', gap: 36, padding:'32px 32px 80px' }}>
      {/* ============== LEFT FILTER RAIL ============== */}
      <aside style={{ width: 240, flexShrink: 0 }}>
        <div className="ag-eyebrow">Filter</div>

        <FilterGroup title="Category">
          <div className="ag-col ag-gap-2" style={{ marginTop: 10 }}>
            {data.categories.map(c => (
              <span key={c.id} onClick={()=>setActiveCat(c.id)}
                style={{ cursor:'pointer', fontSize: 13, color: activeCat===c.id ? 'var(--ag-ink)':'var(--ap-fg-muted)', fontWeight: activeCat===c.id ? 600 : 400 }}>
                {c.label}
                <span className="ag-num" style={{ fontSize: 11, color:'var(--ap-fg-faint)', marginLeft: 6 }}>
                  {data.items.filter(it => c.id==='all' || it.cat===c.id).length}
                </span>
              </span>
            ))}
          </div>
        </FilterGroup>

        <FilterGroup title="Brand">
          <input className="ag-input ag-input--bare" placeholder="Search brand…" style={{ height: 32, fontSize: 12, marginTop: 6 }}/>
          <div className="ag-col ag-gap-2" style={{ marginTop: 12 }}>
            {data.brands.slice(0, 8).map(b => (
              <label key={b} className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
                <Check on={activeBrands.has(b)} onToggle={()=>{
                  const ns = new Set(activeBrands);
                  ns.has(b) ? ns.delete(b) : ns.add(b);
                  setActiveBrands(ns);
                }}/>
                <span>{b}</span>
                <span className="ag-num" style={{ fontSize: 11, color:'var(--ap-fg-faint)', marginLeft:'auto' }}>
                  {data.items.filter(i=>i.brand===b).length}
                </span>
              </label>
            ))}
            <span className="ag-label" style={{ fontSize: 10, color:'var(--ap-fg-muted)', cursor:'pointer', marginTop: 4 }}>Show all 32 brands +</span>
          </div>
        </FilterGroup>

        <FilterGroup title="Price (EUR)">
          <div className="ag-flex ag-gap-2" style={{ marginTop: 10 }}>
            <input className="ag-input ag-input--bare ag-mono" placeholder="0" defaultValue={priceRange[0]} style={{ height: 32, fontSize: 12 }} onBlur={e=>setPriceRange([+e.target.value||0, priceRange[1]])}/>
            <input className="ag-input ag-input--bare ag-mono" placeholder="20000" defaultValue={priceRange[1]} style={{ height: 32, fontSize: 12 }} onBlur={e=>setPriceRange([priceRange[0], +e.target.value||20000])}/>
          </div>
          <div style={{ marginTop: 10, height: 32, position:'relative' }}>
            {/* mini histogram */}
            <div style={{ position:'absolute', inset:'auto 0 0 0', height: 24, display:'flex', alignItems:'flex-end', gap: 2 }}>
              {[3,5,9,12,18,22,16,11,7,4,3,2,1,2,1,1,0,0,1,1].map((n, i) => (
                <div key={i} style={{ flex:1, background:'var(--ap-bg-4)', height: `${Math.min(100, n*5)}%`, borderRadius: 1 }}/>
              ))}
            </div>
            <div style={{ position:'absolute', left:0, right:0, bottom: -6, height: 1, background:'var(--ag-ink)' }}/>
          </div>
        </FilterGroup>

        <FilterGroup title="Condition">
          <div className="ag-col ag-gap-2" style={{ marginTop: 10 }}>
            {allConds.map(c => (
              <label key={c} className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
                <Check on={conds.has(c)} onToggle={()=>{
                  const ns = new Set(conds);
                  ns.has(c) ? ns.delete(c) : ns.add(c);
                  setConds(ns);
                }}/>
                <span>{c}</span>
              </label>
            ))}
          </div>
        </FilterGroup>

        <FilterGroup title="Ships from">
          <div className="ag-col ag-gap-2" style={{ marginTop: 10 }}>
            {allCities.map(c => (
              <label key={c} className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
                <Check on={cities.has(c)} onToggle={()=>{
                  const ns = new Set(cities);
                  ns.has(c) ? ns.delete(c) : ns.add(c);
                  setCities(ns);
                }}/>
                <span>{c}</span>
              </label>
            ))}
          </div>
        </FilterGroup>

        <FilterGroup title="Listing">
          <div className="ag-col ag-gap-2" style={{ marginTop: 10 }}>
            <label className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
              <Check on={newOnly} onToggle={()=>setNewOnly(!newOnly)}/><span>New this week</span>
            </label>
            <label className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
              <Check on={offersOnly} onToggle={()=>setOffersOnly(!offersOnly)}/><span>Accepts offers</span>
            </label>
            <label className="ag-flex ag-gap-2" style={{ alignItems:'center', cursor:'pointer', fontSize: 13 }}>
              <Check on={false} onToggle={()=>{}}/><span>New with tags</span>
            </label>
          </div>
        </FilterGroup>
      </aside>

      {/* ============== MAIN ============== */}
      <section style={{ flex: 1, minWidth: 0 }}>
        <div className="ag-flex ag-gap-3" style={{ alignItems:'baseline' }}>
          <div className="ag-eyebrow">{cat?.label || 'Everything'}</div>
          <span className="ag-num" style={{ fontSize: 11, color:'var(--ap-fg-faint)' }}>·</span>
          <span className="ag-mono" style={{ fontSize: 11, color:'var(--ap-fg-muted)' }}>{sorted.length} of {data.items.length} listings</span>
        </div>
        <h1 className="ag-h1" style={{ marginTop: 10, fontSize: 40 }}>{cat?.label || 'Everything'}</h1>
        <div style={{ maxWidth: 620, marginTop: 12, fontSize: 14, color:'var(--ap-fg-muted)' }}>
          {cat?.id === 'bags' ? 'Authenticated handbags from 1,284 private sellers worldwide. Every piece inspected at one of three hubs before it ships.' :
           cat?.id === 'vintage' ? 'Archive and runway pieces with documented provenance.' :
           'Curated, authenticated, shipped DDP.'}
        </div>

        {/* Active filter chips + sort row */}
        <div className="ag-between" style={{ marginTop: 28, paddingTop: 18, borderTop:'1px solid var(--ap-border)' }}>
          <div className="ag-flex ag-gap-2" style={{ flexWrap:'wrap' }}>
            {activeBrands.size > 0 && [...activeBrands].map(b => (
              <span key={b} className="ag-chip ag-chip--active">
                {b} <Icon name="x" size={11} onClick={()=>{ const ns = new Set(activeBrands); ns.delete(b); setActiveBrands(ns); }}/>
              </span>
            ))}
            {newOnly && <span className="ag-chip ag-chip--active">New this week <Icon name="x" size={11} onClick={()=>setNewOnly(false)}/></span>}
            {offersOnly && <span className="ag-chip ag-chip--active">Accepts offers <Icon name="x" size={11} onClick={()=>setOffersOnly(false)}/></span>}
            {(activeBrands.size > 0 || newOnly || offersOnly) && (
              <span className="ag-label" style={{ fontSize: 10, color:'var(--ap-fg-muted)', cursor:'pointer', alignSelf:'center', marginLeft: 6 }} onClick={()=>{ setActiveBrands(new Set()); setNewOnly(false); setOffersOnly(false); }}>Clear all</span>
            )}
          </div>
          <div className="ag-flex ag-gap-4" style={{ alignItems:'center' }}>
            <div className="ag-flex ag-gap-2">
              <span className="ag-label" style={{ color:'var(--ap-fg-muted)' }}>Sort</span>
              <select value={sort} onChange={e=>setSort(e.target.value)} style={{ border:0, background:'transparent', fontFamily:'var(--ag-font-sans)', fontSize: 12, fontWeight: 600, letterSpacing:'0.06em', textTransform:'uppercase', cursor:'pointer' }}>
                <option value="newest">Newest</option>
                <option value="price-low">Price ↑</option>
                <option value="price-high">Price ↓</option>
                <option value="watched">Most watched</option>
              </select>
            </div>
            <div className="ag-flex">
              <span onClick={()=>setView('grid')} style={{ width: 30, height: 30, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color: view==='grid' ? 'var(--ag-ink)':'var(--ap-fg-faint)' }}><Icon name="grid" size={14}/></span>
              <span onClick={()=>setView('large')} style={{ width: 30, height: 30, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color: view==='large' ? 'var(--ag-ink)':'var(--ap-fg-faint)' }}><Icon name="cards" size={14}/></span>
              <span onClick={()=>setView('list')} style={{ width: 30, height: 30, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color: view==='list' ? 'var(--ag-ink)':'var(--ap-fg-faint)' }}><Icon name="list" size={14}/></span>
            </div>
          </div>
        </div>

        {/* GRID */}
        {view === 'list' ? (
          <div style={{ marginTop: 16 }}>
            {sorted.map(it => (
              <ListRow key={it.id} item={it} onClick={()=>setRoute({ name:'product', id: it.id })} watched={watchlist.has(it.id)} onToggleWatch={()=>toggleWatch(it.id)}/>
            ))}
          </div>
        ) : (
          <div style={{
            marginTop: 16,
            display:'grid',
            gridTemplateColumns: view==='large' ? 'repeat(3, 1fr)' : 'repeat(4, 1fr)',
            gap: 1, background:'var(--ap-border)',
          }}>
            {sorted.map(it => (
              <div key={it.id} style={{ background:'#fff' }} onClick={()=>setRoute({ name:'product', id: it.id })}>
                <GridCard item={it} watched={watchlist.has(it.id)} onToggleWatch={()=>toggleWatch(it.id)} large={view==='large'}/>
              </div>
            ))}
          </div>
        )}

        <div className="ag-center" style={{ marginTop: 56, padding:'24px 0', borderTop:'1px solid var(--ap-border)' }}>
          <button className="ag-btn ag-btn--ghost">Load 200 more <Icon name="arrow-right" size={12}/></button>
        </div>
      </section>
    </div>
  );
};

const FilterGroup = ({ title, children }) => {
  const [open, setOpen] = useState(true);
  return (
    <div style={{ borderTop:'1px solid var(--ap-border)', padding:'18px 0', marginTop: 8 }}>
      <div className="ag-between" onClick={()=>setOpen(!open)} style={{ cursor:'pointer' }}>
        <div className="ag-label" style={{ fontSize: 11 }}>{title}</div>
        <Icon name={open ? 'minus' : 'plus'} size={12}/>
      </div>
      {open && children}
    </div>
  );
};

const Check = ({ on, onToggle }) => (
  <span onClick={onToggle} style={{
    width: 14, height: 14, border:'1px solid '+(on?'var(--ag-ink)':'var(--ap-border)'),
    background: on ? 'var(--ag-ink)' : '#fff',
    borderRadius: 2, display:'inline-flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink: 0,
  }}>
    {on && <Icon name="check" size={9} stroke={3} style={{ color:'#fff' }}/>}
  </span>
);

const GridCard = ({ item, watched, onToggleWatch, large = false }) => {
  const [hover, setHover] = useState(false);
  return (
    <div onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)} style={{ cursor:'pointer' }}>
      <ProductTile item={item}>
        <div className="ag-tile__top">
          <div className="ag-flex ag-gap-1">
            {item.new && <span className="ag-tag ag-tag--red">New</span>}
            {item.acceptOffers && <span className="ag-tag ag-tag--bone">Offers</span>}
          </div>
          <div className={`ag-heart${watched?' ag-heart--active':''}`} onClick={(e)=>{ e.stopPropagation(); onToggleWatch(); }}>
            <Icon name={watched?'heart-fill':'heart'} size={14}/>
          </div>
        </div>
        <div className="ag-tile__bot">
          <span className="ag-tag ag-tag--auth" style={{ background:'rgba(255,255,255,0.95)' }}><Icon name="shield" size={9} stroke={2}/>&nbsp;Auth</span>
          {item.watchers > 30 && (
            <span className="ag-mono" style={{ color:'#fff', fontSize: 10, background:'rgba(0,0,0,0.4)', padding:'2px 7px', borderRadius: 9999 }}>{item.watchers} watching</span>
          )}
        </div>
      </ProductTile>
      <div style={{ padding: large ? '16px 18px 20px' : '12px 14px 16px' }}>
        <div className="ag-between" style={{ alignItems:'baseline' }}>
          <div className="ag-eyebrow-ink">{item.brand}</div>
          <div className="ag-num" style={{ fontSize: large ? 14 : 13, fontWeight: 600 }}>€{item.eur.toLocaleString()}</div>
        </div>
        <div style={{ color:'var(--ap-fg-muted)', fontSize: 12, marginTop: 4, lineHeight: 1.35, height: 32, overflow:'hidden' }}>{item.title}</div>
        <div className="ag-between" style={{ marginTop: 8 }}>
          <RouteLine from={item.city} to="Berlin" compact/>
          <span className="ag-mono" style={{ fontSize: 10, color:'var(--ap-fg-faint)' }}>{item.cond}</span>
        </div>
      </div>
    </div>
  );
};

const ListRow = ({ item, onClick, watched, onToggleWatch }) => (
  <div onClick={onClick} className="ag-flex ag-gap-6" style={{
    alignItems:'center', padding:'18px 0', borderBottom:'1px solid var(--ap-border)', cursor:'pointer',
  }}>
    <div style={{ width: 92, height: 92, flexShrink:0 }}>
      <ProductTile item={item} square showWatermark={false}/>
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div className="ag-flex ag-gap-2" style={{ alignItems:'center' }}>
        <div className="ag-eyebrow-ink">{item.brand}</div>
        {item.new && <span className="ag-tag ag-tag--red">New</span>}
        <span className="ag-tag ag-tag--auth"><Icon name="shield" size={9} stroke={2}/>&nbsp;Auth</span>
      </div>
      <div style={{ marginTop: 4, fontSize: 15, color:'var(--ag-ink)' }}>{item.title}</div>
      <div className="ag-flex ag-gap-4" style={{ marginTop: 8, color:'var(--ap-fg-muted)', fontSize: 12 }}>
        <span>Condition · {item.cond}</span>
        <span>Year · {item.year}</span>
        <RouteLine from={item.city} to="Berlin" compact/>
        <span>{item.watchers} watching</span>
      </div>
    </div>
    <div style={{ textAlign:'right' }}>
      <div className="ag-num" style={{ fontSize: 20, fontWeight: 600 }}>€{item.eur.toLocaleString()}</div>
      {item.acceptOffers && <div className="ag-eyebrow" style={{ marginTop: 4 }}>Or make an offer</div>}
      <div className="ag-flex ag-gap-2" style={{ marginTop: 10, justifyContent:'flex-end' }}>
        <button className="ag-btn ag-btn--sm ag-btn--ghost" onClick={(e)=>{ e.stopPropagation(); onToggleWatch(); }}>
          <Icon name={watched?'heart-fill':'heart'} size={12}/> {watched ? 'Saved' : 'Save'}
        </button>
        <button className="ag-btn ag-btn--sm">View piece</button>
      </div>
    </div>
  </div>
);

window.Browse = Browse;
