/* AIWine — ASK (sommelier, camera, wine list) */
const ASK_SUGGESTIONS = [
  { t: 'Find me a wine for tonight', q: 'Find me a wine for tonight' },
  { t: 'What goes with dinner?', q: 'I’m cooking lamb with rosemary' },
  { t: 'What’s ready in my cellar?', q: 'What should I open from my cellar tonight?' },
  { t: 'I’m at a restaurant', q: '__winelist' },
  { t: 'I’m visiting wine country', q: 'I’m spending Saturday in Martinborough. What should I do?' }
];

/* One pick, honouring the member's Preferences — same rule as Home. */
function best(list) { return AIW.recommend(list || AIW.wines, 1)[0]; }

function reply(q, ctx) {
  const t = q.toLowerCase(), W = AIW.wines;
  const cellar = AIW.cellar().map(c => ({ ...c, w: AIW.byId(c.id) })).filter(c => c.w);

  if (/saturday|visiting|itinerary|wine country|weekend in/.test(t)) {
    const region = (AIW.REGIONS.find(r => t.includes(r.name.toLowerCase())) || AIW.REGIONS[0]);
    const wineries = [...new Set(W.filter(w => (w.region || '').includes(region.name)).sort((a, b) => b.match - a.match).map(w => w.winery))].slice(0, 3);
    if (!wineries.length) return { text: `No ${region.name} wineries are publishing on AIWine yet, so I can’t build you an honest day there. Ask me about a region with wines in the library and I’ll plan it properly.` };
    const times = ['10:30', '13:00', '15:30'];
    return {
      text: `Here’s a Saturday in ${region.name}, built around what you actually like — small producers first, a long lunch in the middle.`,
      itinerary: wineries.map((name, i) => {
        const w = best(W.filter(x => x.winery === name));
        return { time: times[i], place: name, line: `Taste the ${w.name}. ${w.why}` };
      }).concat([{ time: '17:00', place: 'Head home', line: 'Tell me what you tasted and I’ll fold it into your profile.' }])
    };
  }

  if (/cellar|ready|what should i open|drink now|peak/.test(t)) {
    if (!cellar.length) return { text: 'Your cellar is empty so far. Scan a New Zealand bottle from the library, or type in anything you already own — imports and gifts included — and I’ll start watching their drinking windows.' };
    const ready = cellar.filter(c => c.w.ready);
    const list = (ready.length ? ready : cellar).map(c => c.w);
    return { text: ready.length ? `${ready.length} of your ${cellar.length} labels ${ready.length === 1 ? 'is' : 'are'} in its window. I’d open the ${best(list).name} tonight.` : 'Nothing is at its peak yet — everything you own is still building. If you want one now, this is the one I’d open.', list: list.slice(0, 4) };
  }

  if (/cheap|less|under|budget|afford/.test(t)) {
    const ref = ctx.wine;
    const pool = W.filter(w => w.price > 0 && (!ref || (w.price < ref.price && w.id !== ref.id)));
    const pick = best(pool.length ? pool : W);
    if (!pick) return { text: 'Everything in the library sits at a similar price right now.' };
    return { text: ref ? `Yes — ${AIW.money(ref.price - pick.price)} less, and honestly not a step down.` : 'This is the best value in the library for your palate right now.', wine: pick, why: pick.notes || pick.why };
  }

  for (const f of AIW.FOODS) {
    const words = { Seafood: /oyster|seafood|fish|sushi|prawn|scallop|crayfish/, Chicken: /chicken|poultry|duck|roast/, 'Red meat': /lamb|beef|steak|venison|rosemary/, Pasta: /pasta|risotto|pizza|tomato/, 'Asian food': /thai|curry|asian|noodle|spicy/, Vegetarian: /vegetar|mushroom|salad|vegetable/, Cheese: /cheese/, Dessert: /dessert|pudding|chocolate|tart/ }[f];
    if (words && words.test(t)) {
      const pool = W.filter(w => AIW.matchesFood(w, f));
      const pick = best(pool.length ? pool : W);
      const owned = cellar.find(c => c.id === pick.id);
      return { text: `For ${f.toLowerCase()} I’d pour this${owned ? ` — and you already have ${owned.qty} bottle${owned.qty > 1 ? 's' : ''}` : ''}.`, wine: pick, why: pick.notes || pick.why };
    }
  }

  if (/gift|celebrat|birthday|anniversar/.test(t)) {
    const pick = best(W.filter(w => AIW.matchesOccasion(w, 'Celebration')));
    return pick ? { text: 'Something occasion-shaped, but good enough to actually drink with dinner.', wine: pick, why: pick.notes } : { text: 'Nothing in the library fits a celebration right now.' };
  }

  if (/why/.test(t) && ctx.wine) {
    const n = AIW.history().length;
    return { text: n ? `Because of the pattern, not the label. Across your ${n} tasting${n === 1 ? '' : 's'} you lean the same way this wine sits — ${ctx.wine.why}` : `Because of the profile you set up at the start — ${ctx.wine.why} Rate a few wines and this answer gets much more specific.`, wine: ctx.wine };
  }

  const named = W.find(w => t.includes((w.variety || '').toLowerCase()) || t.includes((w.winery || '').toLowerCase()));
  if (named) {
    const pool = W.filter(w => w.variety === named.variety);
    const pick = best(pool);
    return { text: `${named.variety} — here’s the one I’d put in front of you from the library.`, wine: pick, why: pick.notes || pick.why };
  }

  const pick = best(W);
  if (!pick) return { text: 'The library is empty right now — no winery has published a wine yet.' };
  return { text: /tonight|dinner|wine for|recommend|find me/.test(t) ? 'Then I’d keep it simple. This is the closest thing in the library to your palate today.' : 'Tell me the food, the evening, or a wine you loved and I’ll be specific. Meanwhile, this is what I’d pour you.', wine: pick, why: pick.notes || pick.why };
}

function Typing() {
  return <div style={{ display: 'flex', gap: 4, padding: '14px 16px' }}>{[0, 1, 2].map(i => <div key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--brass)', animation: `aw-blink 1.3s ${i * .17}s infinite` }} />)}</div>;
}

function Bubble({ me, children }) {
  return (
    <div style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start', marginBottom: 14 }}>
      <div style={{ maxWidth: '84%', padding: me ? '12px 16px' : 0, borderRadius: 16, background: me ? 'var(--ink)' : 'transparent', color: me ? 'var(--bone)' : 'var(--ink)', ...S.sans, fontSize: me ? 14 : 15.5, lineHeight: 1.55, animation: 'aw-rise .34s cubic-bezier(.22,.9,.28,1)' }}>{children}</div>
    </div>
  );
}

function AnswerWine({ w, why, onWine, onBuy }) {
  return (
    <div style={{ borderRadius: 18, border: '1px solid var(--line)', background: 'var(--card)', overflow: 'hidden', marginTop: 4 }}>
      <div onClick={() => onWine(w)} style={{ display: 'flex', gap: 14, padding: 16, cursor: 'pointer', alignItems: 'center' }}>
        <div style={{ width: 44, flex: 'none' }}><Bottle wine={w} h={94} glow={false} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Eyebrow>{w.region || w.variety}</Eyebrow>
          <div style={{ ...S.serif, fontSize: 21, lineHeight: 1.15, marginTop: 5, color: 'var(--ink)' }}>{w.name}</div>
          <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{w.winery}{w.vintage ? ' · ' + w.vintage : ''}{w.price ? ' · ' + AIW.money(w.price) : ''}</div>
        </div>
        <Match v={w.match} size={40} />
      </div>
      {why && <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.5, color: 'var(--ink-soft)', padding: '0 16px 14px' }}>{why}</div>}
      <div style={{ display: 'flex', borderTop: '1px solid var(--line-soft)' }}>
        {!w.custom && <button onClick={() => onBuy(w)} style={{ flex: 1, ...S.sans, fontSize: 12.5, fontWeight: 600, padding: '13px 0', background: 'none', border: 'none', borderRight: '1px solid var(--line-soft)', color: 'var(--claret)', cursor: 'pointer' }}>Buy {AIW.money(w.price)}</button>}
        <button onClick={() => onWine(w)} style={{ flex: 1, ...S.sans, fontSize: 12.5, fontWeight: 600, padding: '13px 0', background: 'none', border: 'none', color: 'var(--ink-soft)', cursor: 'pointer' }}>Explore</button>
      </div>
    </div>
  );
}

function Itinerary({ items }) {
  return (
    <div style={{ borderRadius: 18, border: '1px solid var(--line)', background: 'var(--card)', padding: 18, marginTop: 4 }}>
      <Eyebrow>Your day</Eyebrow>
      <div style={{ marginTop: 14 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: 'flex', gap: 14, paddingBottom: i === items.length - 1 ? 0 : 18 }}>
            <div style={{ ...S.mono, fontSize: 9.5, color: 'var(--claret)', width: 34, flex: 'none', paddingTop: 3 }}>{it.time}</div>
            <div style={{ width: 1, background: 'var(--line)', flex: 'none', position: 'relative' }}><div style={{ position: 'absolute', left: -3, top: 4, width: 7, height: 7, borderRadius: '50%', background: 'var(--claret)' }} /></div>
            <div style={{ flex: 1, paddingLeft: 6 }}>
              <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)', lineHeight: 1.2 }}>{it.place}</div>
              <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 4, lineHeight: 1.45 }}>{it.line}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------------- camera ---------------- */
function listPrices(w) { return { glass: Math.max(9, Math.round(w.price / 3.4)), bottle: Math.round(w.price * 1.9) }; }

function FakeWineList({ rows }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#EFE7D6', padding: '54px 30px', transform: 'rotate(-1.2deg) scale(1.06)' }}>
      <div style={{ ...S.serif, fontSize: 26, textAlign: 'center', color: '#2A1D16' }}>By the glass</div>
      <div style={{ ...S.mono, fontSize: 8, textAlign: 'center', color: '#8B7E6E', marginTop: 6 }}>New Zealand list</div>
      <div style={{ marginTop: 26 }}>
        {rows.map(r => (
          <div key={r.w.id} style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 15 }}>
            <div style={{ ...S.serif, fontSize: 15.5, color: '#2A1D16' }}>{r.w.winery} {r.w.name} {r.w.vintage}</div>
            <div style={{ flex: 1, borderBottom: '1px dotted #B6A992' }} />
            <div style={{ ...S.mono, fontSize: 9, color: '#4A3D34' }}>{r.glass} / {r.bottle}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Locked({ kind, onClose }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 95, background: 'var(--bg)', padding: '110px 26px 30px' }}>
      <BackBar onBack={onClose} />
      <Eyebrow>Taster · {AIW.plan().scans} scans a month</Eyebrow>
      <div style={{ ...S.serif, fontSize: 32, lineHeight: 1.08, marginTop: 12, color: 'var(--ink)' }}>You’ve used this month’s {kind === 'lists' ? 'wine-list scan' : 'label scans'}.</div>
      <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-soft)', marginTop: 14 }}>Your cellar, your taste profile and asking me anything stay free — always. Scanning is the part that costs us money to run.</div>
      <div style={{ marginTop: 24, borderRadius: 18, border: '1px solid var(--brass)', background: 'linear-gradient(160deg,#FBF6EA,#F2E8D4)', padding: 20 }}>
        <div style={{ ...S.serif, fontSize: 23, color: 'var(--ink)' }}>Connoisseur · $9 a month</div>
        {['Unlimited label & wine-list scanning', '10% off every bottle', 'Deeper taste profile'].map(b => (
          <div key={b} style={{ display: 'flex', gap: 9, alignItems: 'center', marginTop: 10 }}>
            <Ic name="check" size={14} color="var(--brass)" />
            <div style={{ ...S.sans, fontSize: 13, color: 'var(--ink-soft)' }}>{b}</div>
          </div>
        ))}
        <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 12, lineHeight: 1.5 }}>It pays for itself at $90 of wine a month.</div>
        <div style={{ marginTop: 16 }}><Btn full kind="gilt" onClick={() => { if (AIW.join() === 'local') onClose(); }}>Become a Connoisseur</Btn></div>
      </div>
      <button onClick={onClose} style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', background: 'none', border: 'none', width: '100%', marginTop: 16, cursor: 'pointer' }}>Not now</button>
    </div>
  );
}

function Camera({ mode, onClose, onWine, onBuy, onAddCellar }) {
  const kind = mode === 'winelist' ? 'lists' : 'scans';
  const allowed = React.useRef(AIW.canUse(kind));
  const [phase, setPhase] = React.useState(allowed.current ? 'scan' : 'locked');
  const [food, setFood] = React.useState(null);
  const rows = React.useMemo(() => AIW.wines.slice().sort(() => Math.random() - .5).slice(0, 6).map(w => ({ w, ...listPrices(w) })), []);
  const bottle = React.useMemo(() => AIW.wines.slice().sort((a, b) => b.match - a.match)[0], []);
  React.useEffect(() => {
    if (phase !== 'scan') return;
    AIW.use(kind);
    const t = setTimeout(() => setPhase('result'), 2000);
    return () => clearTimeout(t);
  }, []);
  if (phase === 'locked') return <Locked kind={kind} onClose={onClose} />;
  if (!bottle) return <Locked kind={kind} onClose={onClose} />;

  const ranked = rows.slice().sort((a, b) => b.w.match - a.w.match);
  const pick = food === 'Fish' ? (ranked.find(r => r.w.colour !== 'Red') || ranked[0]) : ranked[0];
  const left = AIW.left(kind);

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 95, background: '#100B08' }}>
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
        {mode === 'winelist' ? <FakeWineList rows={rows} /> : (
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(70% 50% at 50% 45%, #3B2C22 0%, #120C08 100%)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src={bottle.bottle} alt="" style={{ height: 400, filter: 'drop-shadow(0 20px 40px rgba(0,0,0,.6))' }} />
          </div>
        )}
        {phase === 'scan' && <div style={{ position: 'absolute', left: 0, right: 0, height: 140, background: 'linear-gradient(to bottom, transparent, rgba(201,164,90,.42), transparent)', animation: 'aw-sweep 1.5s cubic-bezier(.5,0,.5,1) infinite' }} />}
        <div style={{ position: 'absolute', inset: 0, background: phase === 'result' ? 'linear-gradient(to bottom, rgba(16,11,8,.72), rgba(16,11,8,.94))' : 'linear-gradient(to bottom, rgba(16,11,8,.35), rgba(16,11,8,.55))', transition: 'background .5s' }} />
      </div>

      <BackBar onBack={onClose} dark title={mode === 'winelist' ? 'Wine list' : 'Label'} right={isFinite(left) ? <div style={{ ...S.mono, fontSize: 8.5, color: 'rgba(244,239,229,.75)', border: '1px solid rgba(244,239,229,.3)', borderRadius: 100, padding: '5px 9px', marginBottom: 8 }}>{Math.max(0, left)} left this month</div> : null} />

      {phase === 'scan' && (
        <div style={{ position: 'absolute', left: 0, right: 0, top: '46%', textAlign: 'center' }}>
          <div style={{ ...S.serif, fontSize: 24, color: 'var(--bone)' }}>Reading…</div>
          <div style={{ ...S.mono, fontSize: 9, color: 'var(--brass-soft)', marginTop: 10 }}>Matching against the New Zealand library</div>
        </div>
      )}

      {phase === 'result' && mode !== 'winelist' && (
        <div className="aw-scroll" style={{ position: 'absolute', inset: 0, padding: '110px 22px 30px', overflowY: 'auto', animation: 'aw-rise .4s' }}>
          <Eyebrow color="var(--brass-soft)">Identified in the library</Eyebrow>
          <div style={{ ...S.serif, fontSize: 34, color: 'var(--bone)', lineHeight: 1.05, marginTop: 10 }}>{bottle.vintage} {bottle.winery}<br />{bottle.name}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 20 }}>
            <Match v={bottle.match} size={54} dark />
            <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.5, color: 'rgba(244,239,229,.8)', flex: 1 }}>{bottle.why}</div>
          </div>
          <div style={{ marginTop: 24, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <Btn small kind="gilt" onClick={() => onWine(bottle)}>Explore wine</Btn>
            <Btn small kind="onDark" onClick={() => { onAddCellar(bottle); onClose(); }}>Add to cellar</Btn>
            <Btn small kind="onDark" onClick={() => onBuy(bottle)}>Buy {AIW.money(bottle.price)}</Btn>
          </div>
          <div style={{ marginTop: 26, paddingTop: 20, borderTop: '1px solid rgba(244,239,229,.16)' }}>
            <div style={{ ...S.sans, fontSize: 12.5, color: 'rgba(244,239,229,.6)', lineHeight: 1.5 }}>Scanning recognises New Zealand wines published on AIWine. Anything else — imports, gifts, old vintages — add by hand from your cellar in about fifteen seconds.</div>
          </div>
        </div>
      )}

      {phase === 'result' && mode === 'winelist' && (
        <div className="aw-scroll" style={{ position: 'absolute', inset: 0, padding: '104px 22px 30px', overflowY: 'auto', animation: 'aw-rise .4s' }}>
          <Eyebrow color="var(--brass-soft)">{rows.length} wines read · ranked for you</Eyebrow>
          <div style={{ ...S.serif, fontSize: 30, color: 'var(--bone)', lineHeight: 1.1, marginTop: 10 }}>Best for you</div>
          {ranked.slice(0, 3).map((r, i) => (
            <div key={r.w.id} onClick={() => onWine(r.w)} style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '16px 0', borderBottom: '1px solid rgba(244,239,229,.14)', cursor: 'pointer' }}>
              <div style={{ ...S.serif, fontSize: 26, color: ['#C9A45A', '#B7B7B2', '#A9744F'][i], width: 22, flex: 'none' }}>{i + 1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ ...S.serif, fontSize: 19, color: 'var(--bone)', lineHeight: 1.2 }}>{r.w.name}</div>
                <div style={{ ...S.sans, fontSize: 11.5, color: 'rgba(244,239,229,.55)', marginTop: 3 }}>{r.w.winery} · {AIW.money(r.glass)} glass / {AIW.money(r.bottle)} bottle</div>
              </div>
              <Match v={r.w.match} size={40} dark />
            </div>
          ))}
          <div style={{ marginTop: 26 }}>
            <Eyebrow color="rgba(244,239,229,.55)">What are you eating?</Eyebrow>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
              {['Lamb', 'Fish', 'Steak', 'Cheese'].map(f => <Chip key={f} dark active={food === f} onClick={() => setFood(f)}>{f}</Chip>)}
            </div>
          </div>
          {food && (
            <div style={{ marginTop: 20, borderRadius: 18, border: '1px solid rgba(201,164,90,.4)', background: 'rgba(244,239,229,.06)', padding: 18, animation: 'aw-rise .35s' }}>
              <Eyebrow color="var(--brass-soft)">Your taste + the list + {food.toLowerCase()}</Eyebrow>
              <div style={{ ...S.serif, fontSize: 23, color: 'var(--bone)', marginTop: 10, lineHeight: 1.15 }}>{pick.w.name}</div>
              <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.5, color: 'rgba(244,239,229,.78)', marginTop: 8 }}>Order it by the glass at {AIW.money(pick.glass)}. {pick.w.why}</div>
              <div style={{ marginTop: 16 }}><Btn small kind="gilt" onClick={() => onWine(pick.w)}>See the wine</Btn></div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ---------------- ask ---------------- */
function Ask({ seed, onWine, onBuy, onAddCellar, clearSeed }) {
  const [msgs, setMsgs] = React.useState([]);
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [cam, setCam] = React.useState(null);
  const [listening, setListening] = React.useState(false);
  const ctx = React.useRef({ wine: null });
  const end = React.useRef(null);

  const send = (q) => {
    if (!q || !q.trim()) return;
    if (q === '__winelist') { setCam('winelist'); return; }
    setMsgs(m => [...m, { me: true, text: q }]);
    setText(''); setBusy(true);
    setTimeout(() => {
      const r = reply(q, ctx.current);
      if (r.wine) ctx.current.wine = r.wine;
      setBusy(false);
      setMsgs(m => [...m, { ...r }]);
    }, 950);
  };

  React.useEffect(() => { if (seed) { seed === 'voice' ? setListening(true) : send(seed); clearSeed(); } }, [seed]);
  React.useEffect(() => { if (end.current && end.current.parentNode) end.current.parentNode.scrollTop = end.current.parentNode.scrollHeight; }, [msgs, busy]);

  const empty = !msgs.length;
  return (
    <React.Fragment>
      <Screen top={60} bottom={168}>
        {empty ? (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'radial-gradient(120% 120% at 30% 20%, #7A2634, var(--claret-deep))', display: 'flex', alignItems: 'center', justifyContent: 'center', ...S.serif, fontSize: 15, color: 'var(--bone)' }}>A</div>
              <Eyebrow>AIWine sommelier</Eyebrow>
            </div>
            <div style={{ ...S.serif, fontSize: 36, lineHeight: 1.05, marginTop: 20, color: 'var(--ink)' }}>What can I<br />help you with?</div>
            <div style={{ marginTop: 26 }}>
              {ASK_SUGGESTIONS.map(s => (
                <div key={s.t} onClick={() => send(s.q)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '17px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
                  <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)' }}>{s.t}</div>
                  <div style={{ color: 'var(--claret)' }}><Ic name="chevron" size={15} /></div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 28, borderRadius: 18, background: 'var(--bg-alt)', padding: 18 }}>
              <Eyebrow>Or show me</Eyebrow>
              <div style={{ display: 'flex', gap: 9, marginTop: 12, flexWrap: 'wrap' }}>
                <Chip onClick={() => setCam('bottle')}>A bottle</Chip>
                <Chip onClick={() => setCam('winelist')}>A wine list</Chip>
                <Chip onClick={() => setCam('bottle')}>A shelf</Chip>
              </div>
              <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 12, lineHeight: 1.5 }}>Scanning recognises New Zealand wines published on AIWine.</div>
            </div>
          </div>
        ) : (
          <div>
            {msgs.map((m, i) => (
              <div key={i}>
                <Bubble me={m.me}>{m.text}</Bubble>
                {m.wine && <div style={{ marginBottom: 18 }}><AnswerWine w={m.wine} why={m.why} onWine={onWine} onBuy={onBuy} /></div>}
                {m.itinerary && <div style={{ marginBottom: 18 }}><Itinerary items={m.itinerary} /></div>}
                {m.list && <div style={{ marginBottom: 18 }}>{m.list.map(w => <WineRow key={w.id} w={w} onWine={onWine} />)}</div>}
              </div>
            ))}
            {busy && <Typing />}
            {!busy && (
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 4 }}>
                {['Is there something cheaper?', 'Why this one?', 'What should I eat with it?'].map(s => <Chip key={s} onClick={() => send(s)} style={{ fontSize: 12 }}>{s}</Chip>)}
              </div>
            )}
            <div ref={end} />
          </div>
        )}
      </Screen>

      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 96, zIndex: 60, padding: '10px 18px 14px', background: 'linear-gradient(to top, var(--bg) 62%, transparent)' }}>
        {listening ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--ink)', borderRadius: 100, padding: '13px 18px' }}>
            <div style={{ display: 'flex', gap: 3, alignItems: 'center', height: 20 }}>
              {[0, 1, 2, 3, 4, 5, 6].map(i => <div key={i} style={{ width: 3, borderRadius: 2, background: 'var(--brass)', height: 20, animation: `aw-wave 1s ${i * .09}s infinite ease-in-out` }} />)}
            </div>
            <div style={{ ...S.sans, fontSize: 13, color: 'rgba(244,239,229,.8)', flex: 1 }}>Listening…</div>
            <button onClick={() => { setListening(false); send('I’m cooking lamb with rosemary tonight'); }} style={{ ...S.mono, fontSize: 9, background: 'var(--brass)', color: '#20160F', border: 'none', borderRadius: 100, padding: '7px 12px', cursor: 'pointer' }}>Done</button>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--card-2)', border: '1px solid var(--line)', borderRadius: 100, padding: '6px 6px 6px 18px', boxShadow: '0 10px 24px rgba(27,20,16,.10)' }}>
            <input value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === 'Enter' && send(text)} placeholder="Ask AIWine anything about wine" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', ...S.sans, fontSize: 14, color: 'var(--ink)', minWidth: 0 }} />
            <button onClick={() => setListening(true)} title="Speak" style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic name="voice" size={18} /></button>
            <button onClick={() => setCam('bottle')} title="Scan" style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic name="scan" size={18} /></button>
            <button onClick={() => send(text || 'Find me a wine for tonight')} style={{ width: 40, height: 40, borderRadius: '50%', border: 'none', background: 'var(--claret)', color: 'var(--bone)', cursor: 'pointer', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic name="send" size={17} color="var(--bone)" /></button>
          </div>
        )}
      </div>

      {cam && <Camera mode={cam} onClose={() => setCam(null)} onWine={onWine} onBuy={onBuy} onAddCellar={onAddCellar} />}
    </React.Fragment>
  );
}

Object.assign(window, { Ask, Camera, AnswerWine, reply });
