// screens-tabs.jsx — Shop home, Sets browser, Account/Loyalty

// per-pack pricing w/ automatic volume discount (matches plan's bundle logic)
function packLine(set, packs, markup) {
  const off = packs >= 10 ? 0.08 : packs >= 5 ? 0.04 : 0;
  const per = fairPrice(set.msrp, markup) * (1 - off);
  return { per, off, total: per * packs };
}

/* ───────────── SHOP / HOME ───────────── */
function ShopHome({ t, cart, remaining, cutoff, openSet, goSets, cartCount, onCart, onBell, pulls, goWall, liveDelivery, openDelivery, ver = 3, lens, openScan, onCategoryQueued }) {
  const featured = SETS[0];
  const fresh = SETS.slice(1);
  const fair = fairPrice(featured.msrp, t.markup);
  const next = DELIVERY_DAYS[0];
  const d = ACTIVE_DELIVERY;
  const ahead = d.stops.findIndex(s => s.you) - d.stops.findIndex(s => s.state === 'active');

  return (
    <div className="fade-up">
      <BrandBar t={t} onBell={onBell} cartCount={cartCount} onCart={onCart} />

      {/* the shelves — Pokémon is open, the rest are queued in order */}
      <CategoryRail onQueued={onCategoryQueued} />
      <div style={{ padding: '10px 20px 16px' }}>
        <p className="muted" style={{ fontSize: 12.5, lineHeight: 1.4, margin: 0 }}>
          A game shop for {BRAND.place}, open on one shelf so far.
          <b style={{ color: 'var(--ink)' }}> {LEAD_CATEGORY.name} first</b> — packs, singles,
          and collection buys. The next shelf lands when sourcing does.
        </p>
      </div>

      {liveDelivery ? (
        /* LIVE — Rook is on the run */
        <button onClick={openDelivery} style={{ width: 'calc(100% - 40px)', margin: '8px 20px 18px', padding: '14px 16px', borderRadius: 18, background: 'var(--ink)', color: 'var(--paper)', display: 'flex', alignItems: 'center', gap: 13, border: 'none', cursor: 'pointer', textAlign: 'left', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(120% 100% at 100% 0%, color-mix(in oklab, var(--accent) 34%, transparent), transparent 60%)' }} />
          <div style={{ width: 40, height: 40, borderRadius: 11, background: 'color-mix(in oklab, var(--accent) 26%, transparent)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, position: 'relative' }}>
            <Icon name="truck" size={21} color="var(--paper)" />
            <span style={{ position: 'absolute', top: -3, right: -3, width: 11, height: 11, borderRadius: 9999, background: 'var(--accent)', boxShadow: '0 0 0 2px var(--ink)' }} />
          </div>
          <div style={{ flex: 1, lineHeight: 1.25, minWidth: 0, position: 'relative' }}>
            <div style={{ fontWeight: 700, fontSize: 14.5 }}>Rook is {ahead <= 0 ? 'at your stop' : ahead + ' stop' + (ahead > 1 ? 's' : '') + ' away'}</div>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, opacity: 0.72 }}>Out for delivery · your ETA ~4:14 PM</div>
          </div>
          <span style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 4, background: 'color-mix(in oklab, var(--paper) 16%, transparent)', padding: '8px 12px', borderRadius: 9999, fontWeight: 700, fontSize: 12.5, flexShrink: 0 }}>Track <Icon name="arrowR" size={14} color="var(--paper)" sw={2.6} /></span>
        </button>
      ) : (
        /* delivery strip */
        <div style={{ margin: '8px 20px 18px', padding: '12px 16px', borderRadius: 16, background: 'var(--ink)', color: 'var(--paper)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'color-mix(in oklab, var(--paper) 16%, transparent)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="truck" size={20} color="var(--paper)" />
          </div>
          <div style={{ flex: 1, lineHeight: 1.25, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Next delivery · {next.day}, {next.date}</div>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, opacity: 0.7, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Order by Sun 8 PM · 4–6 PM windows</div>
          </div>
          <span className="badge" style={{ background: cutoff.soon ? 'var(--gold)' : 'var(--accent)', color: 'var(--on-accent)', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5 }}>
            <Icon name="clock" size={11} color="var(--on-accent)" />{cutoff.label}
          </span>
        </div>
      )}

      {/* Lens — scan a foreign-language card */}
      {lens && <ScanEntry onOpen={openScan} />}

      {/* hero / this week's drop */}
      <div style={{ padding: '0 20px', marginBottom: 26 }}>
        <div className="kicker" style={{ marginBottom: 10 }}>This week's drop</div>
        <button onClick={() => openSet(featured)} className="card" style={{ width: '100%', textAlign: 'left', border: 'none', cursor: 'pointer', padding: 18, display: 'flex', gap: 16, overflow: 'hidden', position: 'relative', alignItems: 'center' }}>
          <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(120% 90% at 0% 0%, ${featured.c1}1f, transparent 60%)` }} />
          <PackArt set={featured} w={118} h={160} />
          <div style={{ position: 'relative', flex: 1 }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}><HypeBadge hype={featured.hype} /></div>
            <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 24, lineHeight: 0.98, letterSpacing: '-0.02em' }}>{featured.name}</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 6, lineHeight: 1.35 }}>{featured.blurb}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 12 }}>
              <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 22 }}>{money(fair)}</span>
              <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--ink-3)' }}>/ pack</span>
            </div>
          </div>
        </button>
      </div>

      {/* fresh drops rail */}
      <SectionHead kicker="In stock now" title="Fresh packs" action={ver >= 2 ? 'All sets' : undefined} onAction={ver >= 2 ? goSets : undefined} />
      <div className="rail" style={{ marginBottom: 26 }}>
        {fresh.map(s => {
          const f = fairPrice(s.msrp, t.markup);
          const left = remaining(s);
          const out = left <= 0;
          return (
            <button key={s.id} onClick={() => openSet(s)} style={{ width: 150, flexShrink: 0, textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}>
              <div style={{ position: 'relative' }}>
                <div className={out ? 'soldout' : ''}><PackArt set={s} w={150} h={196} /></div>
                <div style={{ position: 'absolute', top: 10, left: 10 }}>
                  {out ? <span className="badge" style={{ background: 'var(--ink)', color: 'var(--paper)' }}>Sold out</span> : <HypeBadge hype={s.hype} />}
                </div>
              </div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 700, fontSize: 15, marginTop: 10, letterSpacing: '-0.01em' }}>{s.name}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 3 }}>
                <span style={{ fontFamily: 'var(--ff-mono)', fontWeight: 700, fontSize: 14 }}>{money(f)}</span>
                <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, color: out ? 'var(--accent)' : left <= 15 ? 'var(--gold)' : 'var(--ink-3)' }}>{out ? 'reserved' : left + ' left'}</span>
              </div>
            </button>
          );
        })}
      </div>

      {/* community pulse — v3 */}
      {ver >= 3 && <>
      <SectionHead kicker="Around the post" title="Neighbors are pulling" action="The Wall" onAction={goWall} />
      <div className="rail" style={{ marginBottom: 26 }}>
        {(pulls || []).slice(0, 4).map(p => {
          const card = makeCard(p.setId, p.idx);
          const r = RARITY[card.rarity];
          return (
            <button key={p.id} onClick={goWall} style={{ width: 132, flexShrink: 0, textAlign: 'left', border: 'none', background: 'var(--surface)', boxShadow: 'var(--shadow-sm)', borderRadius: 16, padding: 12, cursor: 'pointer' }}>
              <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}><CardFace card={card} w={84} /></div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 9, fontWeight: 700, color: r.color, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{r.label}</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 14, letterSpacing: '-0.01em', marginTop: 1 }}>{card.name}</div>
              <div className="muted" style={{ fontSize: 10.5, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.who} · {p.when}</div>
            </button>
          );
        })}
      </div>
      </>}

      {/* trust band */}
      <div style={{ padding: '0 20px', marginBottom: 28 }}>
        <div className="card" style={{ padding: 18, background: 'var(--surface-2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Icon name="shield" size={22} color="var(--good)" />
            <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 17 }}>The no-scalper promise</div>
          </div>
          <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.45, margin: '0 0 14px' }}>
            We price a fair <b style={{ color: 'var(--ink)' }}>{Math.round(t.markup * 100)}% over MSRP</b> — just enough to cover sleeves, gas, and fees. Never resale-gouge. Built for Fort Leavenworth families.
          </p>
          <div style={{ display: 'flex', gap: 10 }}>
            {[['Pre-order', 'cal'], ['We deliver', 'truck'], ['You open', 'spark']].map(([label, icon], i) => (
              <div key={i} style={{ flex: 1, textAlign: 'center', padding: '12px 6px', borderRadius: 14, background: 'var(--surface)', boxShadow: 'inset 0 0 0 1px var(--line)' }}>
                <div style={{ color: 'var(--accent)', display: 'flex', justifyContent: 'center', marginBottom: 6 }}><Icon name={icon} size={20} /></div>
                <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em' }}>{i + 1}. {label.toUpperCase()}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ───────────── SETS BROWSER ───────────── */
function SetsScreen({ t, remaining, openSet, onCategoryQueued }) {
  const [filter, setFilter] = React.useState('All');
  const filters = ['All', 'Current', 'Last gen', 'Throwback'];
  const shelf = setsInCategory(LEAD_CATEGORY.id);
  const list = shelf.filter(s => filter === 'All' || s.era === filter);
  return (
    <div className="fade-up">
      <div style={{ padding: 'var(--top-pad) 20px 10px' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>{LEAD_CATEGORY.name} · the shelf</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 32, letterSpacing: '-0.025em', lineHeight: 1 }}>All sets</div>
      </div>
      <div style={{ paddingTop: 12 }}><CategoryRail onQueued={onCategoryQueued} /></div>
      <div className="rail" style={{ padding: '8px 20px 16px' }}>
        {filters.map(f => (
          <button key={f} className={'chip' + (filter === f ? ' on' : '')} onClick={() => setFilter(f)}>{f}</button>
        ))}
      </div>
      <div style={{ padding: '0 20px 8px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {list.map(s => {
          const f = fairPrice(s.msrp, t.markup);
          const left = remaining(s);
          const out = left <= 0;
          return (
            <button key={s.id} onClick={() => openSet(s)} className="card" style={{ display: 'flex', gap: 14, padding: 12, alignItems: 'center', border: 'none', cursor: 'pointer', textAlign: 'left' }}>
              <div className={out ? 'soldout' : ''}><PackArt set={s} w={74} h={100} sheen={false} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', gap: 6, marginBottom: 5, flexWrap: 'wrap' }}>
                  <span className="kicker" style={{ fontSize: 9.5 }}>{s.era}</span>
                  {out ? <span className="badge" style={{ background: 'var(--ink)', color: 'var(--paper)' }}>Sold out</span> : <HypeBadge hype={s.hype} />}
                </div>
                <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 18, letterSpacing: '-0.01em' }}>{s.name}</div>
                <div className="muted" style={{ fontSize: 12, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>Chase: {s.chase}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8 }}>
                  <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 18 }}>{money(f)}</span>
                  <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, color: 'var(--ink-3)', textDecoration: 'line-through' }}>{money(s.msrp)}</span>
                  <span style={{ marginLeft: 'auto', fontFamily: 'var(--ff-mono)', fontSize: 10.5, color: out ? 'var(--accent)' : left <= 15 ? 'var(--gold)' : 'var(--ink-3)' }}>{out ? 'reserved' : left + ' left'}</span>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ───────────── ACCOUNT / LOYALTY ───────────── */
function AccountScreen({ t, loyalty, orders, sub, setSub, goShop }) {
  const toGo = 10 - (loyalty % 10);
  const pct = ((loyalty % 10) / 10) * 100;
  return (
    <div className="fade-up">
      <div style={{ padding: 'var(--top-pad) 20px 10px' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>Your account</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 32, letterSpacing: '-0.025em', lineHeight: 1 }}>Hey, Jordan</div>
      </div>

      {/* loyalty card */}
      <div style={{ padding: '14px 20px 8px' }}>
        <div className="card" style={{ padding: 20, position: 'relative', overflow: 'hidden', background: 'var(--ink)', color: 'var(--paper)' }}>
          <div style={{ position: 'absolute', right: -20, top: -20, opacity: 0.12 }}><RookMark size={150} color="var(--paper)" /></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative' }}>
            <div>
              <div className="kicker" style={{ color: 'color-mix(in oklab, var(--paper) 65%, transparent)' }}>Pack club</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 22, marginTop: 4 }}>10th pack free</div>
            </div>
            <Icon name="spark" size={26} color="var(--gold)" fill />
          </div>
          <div style={{ display: 'flex', gap: 5, margin: '18px 0 10px', position: 'relative' }}>
            {Array.from({ length: 10 }).map((_, i) => (
              <div key={i} style={{ flex: 1, height: 8, borderRadius: 9999, background: i < (loyalty % 10) ? 'var(--gold)' : 'color-mix(in oklab, var(--paper) 18%, transparent)' }} />
            ))}
          </div>
          <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, opacity: 0.85, position: 'relative' }}>
            {toGo === 10 ? 'Buy 1 pack to start your card' : `${toGo} more pack${toGo > 1 ? 's' : ''} until a free one`}
          </div>
        </div>
      </div>

      {/* subscription */}
      <div style={{ padding: '8px 20px' }}>
        <div className="card hairline" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, background: 'color-mix(in oklab, var(--accent) 14%, var(--surface))', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: 'var(--accent)' }}>
            <Icon name="bell" size={22} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Monthly drop subscription</div>
            <div className="muted" style={{ fontSize: 12.5 }}>Auto-reserve your sets each release</div>
          </div>
          <button onClick={() => setSub(!sub)} aria-label="toggle subscription" style={{ width: 50, height: 30, borderRadius: 9999, border: 'none', cursor: 'pointer', background: sub ? 'var(--good)' : 'var(--line-2)', position: 'relative', transition: 'background .18s', flexShrink: 0 }}>
            <span style={{ position: 'absolute', top: 3, left: sub ? 23 : 3, width: 24, height: 24, borderRadius: 9999, background: '#fff', transition: 'left .18s', boxShadow: '0 1px 3px rgba(0,0,0,0.3)' }} />
          </button>
        </div>
      </div>

      {/* referral */}
      <div style={{ padding: '8px 20px' }}>
        <div className="card" style={{ padding: 16, background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="share" size={20} color="var(--accent)" />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Refer a neighbor</div>
            <div className="muted" style={{ fontSize: 12 }}>They get a free pack on order #3</div>
          </div>
          <code style={{ fontFamily: 'var(--ff-mono)', fontSize: 13, fontWeight: 700, padding: '7px 12px', borderRadius: 9, background: 'var(--surface)', boxShadow: 'inset 0 0 0 1px var(--line)', color: 'var(--accent)' }}>ROOK-J42</code>
        </div>
      </div>

      {/* order history */}
      <div style={{ padding: '18px 20px 8px' }}>
        <div className="kicker" style={{ marginBottom: 10 }}>Order history</div>
        {orders.length === 0 ? (
          <div className="card hairline" style={{ padding: 22, textAlign: 'center' }}>
            <div className="muted" style={{ fontSize: 13.5, marginBottom: 12 }}>No orders yet — your first drop is waiting.</div>
            <button className="btn btn-accent" onClick={goShop}>Browse this week's drop</button>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {orders.map(o => (
              <div key={o.id} className="card hairline" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: 'color-mix(in oklab, var(--good) 14%, var(--surface))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--good)', flexShrink: 0 }}>
                  <Icon name="receipt" size={20} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 14, fontFamily: 'var(--ff-mono)' }}>{o.id}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{o.packs} packs · {o.day}</div>
                </div>
                <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 16 }}>{money(o.total)}</div>
              </div>
            ))}
          </div>
        )}
      </div>
      <div style={{ height: 8 }} />
    </div>
  );
}

Object.assign(window, { packLine, ShopHome, SetsScreen, AccountScreen });
