/* AIWine — app shell, member state, onboarding */
function Splash({ error, onRetry }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 34, textAlign: 'center' }}>
      <div style={{ width: 46, height: 46, borderRadius: '50%', background: 'var(--claret)', color: 'var(--bone)', display: 'flex', alignItems: 'center', justifyContent: 'center', ...S.serif, fontSize: 19 }}>A</div>
      <div style={{ ...S.serif, fontSize: 27, marginTop: 20, color: 'var(--ink)' }}>{error ? 'I can’t reach the wine library' : 'AIWine'}</div>
      <div style={{ ...S.sans, fontSize: 13, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 }}>{error ? 'The connection to the live wine library failed. Check the network and try again.' : 'Pouring the live library…'}</div>
      {error && <div style={{ marginTop: 20 }}><Btn onClick={onRetry}>Try again</Btn></div>}
    </div>
  );
}

const ONBOARD_Q = [
  { k: 'fresh', q: 'Which sounds more like you?', img: 'hero-vineyard.jpg', a: [{ t: 'Fresh & bright', v: 26 }, { t: 'Savoury & earthy', v: 68 }, { t: 'Somewhere between', v: 48 }] },
  { k: 'body', q: 'How do you like a wine to feel?', img: 'regions/martinborough.jpg', a: [{ t: 'Light and easy', v: 32 }, { t: 'Medium, food-friendly', v: 55 }, { t: 'Full and powerful', v: 78 }] },
  { k: 'tannin', q: 'And its grip?', img: 'regions/central-otago.jpg', a: [{ t: 'Soft and silky', v: 32 }, { t: 'Some structure', v: 55 }, { t: 'Firm — I like tannin', v: 76 }] },
  { k: 'oak', q: 'Last one. Oak?', img: 'regions/nelson.jpg', a: [{ t: 'Keep it clean', v: 14 }, { t: 'A little is nice', v: 42 }, { t: 'Bring the barrel', v: 72 }] }
];

function Onboarding({ onDone }) {
  const [step, setStep] = React.useState(0);
  const [p, setP] = React.useState({ ...AIW.NEUTRAL });
  const done = step >= ONBOARD_Q.length;
  const Q = ONBOARD_Q[Math.min(step, ONBOARD_Q.length - 1)];
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 100, background: 'var(--bg)' }}>
      {!done ? (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
          <div style={{ position: 'relative', height: 320, flex: 'none' }}>
            <img src={AIW.IMG + Q.img} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(20,12,8,.45), var(--bg) 97%)' }} />
            <div style={{ position: 'absolute', top: 62, left: 24, display: 'flex', gap: 6 }}>
              {ONBOARD_Q.map((_, i) => <div key={i} style={{ width: 22, height: 2, background: i <= step ? 'var(--bone)' : 'rgba(244,239,229,.35)' }} />)}
            </div>
          </div>
          <div className="aw-scroll" style={{ flex: 1, padding: '0 26px 26px', overflowY: 'auto' }}>
            <Eyebrow>Let’s get to know your taste</Eyebrow>
            <div style={{ ...S.serif, fontSize: 32, lineHeight: 1.08, marginTop: 12, color: 'var(--ink)' }}>{Q.q}</div>
            <div style={{ marginTop: 22 }}>
              {Q.a.map(a => (
                <div key={a.t} onClick={() => { setP(x => ({ ...x, [Q.k]: a.v })); setStep(s => s + 1); }} style={{ padding: '17px 20px', borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', marginBottom: 10, cursor: 'pointer', ...S.serif, fontSize: 21, color: 'var(--ink)' }}>{a.t}</div>
              ))}
            </div>
            <button onClick={() => onDone(p)} style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', marginTop: 4 }}>Skip — learn as I go</button>
          </div>
        </div>
      ) : (
        <div style={{ position: 'absolute', inset: 0, padding: '0 30px', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center' }}>
          <div style={{ width: 46, height: 46, borderRadius: '50%', background: 'var(--claret)', color: 'var(--bone)', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', ...S.serif, fontSize: 19 }}>A</div>
          <div style={{ ...S.serif, fontSize: 33, lineHeight: 1.1, marginTop: 22, color: 'var(--ink)' }}>Your taste profile<br />is ready.</div>
          <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-soft)', marginTop: 12 }}>A sketch for now. Every wine you rate, scan or buy sharpens it — you never have to fill in a form again.</div>
          <div style={{ marginTop: 26, textAlign: 'left' }}>
            <Axis left="Fresh" right="Rich" v={p.fresh} />
            <Axis left="Soft" right="Tannic" v={p.tannin} delay={120} />
          </div>
          <div style={{ marginTop: 18 }}><Btn full onClick={() => onDone(p)}>Start exploring</Btn></div>
        </div>
      )}
    </div>
  );
}

const TASTE_LABEL = { body: 'weight', fresh: 'savouriness', tannin: 'structure', oak: 'oak' };

function App() {
  const [loaded, setLoaded] = React.useState(false);
  const [error, setError] = React.useState(false);
  const [tab, setTab] = React.useState('home');
  const [detail, setDetail] = React.useState(null);
  const [buy, setBuy] = React.useState(null);
  const [taste, setTaste] = React.useState(null);
  const [seed, setSeed] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const [profile, setProfileState] = React.useState(AIW.profile);
  const [history, setHistory] = React.useState(AIW.history());
  const [cellar, setCellar] = React.useState(AIW.cellar());
  const [onboard, setOnboard] = React.useState(!AIW.state.onboarded);
  const [cart, setCart] = React.useState(AIW.cart());
  const [cartOpen, setCartOpen] = React.useState(false);
  const [insight, setInsight] = React.useState(null);
  const [tick, setTick] = React.useState(0);

  const load = React.useCallback(() => {
    setError(false);
    AIW.ready.then(() => setLoaded(true)).catch(() => setError(true));
  }, []);
  React.useEffect(load, []);

  // recompute every wine's match + explanation against the current profile
  React.useEffect(() => {
    if (!loaded) return;
    AIW.wines.forEach(w => { w.match = AIW.matchFor(w, profile); w.why = AIW.whyFor(w, profile, history); });
    setTick(t => t + 1);
  }, [loaded, profile, history]);

  const say = m => { setToast(m); setTimeout(() => setToast(null), 3600); };
  React.useEffect(() => { window.__aiwGo = (t) => { setDetail(null); setTab(t); }; }, []);
  const openWine = w => setDetail(w);
  const ask = q => { setDetail(null); setSeed(q || null); setTab('ask'); };
  const setProfile = p => { AIW.setProfile(p); setProfileState(p); };

  const saveTasting = (w, rating, more) => {
    const next = { ...(profile || AIW.NEUTRAL) };
    let moved = null;
    (more || []).forEach(t => {
      const m = TASTE_MORE.find(x => x.t === t);
      if (m) { next[m.axis] = Math.max(5, Math.min(95, next[m.axis] + m.d)); moved = m.axis; }
    });
    if (rating >= 4) ['tannin', 'body', 'fresh', 'oak'].forEach(k => { next[k] = Math.round(next[k] + (w.axes[k] - next[k]) * .10); });
    setProfile(next);
    setHistory(AIW.addTasting({ id: w.id, when: 'Just now', at: Date.now(), place: 'Recorded in the app', rating, note: (more || [])[0] || '' }));
    setCellar(AIW.drink(w.id));
    setInsight(moved
      ? { title: 'Noted — ' + (more[0] || '').toLowerCase() + '.', body: 'I’ve moved your ' + TASTE_LABEL[moved] + ' a little, and the next set of matches already reflects it.' }
      : { title: 'That’s recorded.', body: 'Your profile shifted slightly towards this wine’s shape. Keep rating and it gets sharper.' });
    setTaste(null);
    say('Tasting saved. Your taste profile just moved.');
  };

  const buyDone = ships => {
    let next = cellar;
    ships.forEach(g => g.items.forEach(i => { next = AIW.addToCellar(i.id, i.qty, i.w.price); }));
    setCellar(next);
    setCart(AIW.clearCart());
  };
  const addToCart = (w, qty) => { setCart({ ...AIW.addToCart(w.id, qty || 1) }); setCartOpen(true); };
  const setCartQty = (id, q) => setCart({ ...AIW.setCartQty(id, q) });

  if (!loaded) return <Device><StatusBar /><Splash error={error} onRetry={load} /></Device>;

  const owned = detail ? cellar.find(c => c.id === detail.id) : null;
  const shared = { onWine: openWine, onAsk: ask, profile, history, cellar, tick };

  return (
    <Device>
      <StatusBar />
      {tab === 'home' && <Home {...shared} go={setTab} insight={insight} onScan={() => ask('__winelist')} />}
      {tab === 'explore' && <Explore {...shared} />}
      {tab === 'ask' && <Ask {...shared} seed={seed} clearSeed={() => setSeed(null)} onBuy={w => addToCart(w, 1)} onAddCellar={w => { setCellar(AIW.addToCellar(w.id, 1, w.price)); say('Added to your cellar.'); }} />}
      {tab === 'cellar' && <Cellar {...shared} onTaste={setTaste} go={setTab} />}
      {tab === 'profile' && <Profile {...shared} />}

      <CartFab count={AIW.cartCount()} onClick={() => setCartOpen(true)} />
      <TabBar tab={tab} go={t => { setDetail(null); setTab(t); }} />

      {detail && <WineDetail w={detail} owned={owned} onBack={() => setDetail(null)} onAdd={addToCart} onOpenCart={() => setCartOpen(true)} cartCount={AIW.cartCount()} onAsk={ask} onTaste={setTaste} onWine={setDetail} />}
      <CartSheet open={cartOpen} cart={cart} onClose={() => setCartOpen(false)} onWine={w => { setCartOpen(false); setDetail(w); }} setQty={setCartQty} onCheckout={buyDone} tick={() => setTick(t => t + 1)} />
      <TasteSheet wine={taste} open={!!taste} onClose={() => setTaste(null)} onSave={saveTasting} history={history} />
      <Toast msg={toast} />
      {onboard && <Onboarding onDone={p => { setProfile(p); AIW.setOnboarded(); setOnboard(false); }} />}
    </Device>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
