// Lists / My Hub page with filtering & sorting

const AGE_BAND_LABELS = {
  'all':  'All ages',
  'pre':  'Pre-baby',
  '0-1':  '0–1',
  '1-3':  '1–3',
  '3-5':  '3–5',
  '5-8':  '5–8',
  '8-12': '8–12',
};

function ListsPage({ lists, productMap, onOpenList, onCreateList, savedIds, onShare }) {
  const [tab, setTab] = useState('explore');
  const [ageBand, setAgeBand] = useState('all');
  const [sort, setSort] = useState('trending'); // trending | followers | newest | size

  const mine = lists.filter(l => l.isMine);
  const followed = lists.filter(l => l.isFollowed);
  const explore = lists.filter(l => !l.isMine);

  let visible = tab === 'mine' ? mine : tab === 'followed' ? followed : explore;
  if (ageBand !== 'all') visible = visible.filter(l => l.ageBand === ageBand);

  visible = [...visible].sort((a, b) => {
    if (sort === 'trending') return (b.trending ? 1 : 0) - (a.trending ? 1 : 0) || (b.followers || 0) - (a.followers || 0);
    if (sort === 'followers') return (b.followers || 0) - (a.followers || 0);
    if (sort === 'size') return (b.productIds.length || 0) - (a.productIds.length || 0);
    return 0;
  });

  const trendingExplore = explore.filter(l => l.trending).slice(0, 4);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-eyebrow">My Hub</div>
          <h1 className="page-title">Lists, registries,<br/><em>made beautifully.</em></h1>
          <p className="page-sub">Curate gear for the baby. Build a birthday list grandparents can actually use. Follow the parents whose taste you trust.</p>
        </div>
        <div className="page-head-action">
          <button className="btn btn-ghost" onClick={onCreateList} style={{ width: 'auto', padding: '12px 18px' }}>
            <span>New list</span><span className="arrow">+</span>
          </button>
        </div>
      </div>

      {tab === 'explore' && trendingExplore.length > 0 && (
        <section style={{ marginBottom: 56 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 20 }}>
            <h2 style={{ fontFamily: 'var(--serif)', fontSize: 28, letterSpacing: '-0.02em', margin: 0, fontWeight: 400 }}>
              Trending this week
            </h2>
            <span style={{ fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
              {trendingExplore.length} lists
            </span>
          </div>
          <div className="trending-row">
            {trendingExplore.map(l => (
              <TrendingListCard key={l.id} list={l} productMap={productMap} onOpen={() => onOpenList(l)} />
            ))}
          </div>
        </section>
      )}

      <div className="lists-tabs">
        <button className={`lists-tab${tab === 'explore' ? ' is-active' : ''}`} onClick={() => setTab('explore')}>
          Explore<span className="count">{explore.length}</span>
        </button>
        <button className={`lists-tab${tab === 'mine' ? ' is-active' : ''}`} onClick={() => setTab('mine')}>
          My lists<span className="count">{mine.length}</span>
        </button>
        <button className={`lists-tab${tab === 'followed' ? ' is-active' : ''}`} onClick={() => setTab('followed')}>
          Following<span className="count">{followed.length}</span>
        </button>
      </div>

      <div className="lists-filterbar">
        <div className="lists-chips">
          {Object.keys(AGE_BAND_LABELS).map(k => (
            <button
              key={k}
              className={`lists-chip${ageBand === k ? ' is-current' : ''}`}
              onClick={() => setAgeBand(k)}
            >{AGE_BAND_LABELS[k]}</button>
          ))}
        </div>
        <div className="lists-sort">
          <span style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Sort</span>
          <select value={sort} onChange={(e) => setSort(e.target.value)} className="lists-sort-select">
            <option value="trending">Trending</option>
            <option value="followers">Most followed</option>
            <option value="size">Most items</option>
          </select>
        </div>
      </div>

      {visible.length === 0 ? (
        <div className="empty">
          <h3 className="empty-title">No lists match</h3>
          <p>Try a different age band or tab.</p>
        </div>
      ) : (
        <div className="lists-grid">
          {tab === 'mine' && (
            <button className="list-create" onClick={onCreateList}>
              <span className="list-create-plus">+</span>
              <span>Start a new list</span>
            </button>
          )}
          {visible.map(l => (
            <ListCard key={l.id} list={l} productMap={productMap} onOpen={() => onOpenList(l)} />
          ))}
        </div>
      )}
    </div>
  );
}

function ListCard({ list, productMap, onOpen }) {
  const products = (list.productIds || []).map(id => productMap[id]).filter(Boolean).slice(0, 3);
  const kindBadge = list.kind === 'registry' || list.public ? 'Registry'
    : list.kind === 'partner' ? 'Shared' : null;
  return (
    <article className="list-card" onClick={onOpen}>
      <div className="list-cover">
        {list.trending && <span className="list-trending">Trending</span>}
        {kindBadge && !list.trending && <span className="list-trending list-kind-badge">{kindBadge}</span>}
        {products.length > 0 ? (
          <>
            {products.map((p, i) => <img key={p.id} src={p.img} alt={p.name} loading="lazy" />)}
            {Array.from({ length: Math.max(0, 3 - products.length) }).map((_, i) => (
              <div key={'e'+i} className="list-cover-empty"></div>
            ))}
          </>
        ) : (
          <div className="list-cover-empty" style={{ gridColumn: '1 / 3', gridRow: '1 / 3' }}>Empty list</div>
        )}
      </div>
      <h3 className="list-name">{list.name}</h3>
      <div className="list-meta">
        <span>{AGE_BAND_LABELS[list.ageBand] || ''}</span>
        <span className="dot" />
        <span>{list.productIds.length} items</span>
        <span className="dot" />
        <span>by {list.owner}</span>
      </div>
      {list.desc && <p className="list-desc">{list.desc}</p>}
      {list.followers > 0 && (
        <div className="list-foot">
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
          <span>{list.followers.toLocaleString()} followers</span>
        </div>
      )}
    </article>
  );
}

function TrendingListCard({ list, productMap, onOpen }) {
  const products = (list.productIds || []).map(id => productMap[id]).filter(Boolean).slice(0, 4);
  return (
    <article className="trending-card" onClick={onOpen}>
      <div className="trending-card-imgs">
        {products.map(p => <img key={p.id} src={p.img} alt="" loading="lazy" />)}
        {Array.from({ length: Math.max(0, 4 - products.length) }).map((_, i) => <div key={i} className="trending-card-imgs-empty" />)}
      </div>
      <div className="trending-card-body">
        <div style={{ fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 4 }}>
          {`${AGE_BAND_LABELS[list.ageBand]} · ${list.productIds.length} items`}
        </div>
        <h4 className="trending-card-title">{list.name}</h4>
        <div className="trending-card-meta">{`${list.followers.toLocaleString()} followers · by ${list.owner}`}</div>
      </div>
    </article>
  );
}

function ListDetailPage({ list, productMap, savedIds, claims = [], audience, onBack, onOpenProduct, onSave, onShare, onFollow, onClaim }) {
  const products = list.productIds.map(id => productMap[id]).filter(Boolean);
  const total = products.reduce((s, p) => s + p.price, 0);
  const isRegistry = list.kind === 'registry' || list.public;
  const claimByProductId = {};
  claims.forEach(c => { claimByProductId[c.productId] = c; });
  const kindLabel = list.kind === 'registry' || list.public
    ? 'Public registry'
    : list.kind === 'partner'
      ? 'Shared with partner'
      : list.isMine ? 'My list' : list.isFollowed ? 'Following' : 'Public list';
  const claimedCount = Object.keys(claimByProductId).length;
  return (
    <div className="page">
      <button onClick={onBack} className="btn btn-ghost" style={{ width: 'auto', padding: '8px 14px', marginBottom: 24, fontSize: 13 }}>
        <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span>
        <span>All lists</span>
      </button>

      <div className="list-detail-head">
        <div>
          <div className="page-eyebrow">{`${kindLabel}${list.trending ? ' · Trending' : ''}`}</div>
          <h1 className="page-title" style={{ fontSize: 'clamp(36px, 4vw, 48px)' }}>{list.name}</h1>
          {list.desc && <p className="page-sub">{list.desc}</p>}
          <div className="list-owner">
            <div className="avatar">{list.owner.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
            <span>by {list.owner}</span>
            <span style={{ width: 3, height: 3, background: 'currentColor', borderRadius: '50%' }} />
            <span>{AGE_BAND_LABELS[list.ageBand]}</span>
            <span style={{ width: 3, height: 3, background: 'currentColor', borderRadius: '50%' }} />
            <span>{products.length} items</span>
            <span style={{ width: 3, height: 3, background: 'currentColor', borderRadius: '50%' }} />
            <span>~ ${total.toLocaleString()} total</span>
            {list.followers > 0 && <><span style={{ width: 3, height: 3, background: 'currentColor', borderRadius: '50%' }} /><span>{list.followers.toLocaleString()} followers</span></>}
            {isRegistry && claimedCount > 0 && <><span style={{ width: 3, height: 3, background: 'currentColor', borderRadius: '50%' }} /><span>{claimedCount} claimed</span></>}
          </div>
        </div>
        <div className="page-head-action">
          {!list.isMine && (
            <button className="btn btn-ghost" onClick={() => onFollow(list.id)} style={{ width: 'auto', padding: '12px 18px' }}>
              <span>{list.isFollowed ? 'Following' : 'Follow list'}</span>
              <span className="arrow">{list.isFollowed ? '✓' : '+'}</span>
            </button>
          )}
          <button className="btn" onClick={() => onShare(list)} style={{ width: 'auto', padding: '12px 18px' }}>
            <span>Share</span><span className="arrow">→</span>
          </button>
        </div>
      </div>

      {isRegistry && list.isMine && claims.length > 0 && (
        <section className="registry-claims">
          <div className="registry-claims-head">
            <div>
              <div className="page-eyebrow" style={{ marginBottom: 4 }}>Notes from your people</div>
              <h2 style={{ fontFamily: 'var(--serif)', fontSize: 26, letterSpacing: '-0.02em', margin: 0, fontWeight: 400 }}>{claims.length} {claims.length === 1 ? 'gift' : 'gifts'} taken</h2>
            </div>
          </div>
          <ul className="registry-claims-list">
            {claims.map(c => {
              const p = productMap[c.productId];
              if (!p) return null;
              return (
                <li key={c.productId} className="registry-claim">
                  <img src={p.img} alt="" />
                  <div className="registry-claim-body">
                    <div className="registry-claim-name">{p.name}</div>
                    <div className="registry-claim-buyer">{c.buyerName}</div>
                    {c.note && <p className="registry-claim-note">&ldquo;{c.note}&rdquo;</p>}
                  </div>
                </li>
              );
            })}
          </ul>
        </section>
      )}

      {products.length === 0 ? (
        <div className="empty">
          <h3 className="empty-title">Nothing here yet</h3>
          <p>Find products and tap the heart, then add them to this list.</p>
        </div>
      ) : (
        <div className="grid">
          {products.map(p => {
            const claimed = claimByProductId[p.id];
            return (
              <div key={p.id} className={`registry-product${claimed ? ' is-claimed' : ''}`}>
                <ProductCard p={p} isSaved={savedIds.includes(p.id)} showPrice={true}
                  onOpen={(prod) => onOpenProduct(prod, products)} onSave={onSave} />
                {isRegistry && (
                  claimed ? (
                    <div className="registry-claimed-tag" title={claimed.note ? `“${claimed.note}” — ${claimed.buyerName}` : claimed.buyerName}>
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
                      <span>Taken by {claimed.buyerName}</span>
                    </div>
                  ) : !list.isMine ? (
                    <button className="registry-claim-btn" onClick={(e) => { e.stopPropagation(); onClaim && onClaim(p); }}>
                      <span>I'm getting this</span>
                      <span className="arrow">→</span>
                    </button>
                  ) : null
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.ListsPage = ListsPage;
window.ListDetailPage = ListDetailPage;
