/* AIWine — WINE DETAIL + CART (winery fulfilment rules mirror the website cart) */
function ShipHint({ g }) {
  const M = AIW.MARKET;
  if (g.blocked) return <div style={{ ...S.sans, fontSize: 12, color: 'var(--claret)', lineHeight: 1.45 }}>{g.blockReason}</div>;
  if (g.bottles >= M.fullCase && g.discPct) return <div style={{ ...S.sans, fontSize: 12, color: 'var(--green)' }}>Discovery Dozen ✓ · {Math.round(g.discPct * 100)}% off &amp; free delivery</div>;
  if (g.bottles >= g.freeThreshold) return <div style={{ ...S.sans, fontSize: 12, color: 'var(--green)' }}>Free delivery ✓</div>;
  return <div style={{ ...S.sans, fontSize: 12, color: 'var(--ink-soft)' }}>Add {g.freeThreshold - g.bottles} more for free delivery from {g.winery}</div>;
}

function WineDetail({ w, owned, onBack, onAdd, onOpenCart, onAsk, onTaste, onWine, cartCount }) {
  const [qty, setQty] = React.useState(1);
  const similar = AIW.wines.filter(x => x.id !== w.id && (x.variety === w.variety || (x.mood || []).some(m => (w.mood || []).includes(m)))).sort((a, b) => b.match - a.match).slice(0, 3);
  const plan = AIW.plan();
  const key = w.custom ? null : AIW.shipKeyOf(w);
  const st = key ? AIW.settingsOf(key) : null;
  const cases = key ? AIW.fulfilmentOf(key) === 'cases' : false;
  const twin = AIW.libraryTwin ? AIW.libraryTwin(w) : null;
  const soldOut = !w.custom && w.stock === 0;

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 75, background: 'var(--bg)', animation: 'aw-slide .32s cubic-bezier(.22,.9,.28,1)' }}>
      <BackBar onBack={onBack} right={cartCount ? <button onClick={onOpenCart} style={{ ...S.mono, fontSize: 9, background: 'var(--claret)', color: 'var(--bone)', border: 'none', borderRadius: 100, padding: '8px 12px', cursor: 'pointer', marginBottom: 8 }}>Cart · {cartCount}</button> : null} />
      <Screen top={0} bottom={w.custom ? 30 : 132}>
        <div style={{ margin: '0 -22px', padding: '96px 22px 26px', background: `linear-gradient(175deg, ${w.tint}30 0%, ${w.tint}10 45%, var(--bg) 100%)`, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Bottle wine={w} h={280} />
          {w.region && <Eyebrow style={{ marginTop: 26 }}>{w.region}</Eyebrow>}
          <div style={{ ...S.serif, fontSize: 38, lineHeight: 1.05, textAlign: 'center', marginTop: 12, color: 'var(--ink)' }}>{w.name}</div>
          <div style={{ ...S.serif, fontSize: 20, fontStyle: 'italic', color: 'var(--muted)', marginTop: 8 }}>{w.winery}{w.vintage ? ' · ' + w.vintage : ''}</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap', justifyContent: 'center' }}>
            {owned && <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--green)', border: '1px solid var(--green)', borderRadius: 100, padding: '5px 10px' }}>{owned.qty} in your cellar</div>}
            {w.custom && <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--muted)', border: '1px solid var(--line)', borderRadius: 100, padding: '5px 10px' }}>Your own bottle</div>}
            {w.organic && <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--green)', border: '1px solid var(--line)', borderRadius: 100, padding: '5px 10px' }}>Organic</div>}
          </div>
        </div>

        {twin && (
          <div style={{ borderRadius: 16, border: '1px solid var(--brass)', background: 'var(--bg-alt)', padding: 16, marginBottom: 18 }}>
            <Eyebrow color="var(--brass)">Now in the library</Eyebrow>
            <div style={{ ...S.sans, fontSize: 13, color: 'var(--ink-soft)', marginTop: 8, lineHeight: 1.5 }}>{twin.winery} publishes this wine on AIWine now — open the live page for notes, pairings and price.</div>
            <div style={{ marginTop: 12 }}><Btn small kind="ghost" onClick={() => onWine(twin)}>Open the live wine</Btn></div>
          </div>
        )}

        <div style={{ borderRadius: 20, background: 'var(--ink)', padding: 22, marginTop: 8 }}>
          <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            <Match v={w.match} size={62} dark />
            <div>
              <Eyebrow color="var(--brass-soft)">AIWine match</Eyebrow>
              <div style={{ ...S.serif, fontSize: 22, color: 'var(--bone)', marginTop: 8, lineHeight: 1.2 }}>{w.match >= 85 ? 'This looks very much like your style.' : w.match >= 72 ? 'Close to your style, with a twist.' : 'A deliberate stretch for you.'}</div>
            </div>
          </div>
          <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'rgba(244,239,229,.76)', marginTop: 16 }}>{w.why}</div>
          <button onClick={() => onAsk('Why this one?')} style={{ ...S.sans, fontSize: 12.5, fontWeight: 600, color: 'var(--brass-soft)', background: 'none', border: 'none', padding: 0, marginTop: 14, cursor: 'pointer' }}>Ask why →</button>
        </div>

        <div style={{ height: 34 }} />
        <SectionHead eyebrow="The wine" title="How it tastes" />
        {w.notes && <div style={{ ...S.serif, fontSize: 19, fontStyle: 'italic', lineHeight: 1.45, color: 'var(--ink-soft)', marginBottom: 24 }}>{w.notes}</div>}
        <Axis left="Light" right="Full" v={w.axes.body} />
        <Axis left="Fresh" right="Rich" v={w.axes.fresh} delay={80} />
        <Axis left="Soft" right="Tannic" v={w.axes.tannin} delay={160} />
        <Axis left="Unoaked" right="Oaky" v={w.axes.oak} delay={240} />
        {w.custom && <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: -6, marginBottom: 16, lineHeight: 1.5 }}>Estimated from the grape and style you entered — rate it and I’ll refine it.</div>}

        <div style={{ height: 14 }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div style={{ borderRadius: 16, border: '1px solid var(--line)', padding: 16, background: 'var(--card)' }}>
            <Eyebrow>When to drink</Eyebrow>
            <div style={{ ...S.serif, fontSize: 20, color: 'var(--ink)', marginTop: 9 }}>{w.drink}</div>
            <div style={{ ...S.sans, fontSize: 12, color: w.ready ? 'var(--green)' : 'var(--muted)', marginTop: 6 }}>{w.peak}</div>
          </div>
          <div style={{ borderRadius: 16, border: '1px solid var(--line)', padding: 16, background: 'var(--card)' }}>
            <Eyebrow>What to eat</Eyebrow>
            {w.food.length ? w.food.map(f => <div key={f} style={{ ...S.serif, fontSize: 17, color: 'var(--ink)', marginTop: 7 }}>{f}</div>)
              : <button onClick={() => onAsk('What should I eat with the ' + w.name + '?')} style={{ ...S.sans, fontSize: 12.5, color: 'var(--claret)', background: 'none', border: 'none', padding: 0, marginTop: 9, cursor: 'pointer', textAlign: 'left' }}>Ask me for a match →</button>}
          </div>
        </div>

        {w.awards && w.awards.length > 0 && (
          <div style={{ marginTop: 20, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {w.awards.map(a => <div key={a} style={{ ...S.mono, fontSize: 8.5, color: 'var(--brass)', border: '1px solid var(--brass)', borderRadius: 100, padding: '6px 10px' }}>{a}</div>)}
          </div>
        )}

        {!w.custom && st && (
          <React.Fragment>
            <div style={{ height: 30 }} />
            <SectionHead eyebrow="Shipping" title={'Sold and shipped by ' + key} />
            <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', overflow: 'hidden' }}>
              {[
                ['Delivery', st.freeThreshold + '+ bottles ships free · otherwise $' + AIW.MARKET.postagePerShipment + ' a carton'],
                cases ? ['Carton', 'This winery ships in 6s and 12s only'] : null,
                st.minOrder > 1 ? ['Minimum', st.minOrder + ' bottles per order'] : null,
                st.mixed === false ? ['Mixing', 'One wine per carton'] : null,
                st.dozenOn ? ['A dozen', Math.round(st.dozenRate * 100) + '% off at 12 bottles'] : null,
                st.allocOn && st.allocWines.indexOf(String(w.id)) >= 0 ? ['Allocation', 'Limit ' + st.allocCap + ' bottles per order'] : null,
                st.paused ? ['Paused', 'Not taking orders right now'] : null,
                st.pickup ? ['Pickup', 'Cellar-door pickup available'] : null
              ].filter(Boolean).map(([k, v], i) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 14, padding: '13px 16px', borderTop: i ? '1px solid var(--line-soft)' : 'none' }}>
                  <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', flex: 'none', paddingTop: 2 }}>{k}</div>
                  <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--ink-soft)', textAlign: 'right', lineHeight: 1.45 }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 }}>Every winery sets its own rules in its AIWine portal — this is {key}’s, live.</div>
          </React.Fragment>
        )}

        {owned && (
          <React.Fragment>
            <div style={{ height: 30 }} />
            <SectionHead eyebrow="Your bottle" title="Since you own it" />
            <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
              <Btn small kind="dark" onClick={() => onTaste(w)}>Drink &amp; rate</Btn>
              <Btn small kind="ghost" onClick={() => onAsk('What should I eat with the ' + w.name + ' tonight?')}>What to eat</Btn>
            </div>
            <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 12 }}>{owned.bought ? 'Added ' + owned.bought : ''}{owned.paid ? ' at $' + owned.paid : ''}</div>
          </React.Fragment>
        )}

        {similar.length > 0 && (
          <React.Fragment>
            <div style={{ height: 34 }} />
            <SectionHead eyebrow="If you like this" title="Other wines like it" />
            {similar.map(s => <WineRow key={s.id} w={s} onWine={onWine} />)}
          </React.Fragment>
        )}
        <div style={{ height: 20 }} />
      </Screen>

      {!w.custom && (
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 20px 22px', background: 'linear-gradient(to top, var(--bg) 62%, transparent)', zIndex: 66 }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ flex: 'none' }}>
              <div style={{ ...S.serif, fontSize: 24, color: 'var(--ink)', lineHeight: 1 }}>{AIW.money(w.price)}</div>
              <div style={{ ...S.mono, fontSize: 8, color: 'var(--brass)', marginTop: 5 }}>{plan.discount ? 'Member ' + AIW.money(w.price * (1 - plan.discount)) : 'Members ' + AIW.money(w.price * .9)}</div>
            </div>
            {!soldOut && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, border: '1px solid var(--line)', borderRadius: 100, padding: '4px 8px' }}>
                <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 28, height: 28, borderRadius: '50%', border: 'none', background: 'none', cursor: 'pointer', fontSize: 15, color: 'var(--ink)' }}>−</button>
                <div style={{ ...S.serif, fontSize: 18, width: 16, textAlign: 'center', color: 'var(--ink)' }}>{qty}</div>
                <button onClick={() => setQty(q => Math.min(w.stock || 12, q + 1))} style={{ width: 28, height: 28, borderRadius: '50%', border: 'none', background: 'none', cursor: 'pointer', fontSize: 15, color: 'var(--ink)' }}>+</button>
              </div>
            )}
            <Btn full onClick={() => soldOut ? null : onAdd(w, qty)} style={{ flex: 1, opacity: soldOut || (st && st.paused) ? .5 : 1 }}>{soldOut ? 'Sold out' : st && st.paused ? 'Not taking orders' : 'Add to cart'}</Btn>
          </div>
          {st && !soldOut && <div style={{ ...S.sans, fontSize: 11, color: 'var(--muted)', marginTop: 8 }}>{cases ? key + ' ships in 6s & 12s — I’ll help you complete the carton.' : 'Free delivery from ' + key + ' at ' + st.freeThreshold + ' bottles.'}</div>}
        </div>
      )}
    </div>
  );
}

/* ---------- cart ---------- */
function CartSheet({ open, onClose, onWine, onCheckout, cart, setQty, tick }) {
  const [done, setDone] = React.useState(false);
  React.useEffect(() => { if (open) setDone(false); }, [open]);
  const ships = AIW.shipments(cart);
  const unknown = AIW.cartUnknown();
  const M = AIW.MARKET, member = AIW.plan().discount > 0;
  const bottles = ships.reduce((n, g) => n + g.bottles, 0);
  const sub = ships.reduce((n, g) => n + g.subtotal, 0);
  const caseDisc = ships.reduce((n, g) => n + g.discount, 0);
  const memberDisc = ships.reduce((n, g) => n + g.appDiscount, 0);
  const postage = ships.reduce((n, g) => n + g.postage, 0);
  const total = ships.reduce((n, g) => n + g.total, 0);
  const blocked = ships.some(g => g.blocked);

  return (
    <Sheet open={open} onClose={onClose} height={done ? '52%' : '88%'}>
      {done ? (
        <div style={{ padding: '46px 26px', textAlign: 'center' }}>
          <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--claret)', color: 'var(--bone)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}><Ic name="check" size={22} color="var(--bone)" /></div>
          <div style={{ ...S.serif, fontSize: 30, marginTop: 20, lineHeight: 1.1, color: 'var(--ink)' }}>On its way</div>
          <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 12 }}>{bottles} bottles in {ships.length} shipment{ships.length === 1 ? '' : 's'}, each direct from the winery. They’re in your cellar — I’ll tell you when they’re ready to open.</div>
          <div style={{ marginTop: 26 }}><Btn full onClick={onClose}>Done</Btn></div>
        </div>
      ) : (
        <div className="aw-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '34px 22px 26px' }}>
          <Eyebrow>Your cart</Eyebrow>
          <div style={{ ...S.serif, fontSize: 30, lineHeight: 1.08, marginTop: 10, color: 'var(--ink)' }}>{bottles ? `${bottles} bottle${bottles === 1 ? '' : 's'} · ${ships.length} shipment${ships.length === 1 ? '' : 's'}` : 'Nothing here yet'}</div>
          {!bottles && !unknown.bottles && <div style={{ ...S.sans, fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 12, lineHeight: 1.55 }}>Wines you add are grouped by winery — each one ships from its own cellar door, with its own delivery rules.</div>}

          {unknown.bottles > 0 && (
            <div style={{ marginTop: 18, borderRadius: 16, border: '1px solid var(--line)', background: 'var(--bg-alt)', padding: 18 }}>
              <Eyebrow>Added on the website</Eyebrow>
              <div style={{ ...S.serif, fontSize: 21, lineHeight: 1.2, marginTop: 9, color: 'var(--ink)' }}>
                {unknown.bottles} bottle{unknown.bottles === 1 ? '' : 's'} the app can’t show
              </div>
              <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 9 }}>
                You share one basket with aiwine.co.nz, but the website also lists wines that aren’t published to the app’s live library yet. Those bottles are still in your cart — finish that order on the website.
              </div>
              <div style={{ marginTop: 14 }}>
                <Btn small kind="ghost" onClick={() => { window.open('https://aiwine.co.nz/checkout.html', '_blank', 'noopener'); }}>Open the website cart</Btn>
              </div>
            </div>
          )}

          {ships.map(g => (
            <div key={g.winery} style={{ marginTop: 20, borderRadius: 18, border: '1px solid ' + (g.blocked ? 'var(--claret)' : 'var(--line)'), background: 'var(--card)', overflow: 'hidden' }}>
              <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line-soft)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)' }}>{g.winery}</div>
                <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--muted)' }}>{g.bottles} btl</div>
              </div>
              {g.items.map(i => (
                <div key={i.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px' }}>
                  <div onClick={() => onWine(i.w)} style={{ width: 24, flex: 'none', cursor: 'pointer' }}><Bottle wine={i.w} h={48} glow={false} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ ...S.serif, fontSize: 16, color: 'var(--ink)' }}>{i.w.name}</div>
                    <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{i.w.vintage} · {AIW.money(i.w.price)}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <button onClick={() => setQty(i.id, i.qty - 1)} style={{ width: 26, height: 26, borderRadius: '50%', border: '1px solid var(--line)', background: 'none', cursor: 'pointer', color: 'var(--ink)' }}>−</button>
                    <div style={{ ...S.sans, fontSize: 13, width: 14, textAlign: 'center', color: 'var(--ink)' }}>{i.qty}</div>
                    <button onClick={() => setQty(i.id, i.qty + 1)} style={{ width: 26, height: 26, borderRadius: '50%', border: '1px solid var(--line)', background: 'none', cursor: 'pointer', color: 'var(--ink)' }}>+</button>
                  </div>
                </div>
              ))}
              <div style={{ padding: '12px 16px', borderTop: '1px solid var(--line-soft)', display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center', background: 'var(--bg-alt)' }}>
                <ShipHint g={g} />
                <div style={{ ...S.sans, fontSize: 12, color: g.postage ? 'var(--ink-soft)' : 'var(--green)', flex: 'none' }}>{g.postage ? 'Delivery ' + AIW.money(g.postage) : 'Free delivery'}</div>
              </div>
            </div>
          ))}

          {bottles > 0 && (
            <React.Fragment>
              <div style={{ marginTop: 24 }}>
                {[['Bottles · ' + bottles, AIW.money(sub)]]
                  .concat(caseDisc ? [['Case discount', '−' + AIW.money(caseDisc)]] : [])
                  .concat(memberDisc ? [['Connoisseur member · 10%', '−' + AIW.money(memberDisc)]] : [])
                  .concat([['Delivery · ' + ships.length + ' shipment' + (ships.length === 1 ? '' : 's'), postage ? AIW.money(postage) : 'Free']])
                  .map(([k, v]) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 0', ...S.sans, fontSize: 13, color: 'var(--ink-soft)' }}><span>{k}</span><span>{v}</span></div>
                  ))}
                <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 14, marginTop: 8, borderTop: '1px solid var(--line)' }}>
                  <span style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>Total</span>
                  <span style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>{AIW.money(total)}</span>
                </div>
                <div style={{ ...S.sans, fontSize: 11, color: 'var(--muted)', marginTop: 6 }}>Includes GST (15%). Delivery within New Zealand only.</div>
              </div>

              {!member && (
                <div style={{ marginTop: 18, borderRadius: 16, border: '1px solid var(--brass)', background: 'linear-gradient(160deg,#FBF6EA,#F2E8D4)', padding: 16 }}>
                  <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--brass)' }}>Connoisseur · $9 a month</div>
                  <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)', marginTop: 5 }}>You’d save {AIW.money(Math.round((sub - caseDisc) * .1))} on this order</div>
                  <div style={{ ...S.sans, fontSize: 12, color: 'var(--ink-soft)', marginTop: 6, lineHeight: 1.5 }}>10% off every bottle, on top of any winery case discount. It pays for itself at $90 of wine a month.</div>
                  <div style={{ marginTop: 12 }}><Btn small kind="gilt" onClick={() => { if (AIW.join() === 'local') tick(); }}>Join and save now</Btn></div>
                </div>
              )}

              <div style={{ marginTop: 20 }}>
                <Btn full onClick={() => { if (blocked) return; AIW.addSpend(total - postage); onCheckout(ships); setDone(true); }} style={{ opacity: blocked ? .45 : 1 }}>{blocked ? 'Fix the cartons above' : 'Checkout'}</Btn>
              </div>
              <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', textAlign: 'center', marginTop: 12 }}>Each winery ships and invoices its own carton. You must be 18+.</div>
            </React.Fragment>
          )}
        </div>
      )}
    </Sheet>
  );
}

Object.assign(window, { WineDetail, CartSheet, ShipHint });
