// screens-flow.jsx — Product detail, Cart, Checkout, Confirmation
const TAX_RATE = 0.095; // KS state + Leavenworth local (est.)

/* ───────────── PRODUCT DETAIL ───────────── */
function ProductScreen({ set, t, remaining, inCart, onBack, onAdd, cartCount, goCart }) {
  const out = remaining <= 0;
  const clamp = (n) => Math.max(1, Math.min(remaining || 1, n));
  const [packs, setPacks] = React.useState(clamp(3));
  const line = packLine(set, packs, t.markup);
  const [added, setAdded] = React.useState(false);

  function add() {
    if (out) return;
    onAdd(set.id, packs);
    setAdded(true);
    setTimeout(() => setAdded(false), 1400);
  }

  return (
    <div className="screen-push anim-in">
      <PushHeader title="" onBack={onBack} trailing={
        <button onClick={goCart} style={{ width: 40, height: 40, borderRadius: 9999, border: 'none', background: 'var(--surface)', boxShadow: 'var(--shadow-sm)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--ink)', position: 'relative' }}>
          <Icon name="cart" size={20} />
          {cartCount > 0 && <span style={{ position: 'absolute', top: -4, right: -4, minWidth: 18, height: 18, padding: '0 4px', borderRadius: 9999, background: 'var(--accent)', color: 'var(--on-accent)', fontFamily: 'var(--ff-mono)', fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{cartCount}</span>}
        </button>
      } />
      <div className="scroll" style={{ paddingBottom: 120 }}>
        {/* hero pack */}
        <div style={{ display: 'flex', justifyContent: 'center', padding: '6px 0 22px', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(60% 50% at 50% 38%, ${set.c1}26, transparent 70%)` }} />
          <div style={{ filter: 'drop-shadow(0 24px 30px rgba(34,29,22,0.28))', position: 'relative' }}>
            <PackArt set={set} w={186} h={250} />
          </div>
        </div>

        <div style={{ padding: '0 20px' }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
            <span className="kicker" style={{ alignSelf: 'center' }}>{set.era}</span>
            <HypeBadge hype={set.hype} />
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 34, letterSpacing: '-0.025em', lineHeight: 0.98 }}>{set.name}</div>
          <p className="muted" style={{ fontSize: 14.5, lineHeight: 1.45, marginTop: 10 }}>{set.blurb}</p>

          {/* chase + price row */}
          <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
            <div className="card hairline" style={{ flex: 1, padding: 14 }}>
              <div className="kicker" style={{ fontSize: 9.5, marginBottom: 6 }}>Chase card</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontWeight: 700, fontSize: 15 }}>
                <Icon name="star" size={16} fill color="var(--gold)" />{set.chase}
              </div>
            </div>
            <div className="card hairline" style={{ flex: 1, padding: 14 }}>
              <div className="kicker" style={{ fontSize: 9.5, marginBottom: 6 }}>Per pack</div>
              <PriceTag set={set} markup={t.markup} />
            </div>
          </div>

          {/* fair markup note */}
          <div style={{ marginTop: 12, padding: '12px 14px', borderRadius: 14, background: 'color-mix(in oklab, var(--good) 8%, var(--surface))', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <Icon name="shield" size={18} color="var(--good)" />
            <div style={{ fontSize: 12.5, lineHeight: 1.4, color: 'var(--ink-2)' }}>
              Fair <b style={{ color: 'var(--ink)' }}>+{Math.round(t.markup * 100)}% over MSRP</b>. A scalper would ask {money(set.msrp * 2)}+ for this pack.
            </div>
          </div>

          {/* stock */}
          <div style={{ marginTop: 18 }}><StockMeter stock={Math.max(0, remaining)} /></div>
          {inCart > 0 && (
            <div style={{ marginTop: 10, padding: '9px 13px', borderRadius: 12, background: 'color-mix(in oklab, var(--accent) 10%, var(--surface))', display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>
              <Icon name="cart" size={15} color="var(--accent)" />
              <span><b style={{ color: 'var(--ink)' }}>{inCart} pack{inCart > 1 ? 's' : ''}</b> already in your order</span>
              <button onClick={goCart} style={{ marginLeft: 'auto', border: 'none', background: 'none', color: 'var(--accent)', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'var(--ff-ui)' }}>View</button>
            </div>
          )}

          {/* bundle picker */}
          <div className="kicker" style={{ margin: '22px 0 10px' }}>Choose your bundle</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, opacity: out ? 0.5 : 1, pointerEvents: out ? 'none' : 'auto' }}>
            {BUNDLES.map(b => {
              const on = packs === b.packs;
              const tooMany = b.packs > remaining;
              return (
                <button key={b.packs} disabled={tooMany} onClick={() => setPacks(b.packs)} style={{
                  border: 'none', cursor: tooMany ? 'not-allowed' : 'pointer', borderRadius: 14, padding: '12px 4px', textAlign: 'center',
                  background: on ? 'var(--ink)' : 'var(--surface)', color: on ? 'var(--paper)' : 'var(--ink)',
                  boxShadow: on ? 'none' : 'inset 0 0 0 1px var(--line)', transition: 'all .14s', opacity: tooMany ? 0.35 : 1,
                }}>
                  <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 20 }}>{b.packs}</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 9, opacity: 0.7, marginTop: 2 }}>{b.off > 0 ? `-${Math.round(b.off * 100)}%` : 'pack' + (b.packs > 1 ? 's' : '')}</div>
                </button>
              );
            })}
          </div>

          {/* fine control */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 16, opacity: out ? 0.5 : 1, pointerEvents: out ? 'none' : 'auto' }}>
            <span className="muted" style={{ fontSize: 13.5, fontWeight: 600 }}>Exact quantity</span>
            <Stepper value={packs} onChange={setPacks} min={1} max={Math.max(1, remaining)} />
          </div>
          {line.off > 0 && (
            <div style={{ marginTop: 12, fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--good)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check" size={14} color="var(--good)" sw={2.6} /> Bundle saving applied — {money((fairPrice(set.msrp, t.markup) - line.per) * packs)} off
            </div>
          )}
        </div>
      </div>

      {/* sticky add bar */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 20px 30px', background: 'color-mix(in oklab, var(--paper) 88%, transparent)', backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)', boxShadow: '0 -0.5px 0 var(--line)', display: 'flex', alignItems: 'center', gap: 14 }}>
        {out ? (
          <button className="btn btn-soft btn-block" style={{ flex: 1 }} onClick={goCart}>
            {inCart > 0 ? `All ${inCart} reserved · view order` : 'Sold out'}
          </button>
        ) : (
          <>
            <div>
              <div className="kicker" style={{ fontSize: 9.5 }}>{packs} pack{packs > 1 ? 's' : ''}</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 26 }}>{money(line.total)}</div>
            </div>
            <button className="btn btn-accent btn-block" style={{ flex: 1 }} onClick={add}>
              {added ? <><Icon name="check" size={20} color="var(--on-accent)" sw={2.6} /> Added</> : <>Add to order</>}
            </button>
          </>
        )}
      </div>
    </div>
  );
}

/* ───────────── CART ───────────── */
function CartScreen({ cart, t, updateQty, goCheckout, goShop, onBack }) {
  const entries = Object.entries(cart).filter(([, p]) => p > 0);
  const lines = entries.map(([id, packs]) => ({ set: setById(id), packs, ...packLine(setById(id), packs, t.markup) }));
  const subtotal = lines.reduce((s, l) => s + l.total, 0);
  const tax = subtotal * TAX_RATE;
  const total = subtotal + tax;
  const packTotal = lines.reduce((s, l) => s + l.packs, 0);
  const scalper = lines.reduce((s, l) => s + l.set.msrp * 2 * l.packs, 0);

  if (entries.length === 0) {
    return (
      <div className="screen-push anim-in">
        <PushHeader title="Cart" onBack={onBack} />
        <div className="scroll" style={{ padding: '40px 20px', textAlign: 'center' }}>
          <div style={{ width: 76, height: 76, borderRadius: 9999, background: 'var(--surface)', boxShadow: 'var(--shadow-sm)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px', color: 'var(--ink-3)' }}>
            <Icon name="cart" size={32} />
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 20 }}>No packs yet</div>
          <p className="muted" style={{ fontSize: 14, margin: '8px 0 20px' }}>Reserve from this week's drop before the Sunday cutoff.</p>
          <button className="btn btn-accent" onClick={goShop}>Browse packs</button>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-push anim-in">
      <PushHeader title={`Cart · ${packTotal} ${packTotal === 1 ? 'pack' : 'packs'}`} onBack={onBack} />
      <div className="scroll" style={{ paddingBottom: 24 }}>

      <div style={{ padding: '8px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {lines.map(l => (
          <div key={l.set.id} className="card hairline" style={{ padding: 12, display: 'flex', gap: 14, alignItems: 'center' }}>
            <PackArt set={l.set} w={58} h={78} sheen={false} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 16, letterSpacing: '-0.01em' }}>{l.set.name}</div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{money(l.per)}/pack{l.off > 0 ? ` · -${Math.round(l.off*100)}%` : ''}</div>
              <div style={{ marginTop: 10 }}><Stepper value={l.packs} onChange={(v) => updateQty(l.set.id, v)} min={0} max={l.set.stock} /></div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 17 }}>{money(l.total)}</div>
            </div>
          </div>
        ))}
      </div>

      {/* fair pricing reassurance */}
      <div style={{ padding: '14px 20px 0' }}>
        <div style={{ padding: '12px 14px', borderRadius: 14, background: 'color-mix(in oklab, var(--good) 9%, var(--surface))', display: 'flex', gap: 10, alignItems: 'center' }}>
          <Icon name="shield" size={20} color="var(--good)" />
          <div style={{ fontSize: 12.5, lineHeight: 1.35, color: 'var(--ink-2)' }}>
            You're paying <b style={{ color: 'var(--ink)' }}>{money(subtotal)}</b> — about <b style={{ color: 'var(--good)' }}>{money(scalper - subtotal)} less</b> than scalper rates.
          </div>
        </div>
      </div>

      {/* summary */}
      <div style={{ padding: '16px 20px 0' }}>
        <div className="card" style={{ padding: 16 }}>
          {[['Subtotal', money(subtotal)], [`Sales tax · KS (est. ${(TAX_RATE*100).toFixed(1)}%)`, money(tax)], ['Delivery', 'Free on post']].map(([k, v], i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14, color: 'var(--ink-2)' }}>
              <span>{k}</span><span style={{ fontFamily: 'var(--ff-mono)', color: i === 2 ? 'var(--good)' : 'var(--ink)' }}>{v}</span>
            </div>
          ))}
          <hr className="divider" style={{ margin: '10px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontWeight: 700, fontSize: 16 }}>Total</span>
            <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 26 }}>{money(total)}</span>
          </div>
        </div>
      </div>

      {/* checkout */}
      <div style={{ padding: '18px 20px 30px' }}>
        <button className="btn btn-accent btn-block" onClick={() => goCheckout(total, packTotal)}>
          Choose delivery <Icon name="arrowR" size={19} color="var(--on-accent)" sw={2.4} />
        </button>
      </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProductScreen, CartScreen, TAX_RATE });
