/* AIWine — HOME */
function AskBar({ onAsk, onScan }) {
  const hints = ['I’m cooking lamb tonight…', 'Something for Friday under $40', 'What’s ready to drink in my cellar?', 'I’m at a restaurant'];
  const [i, setI] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setI(v => (v + 1) % hints.length), 3400); return () => clearInterval(t); }, []);
  return (
    <div style={{ borderRadius: 20, padding: 18, background: 'linear-gradient(155deg, #4A1520 0%, var(--claret-deep) 60%, #24080F 100%)', boxShadow: '0 14px 34px rgba(58,14,24,.28)', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', right: -30, top: -40, width: 150, height: 150, borderRadius: '50%', background: 'radial-gradient(circle, rgba(201,164,90,.30), transparent 65%)' }} />
      <Eyebrow color="var(--brass-soft)">Ask AIWine</Eyebrow>
      <div onClick={() => onAsk()} style={{ marginTop: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(244,239,229,.09)', border: '1px solid rgba(244,239,229,.20)', borderRadius: 14, padding: '14px 15px' }}>
        <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--brass)', flex: 'none', animation: 'aw-pulse 2.4s ease-in-out infinite' }} />
        <div key={i} style={{ ...S.serif, fontSize: 17, color: 'rgba(244,239,229,.86)', animation: 'aw-fade .5s ease', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{hints[i]}</div>
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        <Chip dark onClick={() => onAsk()}>Type</Chip>
        <Chip dark onClick={() => onAsk('voice')}>Speak</Chip>
        <Chip dark onClick={onScan}>Scan</Chip>
      </div>
    </div>
  );
}

function ForYouCard({ w, onWine, i }) {
  return (
    <div onClick={() => onWine(w)} style={{ flex: 'none', width: 236, scrollSnapAlign: 'start', cursor: 'pointer' }}>
      <div style={{ position: 'relative', height: 250, borderRadius: 18, overflow: 'hidden', background: `linear-gradient(168deg, ${w.tint}22 0%, var(--card) 55%)`, border: '1px solid var(--line)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
        <div style={{ position: 'absolute', top: 14, left: 14 }}><Match v={w.match} size={44} delay={i * 160} /></div>
        <div style={{ paddingBottom: 14 }}><Bottle wine={w} h={190} /></div>
      </div>
      <div style={{ marginTop: 13 }}>
        <Eyebrow>{w.region || w.variety}</Eyebrow>
        <div style={{ ...S.serif, fontSize: 21, lineHeight: 1.15, marginTop: 6, color: 'var(--ink)' }}>{w.name}</div>
        <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 3 }}>{w.winery}{w.vintage ? ' · ' + w.vintage : ''}</div>
        <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.5, color: 'var(--ink-soft)', marginTop: 9 }}>{w.why}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 11 }}>
          <Price v={w.price} /><span style={{ ...S.sans, fontSize: 12.5, color: 'var(--claret)', fontWeight: 600 }}>Explore wine →</span>
        </div>
      </div>
    </div>
  );
}

function Home({ onAsk, onScan, onWine, go, profile, history, cellar, insight }) {
  const hour = new Date().getHours();
  const greet = hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening';
  const day = new Date().toLocaleDateString('en-NZ', { weekday: 'long' });
  const sorted = AIW.recommend();                       // honours Preferences
  const foryou = sorted.slice(0, 3);
  const rows = cellar.map(c => ({ ...c, w: AIW.byId(c.id) })).filter(c => c.w);
  const ready = rows.filter(c => c.w.ready).slice(0, 3);
  const tonight = sorted.find(w => w.food && w.food.length) || sorted[0];
  const owned = tonight && rows.find(c => c.id === tonight.id);
  const region = AIW.REGIONS.find(r => !rows.some(c => (c.w.region || '').includes(r.name))) || AIW.REGIONS[0];
  const shown = insight || (history.length
    ? { title: 'Your palate is taking shape.', body: `${history.length} ${history.length === 1 ? 'tasting' : 'tastings'} recorded. Every one of them moves the match scores you see across the app.` }
    : { title: 'I’m still learning you.', body: 'Rate one wine — even one you drank last week — and these recommendations stop being a guess.' });

  return (
    <Screen>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 22 }}>
        <div>
          <Eyebrow>{day} · {AIW.wines.length} wines in the library</Eyebrow>
          <div style={{ ...S.serif, fontSize: 36, lineHeight: 1.05, marginTop: 10, color: 'var(--ink)' }}>{greet}</div>
          <div style={{ ...S.serif, fontSize: 20, fontStyle: 'italic', color: 'var(--muted)', marginTop: 4 }}>What are you in the mood for?</div>
        </div>
        <div onClick={() => go('profile')} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--line)', background: 'var(--card)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flex: 'none', marginTop: 6, color: 'var(--claret)' }}><Ic name="passport" size={18} /></div>
      </div>

      <AskBar onAsk={onAsk} onScan={onScan} />

      <div style={{ height: 38 }} />
      <SectionHead eyebrow="For you" title={history.length ? 'Three wines I think you’ll love' : 'Three places to start'} />
      <Rail>{foryou.map((w, i) => <ForYouCard key={w.id} w={w} onWine={onWine} i={i} />)}</Rail>

      {tonight && (
        <React.Fragment>
          <div style={{ height: 38 }} />
          <div onClick={() => onWine(tonight)} style={{ position: 'relative', height: 300, borderRadius: 20, overflow: 'hidden', cursor: 'pointer' }}>
            <img src={AIW.IMG + 'home-bg.jpg'} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(20,12,8,.92) 12%, rgba(20,12,8,.30) 55%, rgba(20,12,8,.45) 100%)' }} />
            <div style={{ position: 'absolute', inset: 0, padding: 22, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <Eyebrow color="var(--brass-soft)">Tonight</Eyebrow>
              <div>
                <div style={{ ...S.sans, fontSize: 12.5, color: 'rgba(244,239,229,.72)' }}>{tonight.food.length ? 'Good with ' + tonight.food.slice(0, 2).join(' or ') : 'My pick for this evening'}</div>
                <div style={{ ...S.serif, fontSize: 30, lineHeight: 1.1, color: 'var(--bone)', marginTop: 6 }}>{tonight.vintage} {tonight.winery} {tonight.name}</div>
                <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.5, color: 'rgba(244,239,229,.78)', marginTop: 8 }}>{tonight.why}</div>
                <div style={{ display: 'flex', gap: 10, marginTop: 16, alignItems: 'center' }}>
                  <Btn small kind="gilt">See why</Btn>
                  {owned && <Btn small kind="onDark">{owned.qty} in your cellar</Btn>}
                </div>
              </div>
            </div>
          </div>
        </React.Fragment>
      )}

      <div style={{ height: 38 }} />
      {rows.length ? (
        <React.Fragment>
          <SectionHead eyebrow="Your cellar today" title={ready.length ? `${ready.length} ${ready.length === 1 ? 'wine is' : 'wines are'} drinking beautifully` : 'Everything is still resting'} action="Open cellar" onAction={() => go('cellar')} />
          <div style={{ border: '1px solid var(--line)', borderRadius: 18, background: 'var(--card)', overflow: 'hidden' }}>
            {(ready.length ? ready : rows.slice(0, 3)).map((c, i) => (
              <div key={c.id} onClick={() => onWine(c.w)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderTop: i ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}>
                <div style={{ width: 34, flex: 'none' }}><Bottle wine={c.w} h={54} glow={false} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ ...S.serif, fontSize: 17, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.w.vintage} {c.w.name}</div>
                  <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>{c.w.peak}</div>
                </div>
                <div style={{ ...S.mono, fontSize: 9, color: 'var(--green)' }}>{c.qty} btl</div>
              </div>
            ))}
          </div>
        </React.Fragment>
      ) : (
        <div onClick={() => go('cellar')} style={{ borderRadius: 20, border: '1px dashed var(--line)', padding: 24, cursor: 'pointer' }}>
          <Eyebrow>Your cellar</Eyebrow>
          <div style={{ ...S.serif, fontSize: 26, lineHeight: 1.15, marginTop: 10, color: 'var(--ink)' }}>Your cellar starts here.</div>
          <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 8 }}>Scan a bottle or type in something you already own — imports and gifts included — and I’ll tell you when each one is ready.</div>
          <div style={{ ...S.sans, fontSize: 12.5, fontWeight: 600, color: 'var(--claret)', marginTop: 14 }}>Add a bottle →</div>
        </div>
      )}

      <div style={{ height: 38 }} />
      <div onClick={() => go('profile')} style={{ borderRadius: 20, background: 'var(--ink)', padding: 24, cursor: 'pointer', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -50, bottom: -60, width: 190, height: 190, borderRadius: '50%', border: '1px solid rgba(201,164,90,.28)' }} />
        <Eyebrow color="var(--brass-soft)">Your taste</Eyebrow>
        <div style={{ ...S.serif, fontSize: 27, lineHeight: 1.15, color: 'var(--bone)', marginTop: 12 }}>{shown.title}</div>
        <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'rgba(244,239,229,.72)', marginTop: 10 }}>{shown.body}</div>
        <div style={{ marginTop: 22 }}>
          <Axis dark left="Fresh" right="Rich" v={(profile || AIW.NEUTRAL).fresh} />
          <Axis dark left="Soft" right="Tannic" v={(profile || AIW.NEUTRAL).tannin} />
        </div>
        <div style={{ ...S.sans, fontSize: 12.5, fontWeight: 600, color: 'var(--brass-soft)', marginTop: 4 }}>Explore your taste →</div>
      </div>

      <div style={{ height: 34 }} />
      <div onClick={() => go('explore')} style={{ display: 'flex', gap: 16, alignItems: 'center', cursor: 'pointer' }}>
        <img src={region.img} alt="" style={{ width: 96, height: 120, objectFit: 'cover', borderRadius: 14, flex: 'none' }} />
        <div>
          <Eyebrow>Keep exploring</Eyebrow>
          <div style={{ ...S.serif, fontSize: 22, lineHeight: 1.15, marginTop: 8, color: 'var(--ink)' }}>Ready to discover {region.name}?</div>
          <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8 }}>{region.line}</div>
        </div>
      </div>
      <div style={{ height: 20 }} />
      <div style={{ ...S.mono, fontSize: 9, color: 'var(--faint)', textAlign: 'center' }}>AIWine · your personal wine companion</div>
    </Screen>
  );
}

Object.assign(window, { Home });
