/* AIWine — CELLAR (library bottles + private bottles), tasting */
function AddBottle({ open, onClose, onAdded }) {
  const [mode, setMode] = React.useState('choose');
  const [q, setQ] = React.useState('');
  const [f, setF] = React.useState({ winery: '', name: '', vintage: '', variety: '', region: '', style: 'medium-bodied', qty: 1, paid: '', notes: '' });
  React.useEffect(() => { if (open) { setMode('choose'); setQ(''); setF({ winery: '', name: '', vintage: '', variety: '', region: '', style: 'medium-bodied', qty: 1, paid: '', notes: '' }); } }, [open]);
  React.useEffect(() => {
    if (mode !== 'scan') return;
    const t = setTimeout(() => setMode('manual'), 1900);
    return () => clearTimeout(t);
  }, [mode]);

  const results = q.trim().length > 1 ? AIW.wines.filter(w => (w.winery + ' ' + w.name + ' ' + w.variety).toLowerCase().includes(q.toLowerCase())).slice(0, 8) : [];
  const field = (k, label, props = {}) => (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', marginBottom: 6 }}>{label}</div>
      <input value={f[k]} onChange={e => setF(x => ({ ...x, [k]: e.target.value }))} {...props} style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--line)', borderRadius: 12, padding: '13px 14px', ...S.sans, fontSize: 14, background: 'var(--card)', color: 'var(--ink)', outline: 'none' }} />
    </label>
  );

  return (
    <Sheet open={open} onClose={onClose} height="88%">
      <div className="aw-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '34px 22px 30px' }}>
        <Eyebrow>Add to your cellar</Eyebrow>

        {mode === 'choose' && (
          <div>
            <div style={{ ...S.serif, fontSize: 30, lineHeight: 1.1, marginTop: 10, color: 'var(--ink)' }}>What are you putting away?</div>
            {[['scan', 'Scan the label', 'New Zealand wines published on AIWine only — I’ll read the producer, wine and vintage.'],
              ['search', 'Find it in the library', 'Wines published by New Zealand wineries.'],
              ['manual', 'Enter it myself', 'Imports, gifts, old vintages — anything scanning can’t recognise.']].map(([m, t, d]) => (
              <div key={m} onClick={() => setMode(m)} style={{ padding: '18px 20px', borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', marginTop: 12, cursor: 'pointer' }}>
                <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)' }}>{t}</div>
                <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 5 }}>{d}</div>
              </div>
            ))}
          </div>
        )}

        {mode === 'scan' && (
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <div style={{ position: 'relative', width: 150, height: 240, margin: '0 auto', borderRadius: 14, background: 'radial-gradient(70% 60% at 50% 40%, #3B2C22, #140E0A)', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', left: 0, right: 0, height: 70, background: 'linear-gradient(to bottom, transparent, rgba(201,164,90,.45), transparent)', animation: 'aw-sweep 1.4s ease-in-out infinite' }} />
            </div>
            <div style={{ ...S.serif, fontSize: 23, marginTop: 22, color: 'var(--ink)' }}>Reading the label…</div>
            <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', marginTop: 8 }}>Matching against the New Zealand library</div>
            <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 14, lineHeight: 1.5, maxWidth: 260, marginLeft: 'auto', marginRight: 'auto' }}>Scanning recognises New Zealand wines published on AIWine. Anything else takes about fifteen seconds by hand.</div>
          </div>
        )}

        {mode === 'search' && (
          <div>
            <div style={{ ...S.serif, fontSize: 28, lineHeight: 1.1, marginTop: 10, color: 'var(--ink)' }}>Find it in the library</div>
            <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Winery, wine or grape" style={{ width: '100%', boxSizing: 'border-box', marginTop: 16, border: '1px solid var(--line)', borderRadius: 100, padding: '14px 18px', ...S.sans, fontSize: 14, background: 'var(--card)', color: 'var(--ink)', outline: 'none' }} />
            {results.map(w => (
              <div key={w.id} onClick={() => { AIW.addToCellar(w.id, 1, w.price); onAdded(w); }} style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '14px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
                <div style={{ width: 26, flex: 'none' }}><Bottle wine={w} h={54} glow={false} /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ ...S.serif, fontSize: 17, color: 'var(--ink)' }}>{w.vintage} {w.name}</div>
                  <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{w.winery}</div>
                </div>
                <div style={{ ...S.mono, fontSize: 9, color: 'var(--claret)' }}>Add</div>
              </div>
            ))}
            <div onClick={() => { onClose(); if (window.__aiwGo) window.__aiwGo('explore'); }} style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--line-soft)', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ ...S.sans, fontSize: 13, color: 'var(--claret)', fontWeight: 600 }}>Browse the whole library</div>
                <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 3 }}>Rather look than type? Explore by mood, food or region.</div>
              </div>
              <Ic name="chevron" size={14} color="var(--claret)" />
            </div>
            {q.trim().length > 1 && !results.length && (
              <div style={{ marginTop: 22 }}>
                <div style={{ ...S.sans, fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5 }}>Nothing in the library matches “{q}”. That’s common — plenty of good bottles aren’t sold here.</div>
                <div style={{ marginTop: 14 }}><Btn onClick={() => { setF(x => ({ ...x, name: q })); setMode('manual'); }}>Add it myself</Btn></div>
              </div>
            )}
          </div>
        )}

        {mode === 'manual' && (
          <div>
            <div style={{ ...S.serif, fontSize: 28, lineHeight: 1.1, marginTop: 10, color: 'var(--ink)' }}>Your bottle</div>
            <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8, marginBottom: 20 }}>Only the producer and wine are required. I’ll work out the rest — drinking window, matches, pairings.</div>
            {field('winery', 'Producer')}
            {field('name', 'Wine')}
            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ flex: 1 }}>{field('vintage', 'Vintage', { inputMode: 'numeric', placeholder: 'e.g. 2021' })}</div>
              <div style={{ flex: 1 }}>{field('variety', 'Grape', { placeholder: 'e.g. Nebbiolo' })}</div>
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ flex: 1 }}>{field('region', 'Region', { placeholder: 'e.g. Piedmont' })}</div>
              <div style={{ flex: 1 }}>{field('paid', 'Paid (NZD)', { inputMode: 'numeric', placeholder: 'optional' })}</div>
            </div>
            <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', marginBottom: 8 }}>Style</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
              {['light', 'medium-bodied', 'full-bodied'].map(s => <Chip key={s} active={f.style === s} onClick={() => setF(x => ({ ...x, style: s }))}>{s}</Chip>)}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
              <div style={{ ...S.sans, fontSize: 14, color: 'var(--ink)' }}>Bottles</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <button onClick={() => setF(x => ({ ...x, qty: Math.max(1, x.qty - 1) }))} style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid var(--line)', background: 'none', cursor: 'pointer', fontSize: 16, color: 'var(--ink)' }}>−</button>
                <div style={{ ...S.serif, fontSize: 21, width: 22, textAlign: 'center', color: 'var(--ink)' }}>{f.qty}</div>
                <button onClick={() => setF(x => ({ ...x, qty: Math.min(36, x.qty + 1) }))} style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid var(--line)', background: 'none', cursor: 'pointer', fontSize: 16, color: 'var(--ink)' }}>+</button>
              </div>
            </div>
            <div style={{ marginTop: 20 }}>
              <Btn full onClick={() => { if (!f.winery && !f.name) return; onAdded(AIW.addCustom(f)); }}>Add to cellar</Btn>
            </div>
            <button onClick={() => setMode('choose')} style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', background: 'none', border: 'none', width: '100%', marginTop: 12, cursor: 'pointer' }}>Back</button>
          </div>
        )}
      </div>
    </Sheet>
  );
}

function CellarEmpty({ onAdd, go }) {
  return (
    <Screen>
      <Eyebrow>Your cellar</Eyebrow>
      <div style={{ ...S.serif, fontSize: 40, lineHeight: 1.02, marginTop: 12, color: 'var(--ink)' }}>Your cellar<br />starts here.</div>
      <div style={{ ...S.sans, fontSize: 14, lineHeight: 1.6, color: 'var(--ink-soft)', marginTop: 16 }}>Scan a bottle, search the library, or type in something you already own — imports and gifts included. From then on I’ll tell you what’s ready, what’s peaking and what to open tonight.</div>
      <div style={{ marginTop: 24, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <Btn onClick={onAdd}>Add a bottle</Btn>
        <Btn kind="ghost" onClick={() => go('explore')}>Browse the library</Btn>
      </div>
      <div style={{ marginTop: 40, borderRadius: 18, border: '1px dashed var(--line)', padding: 22 }}>
        <Eyebrow>What a full cellar gives you</Eyebrow>
        {[['Drinking windows', 'I watch every bottle and tell you when it enters its window.'],
          ['Tonight’s answer', 'Ask what to open and I choose from what you actually own.'],
          ['A sharper palate', 'Every bottle you rate moves your taste profile.']].map(([t, d]) => (
          <div key={t} style={{ marginTop: 16 }}>
            <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)' }}>{t}</div>
            <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 4, lineHeight: 1.5 }}>{d}</div>
          </div>
        ))}
      </div>
    </Screen>
  );
}

function Cellar({ cellar, onWine, onAsk, onTaste, go, tick }) {
  const [view, setView] = React.useState('Bottles');
  const [adding, setAdding] = React.useState(false);
  const [flash, setFlash] = React.useState(null);
  const rows = cellar.map(c => ({ ...c, w: AIW.byId(c.id) })).filter(c => c.w);
  const total = rows.reduce((n, c) => n + c.qty, 0);
  const ready = rows.filter(c => c.w.ready);
  const low = rows.filter(c => c.qty <= 1);
  const added = w => { setAdding(false); setFlash(w.label || w.name); setTimeout(() => setFlash(null), 2500); go('cellar'); };

  if (!rows.length) return (
    <React.Fragment>
      <CellarEmpty onAdd={() => setAdding(true)} go={go} />
      <AddBottle open={adding} onClose={() => setAdding(false)} onAdded={added} />
    </React.Fragment>
  );

  return (
    <React.Fragment>
      <Screen>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Eyebrow>Your cellar</Eyebrow>
            <div style={{ ...S.serif, fontSize: 40, lineHeight: 1, marginTop: 10, color: 'var(--ink)' }}>{total} bottle{total === 1 ? '' : 's'}</div>
          </div>
          <button onClick={() => setAdding(true)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--line)', background: 'var(--card)', cursor: 'pointer', color: 'var(--claret)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 6 }}><Ic name="plus" size={18} /></button>
        </div>
        <div style={{ display: 'flex', gap: 22, marginTop: 20, paddingBottom: 20, borderBottom: '1px solid var(--line)' }}>
          {[[ready.length, 'ready to drink'], [rows.length, 'labels'], [low.length, 'running low']].map(([n, l]) => (
            <div key={l}><div style={{ ...S.serif, fontSize: 24, color: 'var(--ink)' }}>{n}</div><div style={{ ...S.mono, fontSize: 8.5, color: 'var(--muted)', marginTop: 4 }}>{l}</div></div>
          ))}
        </div>

        <div onClick={() => onAsk('What should I open from my cellar tonight?')} style={{ marginTop: 24, borderRadius: 18, background: 'var(--ink)', padding: 20, cursor: 'pointer' }}>
          <Eyebrow color="var(--brass-soft)">Your cellar today</Eyebrow>
          <div style={{ ...S.serif, fontSize: 24, color: 'var(--bone)', marginTop: 10, lineHeight: 1.18 }}>
            {ready.length ? `${ready.length} ${ready.length === 1 ? 'wine is' : 'wines are'} in their window` : 'Nothing is at its peak yet — everything here is still building.'}
            {low.length ? `, and ${low.length} ${low.length === 1 ? 'is' : 'are'} down to a last bottle.` : '.'}
          </div>
          <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--brass-soft)', fontWeight: 600, marginTop: 14 }}>Ask me what to open →</div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 26, marginBottom: 18 }}>
          {['Bottles', 'Racks', 'List'].map(v => <Chip key={v} active={view === v} onClick={() => setView(v)}>{v}</Chip>)}
        </div>

        {view === 'Bottles' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            {rows.map(c => (
              <div key={c.id} onClick={() => onWine(c.w)} style={{ cursor: 'pointer' }}>
                <div style={{ position: 'relative', height: 190, borderRadius: 14, background: `linear-gradient(170deg, ${c.w.tint}1F, var(--card) 60%)`, border: '1px solid var(--line)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 10 }}>
                  <Bottle wine={c.w} h={148} />
                  <div style={{ position: 'absolute', top: 10, left: 10, ...S.mono, fontSize: 8, color: 'var(--ink-soft)', background: 'rgba(250,246,238,.8)', borderRadius: 100, padding: '4px 7px' }}>×{c.qty}</div>
                  {c.w.ready && <div style={{ position: 'absolute', top: 10, right: 10, width: 7, height: 7, borderRadius: '50%', background: 'var(--green-bright)' }} />}
                  {c.w.custom && <div style={{ position: 'absolute', bottom: 8, left: 10, ...S.mono, fontSize: 7.5, color: 'var(--muted)' }}>Yours</div>}
                </div>
                <div style={{ ...S.serif, fontSize: 16, marginTop: 9, lineHeight: 1.2, color: 'var(--ink)' }}>{c.w.name}</div>
                <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{c.w.vintage} · {c.w.winery}</div>
              </div>
            ))}
          </div>
        )}

        {view === 'Racks' && (
          <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--bg-alt)', padding: 16 }}>
            {[['Reds', c => c.w.colour === 'Red'], ['Whites', c => c.w.colour === 'White'], ['Sparkling & rosé', c => c.w.colour === 'Sparkling' || c.w.colour === 'Rose']].map(([label, f]) => {
              const pool = rows.filter(f);
              const slots = Math.max(8, Math.ceil(pool.length / 8) * 8);
              return (
                <div key={label} style={{ marginBottom: 14 }}>
                  <Eyebrow style={{ marginBottom: 8 }}>{label} · {pool.length}</Eyebrow>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: 10, background: 'linear-gradient(#2A1D16,#1B1410)', borderRadius: 10 }}>
                    {Array.from({ length: slots }).map((_, i) => {
                      const c = pool[i];
                      return (
                        <div key={i} onClick={() => c && onWine(c.w)} style={{ width: 'calc(12.5% - 6px)', height: 54, borderRadius: 4, border: '1px solid rgba(244,239,229,.14)', background: c ? `linear-gradient(180deg, ${c.w.tint}, #150E0B)` : 'rgba(244,239,229,.05)', cursor: c ? 'pointer' : 'default', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 5 }}>
                          {c && <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'rgba(244,239,229,.35)' }} />}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
            <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)' }}>Tap a slot to open the bottle. Empty slots are yours to fill.</div>
          </div>
        )}

        {view === 'List' && rows.map(c => (
          <div key={c.id} onClick={() => onWine(c.w)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
            <div style={{ width: 4, height: 40, borderRadius: 2, background: c.w.tint, flex: 'none' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ ...S.serif, fontSize: 17, color: 'var(--ink)' }}>{c.w.vintage} {c.w.name}</div>
              <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{c.w.winery}{c.bought ? ' · added ' + c.bought : ''}{c.paid ? ' · $' + c.paid : ''}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ ...S.mono, fontSize: 9, color: c.w.ready ? 'var(--green)' : 'var(--muted)' }}>{c.w.ready ? 'Ready' : 'Hold'}</div>
              <div style={{ ...S.sans, fontSize: 12, color: 'var(--ink-soft)', marginTop: 3 }}>×{c.qty}</div>
            </div>
          </div>
        ))}

        <div style={{ height: 26 }} />
        <div onClick={() => onTaste(rows[0].w)} style={{ borderRadius: 16, border: '1px dashed var(--line)', padding: 18, textAlign: 'center', cursor: 'pointer' }}>
          <div style={{ ...S.serif, fontSize: 20, color: 'var(--ink)' }}>Drinking something tonight?</div>
          <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 6 }}>Tell me how it was — it takes one tap.</div>
        </div>
      </Screen>
      <AddBottle open={adding} onClose={() => setAdding(false)} onAdded={added} />
      <Toast msg={flash ? flash + ' is in your cellar.' : null} />
    </React.Fragment>
  );
}

/* ---------- tasting ---------- */
const TASTE_MORE = [
  { t: 'Loved the savouriness', axis: 'fresh', d: 6 }, { t: 'Loved the fruit', axis: 'fresh', d: -6 },
  { t: 'Too tannic', axis: 'tannin', d: -7 }, { t: 'Wanted more grip', axis: 'tannin', d: 7 },
  { t: 'Too oaky', axis: 'oak', d: -7 }, { t: 'Too light', axis: 'body', d: 6 },
  { t: 'Too heavy', axis: 'body', d: -6 }, { t: 'Too acidic', axis: 'fresh', d: 5 }
];

function TasteSheet({ wine, open, onClose, onSave, history }) {
  const [rating, setRating] = React.useState(null);
  const [more, setMore] = React.useState([]);
  const [step, setStep] = React.useState(1);
  React.useEffect(() => { if (open) { setRating(null); setMore([]); setStep(1); } }, [open, wine]);
  if (!wine) return null;
  const opts = [{ e: '♥', t: 'Loved it', v: 5 }, { e: '☺', t: 'Enjoyed it', v: 4 }, { e: '—', t: 'It was OK', v: 3 }, { e: '✕', t: 'Not for me', v: 2 }];
  const n = (history || []).length;

  return (
    <Sheet open={open} onClose={onClose} height="76%">
      <div className="aw-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '34px 22px 26px' }}>
        <Eyebrow>Tasting · {wine.vintage} {wine.winery}</Eyebrow>
        <div style={{ ...S.serif, fontSize: 32, lineHeight: 1.08, marginTop: 10, color: 'var(--ink)' }}>{step === 1 ? 'How was it?' : 'Tell me a little more'}</div>

        {step === 1 && (
          <div style={{ marginTop: 24 }}>
            {opts.map(o => (
              <div key={o.v} onClick={() => { setRating(o.v); setStep(2); }} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '18px', borderRadius: 16, border: '1px solid ' + (rating === o.v ? 'var(--claret)' : 'var(--line)'), marginBottom: 10, cursor: 'pointer', background: 'var(--card)' }}>
                <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--bg-alt)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--claret)', fontSize: 15 }}>{o.e}</div>
                <div style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>{o.t}</div>
              </div>
            ))}
            <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', textAlign: 'center', marginTop: 12 }}>One tap is enough. Everything else is optional.</div>
          </div>
        )}

        {step === 2 && (
          <div style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {TASTE_MORE.map(m => (
                <Chip key={m.t} active={more.includes(m.t)} onClick={() => setMore(x => x.includes(m.t) ? x.filter(y => y !== m.t) : [...x, m.t])}>{m.t}</Chip>
              ))}
            </div>
            <div style={{ marginTop: 22, borderRadius: 16, background: 'var(--bg-alt)', padding: 16 }}>
              <Eyebrow>What this tells me</Eyebrow>
              <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 9 }}>
                {more.length
                  ? 'Your profile will shift towards ' + more.slice(0, 2).map(m => m.toLowerCase()).join(' and ') + ', and the next matches will follow.'
                  : n ? `This will be tasting number ${n + 1}. Each one sharpens the match scores you see.` : 'This is your first tasting — the moment your profile stops being a guess.'}
              </div>
            </div>
            <div style={{ marginTop: 22 }}><Btn full onClick={() => onSave(wine, rating, more)}>Save tasting</Btn></div>
            <button onClick={() => onSave(wine, rating, [])} style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', background: 'none', border: 'none', width: '100%', marginTop: 12, cursor: 'pointer' }}>Skip the detail</button>
          </div>
        )}
      </div>
    </Sheet>
  );
}

Object.assign(window, { Cellar, TasteSheet, AddBottle, TASTE_MORE });
