/* AIWine — PROFILE, taste, membership */
function Membership({ onChange }) {
  const plan = AIW.plan(), key = AIW.planKey();
  const member = key === 'connoisseur';
  const saved = AIW.savings(), spend = AIW.spend(), cost = member ? 108 : 0;
  const u = AIW.usage();
  return (
    <div style={{ borderRadius: 20, border: '1px solid var(--brass)', background: 'linear-gradient(160deg, #FBF6EA, #F1E7D2)', padding: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <Eyebrow color="var(--brass)">Membership</Eyebrow>
          <div style={{ ...S.serif, fontSize: 27, color: 'var(--ink)', marginTop: 9 }}>AIWine {plan.name}</div>
        </div>
        <div style={{ ...S.mono, fontSize: 8.5, border: '1px solid var(--brass)', borderRadius: 100, padding: '5px 9px', color: 'var(--brass)' }}>{member ? '$9 / month' : 'Free'}</div>
      </div>

      {member ? (
        <React.Fragment>
          <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 12 }}>10% off every bottle on top of any winery case discount, plus unlimited scanning and wine-list matching. Delivery is set by each winery.</div>
          <div style={{ display: 'flex', gap: 22, marginTop: 18, paddingTop: 16, borderTop: '1px solid rgba(169,134,84,.35)' }}>
            <div><div style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>${saved}</div><div style={{ ...S.mono, fontSize: 8, color: 'var(--muted)', marginTop: 4 }}>saved so far</div></div>
            <div><div style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>${cost}</div><div style={{ ...S.mono, fontSize: 8, color: 'var(--muted)', marginTop: 4 }}>membership a year</div></div>
          </div>
          <div style={{ ...S.sans, fontSize: 12.5, lineHeight: 1.5, color: saved >= cost ? 'var(--green)' : 'var(--ink-soft)', marginTop: 12 }}>
            {saved >= cost ? 'Your membership has paid for itself.' : `It pays for itself at $90 of wine a month — you're $${Math.max(0, Math.round((cost - saved) * 10))} of wine away this year.`}
          </div>
          {AIW.freeNextYear() && <div style={{ ...S.mono, fontSize: 9, color: 'var(--brass)', marginTop: 10 }}>Over $600 this year — next year is on us.</div>}
          <button onClick={() => { AIW.setPlan('taster'); onChange(); }} style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', background: 'none', border: 'none', padding: 0, marginTop: 14, cursor: 'pointer' }}>Manage membership</button>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 12 }}>
            Your cellar, browsing and asking are free and always will be. Taster includes {plan.scans} label scans and {plan.lists} wine-list scan a month — you’ve used {u.scans} and {u.lists}.
          </div>
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(169,134,84,.35)' }}>
            <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)' }}>Connoisseur · $9 a month</div>
            {['10% off every bottle', 'Unlimited scanning & wine-list matching', 'Deeper taste profile'].map(b => (
              <div key={b} style={{ display: 'flex', gap: 9, alignItems: 'center', marginTop: 9 }}>
                <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. Spend over $600 in a year and the next year is free.</div>
            <div style={{ marginTop: 16 }}><Btn full kind="gilt" onClick={() => { if (AIW.join() === 'local') onChange(); }}>Become a Connoisseur</Btn></div>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

function InstallRow() {
  const [state, setState] = React.useState('idle');
  const standalone = typeof window !== 'undefined' && (window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone);
  const ios = typeof navigator !== 'undefined' && /iPhone|iPad|iPod/.test(navigator.userAgent);
  if (standalone || state === 'done') return null;
  const install = async () => {
    const p = window.__aiwInstall;
    if (!p) { setState('how'); return; }
    p.prompt();
    const r = await p.userChoice;
    setState(r && r.outcome === 'accepted' ? 'done' : 'idle');
  };
  return (
    <div style={{ borderRadius: 20, border: '1px solid var(--line)', background: 'var(--card)', padding: 20, display: 'flex', gap: 16, alignItems: 'center' }}>
      <img src="icons/icon-192.png" alt="AIWine" style={{ width: 54, height: 54, borderRadius: 13, flex: 'none' }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)', lineHeight: 1.15 }}>Keep AIWine on your home screen</div>
        <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 5, lineHeight: 1.5 }}>
          {state === 'how'
            ? (ios ? 'Tap Share, then “Add to Home Screen”.' : 'Open your browser menu and choose “Install app”.')
            : 'Opens full screen, remembers your cellar, and works with a poor signal at the restaurant table.'}
        </div>
        {state !== 'how' && <div style={{ marginTop: 12 }}><Btn small onClick={install}>{ios ? 'How to add it' : 'Install AIWine'}</Btn></div>}
      </div>
    </div>
  );
}

function Profile({ profile, history, cellar, onWine, onAsk }) {
  const [, force] = React.useState(0);
  const [auth, setAuth] = React.useState(null);
  const [settings, setSettings] = React.useState(null);
  const p = profile || AIW.NEUTRAL;
  const rows = cellar.map(c => ({ ...c, w: AIW.byId(c.id) })).filter(c => c.w);
  const rated = history.map(h => ({ h, w: AIW.byId(h.id) })).filter(x => x.w);
  const count = (arr, k) => { const m = {}; arr.forEach(v => { if (v) m[v] = (m[v] || 0) + 1; }); return Object.entries(m).sort((a, b) => b[1] - a[1]).map(e => e[0]); };
  const loves = count(rated.filter(x => x.h.rating >= 4).map(x => x.w.variety));
  const inCellar = count(rows.map(c => c.w.variety)).filter(v => !loves.includes(v));
  const regions = [...new Set(rows.map(c => c.w.region).filter(Boolean))];
  const tryThese = AIW.recommend(AIW.wines.filter(w => !rows.some(c => c.id === w.id)), 3);
  const headline = !history.length ? 'A sketch, for now'
    : p.fresh > 58 ? 'Savoury, and getting bolder'
      : p.body < 45 ? 'Light, fresh and precise'
        : 'Balanced — and still moving';

  return (
    <Screen>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--claret)', color: 'var(--bone)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic name="passport" size={22} color="var(--bone)" /></div>
        <div>
          <div style={{ ...S.serif, fontSize: 30, lineHeight: 1, color: 'var(--ink)' }}>Your wine profile</div>
          <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', marginTop: 7 }}>{AIW.plan().name} · {history.length} tasting{history.length === 1 ? '' : 's'}</div>
        </div>
      </div>

      <div style={{ height: 26 }} />
      <AccountCard onAuth={(i) => setAuth(i)} onSignOut={() => { try { AIAccount.logout(); } catch (e) {} force(x => x + 1); }} />
      <AuthSheet open={!!auth} intent={auth} onClose={() => setAuth(null)} onDone={() => { setAuth(null); force(x => x + 1); }} />

      <div style={{ height: 26 }} />
      <div style={{ borderRadius: 20, background: 'var(--ink)', padding: 24, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -60, top: -60, width: 200, height: 200, borderRadius: '50%', background: 'radial-gradient(circle, rgba(201,164,90,.18), transparent 70%)' }} />
        <Eyebrow color="var(--brass-soft)">Your taste</Eyebrow>
        <div style={{ ...S.serif, fontSize: 30, color: 'var(--bone)', marginTop: 10, lineHeight: 1.1 }}>{headline}</div>
        <div style={{ marginTop: 26 }}>
          <Axis dark left="Light" right="Full" v={p.body} />
          <Axis dark left="Fresh" right="Rich" v={p.fresh} delay={90} />
          <Axis dark left="Soft" right="Tannic" v={p.tannin} delay={180} />
          <Axis dark left="Unoaked" right="Oaky" v={p.oak} delay={270} />
        </div>
        <div style={{ ...S.sans, fontSize: 12.5, lineHeight: 1.55, color: 'rgba(244,239,229,.7)', paddingTop: 8, borderTop: '1px solid rgba(244,239,229,.14)' }}>
          {history.length
            ? `Built from ${history.length} tasting${history.length === 1 ? '' : 's'} and ${rows.length} label${rows.length === 1 ? '' : 's'} in your cellar. It moves every time you tell me something.`
            : 'Built from your answers at sign-up. Rate a wine and it starts becoming yours.'}
        </div>
      </div>

      <div style={{ height: 26 }} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div style={{ borderRadius: 16, border: '1px solid var(--line)', padding: 16, background: 'var(--card)' }}>
          <Eyebrow>You love</Eyebrow>
          {loves.length ? loves.slice(0, 4).map(l => <div key={l} style={{ ...S.serif, fontSize: 17, color: 'var(--ink)', marginTop: 8 }}>{l}</div>)
            : <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8, lineHeight: 1.5 }}>Rate a wine four stars or more and it shows up here.</div>}
        </div>
        <div style={{ borderRadius: 16, border: '1px solid var(--line)', padding: 16, background: 'var(--card)' }}>
          <Eyebrow>In your cellar</Eyebrow>
          {inCellar.length ? inCellar.slice(0, 4).map(l => <div key={l} style={{ ...S.serif, fontSize: 17, color: 'var(--ink)', marginTop: 8 }}>{l}</div>)
            : <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8, lineHeight: 1.5 }}>Nothing put away yet.</div>}
        </div>
      </div>

      <div style={{ height: 32 }} />
      <SectionHead eyebrow="AIWine thinks" title="You should try these" />
      <Rail>
        {tryThese.map(w => (
          <div key={w.id} onClick={() => onWine(w)} style={{ flex: 'none', width: 150, cursor: 'pointer' }}>
            <div style={{ height: 170, borderRadius: 14, background: `linear-gradient(170deg, ${w.tint}22, var(--card))`, border: '1px solid var(--line)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 8 }}><Bottle wine={w} h={136} /></div>
            <div style={{ ...S.serif, fontSize: 16, marginTop: 9, lineHeight: 1.2, color: 'var(--ink)' }}>{w.name}</div>
            <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{w.winery}</div>
          </div>
        ))}
      </Rail>

      <div style={{ height: 34 }} />
      <InstallRow />

      <div style={{ height: 20 }} />
      <Membership onChange={() => force(x => x + 1)} />

      <div style={{ height: 34 }} />
      <SectionHead eyebrow="Your journey" title="Where you’ve been" />
      <div style={{ borderRadius: 18, border: '1px solid var(--line)', background: 'var(--card)', padding: 18 }}>
        <div style={{ display: 'flex', gap: 26 }}>
          {[[history.length, 'tasted'], [regions.length, 'regions'], [[...new Set(rows.map(c => c.w.winery))].length, 'wineries']].map(([n, l]) => (
            <div key={l}><div style={{ ...S.serif, fontSize: 22, color: 'var(--ink)' }}>{n}</div><div style={{ ...S.mono, fontSize: 8, color: 'var(--muted)', marginTop: 4 }}>{l}</div></div>
          ))}
        </div>
        <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 14, lineHeight: 1.5 }}>
          {regions.length ? 'Your passport fills as you taste and visit — every region and cellar door you record stays here.' : 'Your passport starts with your first bottle. Regions, wineries and cellar doors collect here.'}
        </div>
      </div>

      {rated.length > 0 && (
        <React.Fragment>
          <div style={{ height: 30 }} />
          <SectionHead eyebrow="Recent" title="What you’ve been drinking" />
          {rated.slice(0, 8).map(({ h, w }, i) => (
            <div key={i} onClick={() => onWine(w)} style={{ display: 'flex', gap: 14, padding: '15px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
              <div style={{ width: 4, borderRadius: 2, background: w.tint, flex: 'none' }} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                  <div style={{ ...S.serif, fontSize: 17, color: 'var(--ink)' }}>{w.name}</div>
                  <Stars n={h.rating} />
                </div>
                <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--muted)', marginTop: 5 }}>{h.when} · {h.place}</div>
                {h.note && <div style={{ ...S.serif, fontSize: 16, fontStyle: 'italic', color: 'var(--ink-soft)', marginTop: 7 }}>“{h.note}”</div>}
              </div>
            </div>
          ))}
        </React.Fragment>
      )}

      <div style={{ height: 30 }} />
      <div style={{ borderRadius: 16, border: '1px solid var(--line)', overflow: 'hidden' }}>
        {[['prefs', 'Preferences', 'Price range, grapes to skip'],
          ['delivery', 'Delivery & payment', 'Address and how you receive wine'],
          ['notify', 'Notifications', 'What is worth interrupting you for'],
          ['privacy', 'Privacy', 'What we hold, and how to take it back'],
          ['help', 'Help', 'Questions, contact, drinking well']].map(([id, s, note], i) => (
          <div key={id} onClick={() => setSettings(id)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, padding: '15px 16px', borderTop: i ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}>
            <div>
              <div style={{ ...S.sans, fontSize: 13.5, color: 'var(--ink)' }}>{s}</div>
              <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 3 }}>{note}</div>
            </div>
            <Ic name="chevron" size={14} color="var(--faint)" />
          </div>
        ))}
      </div>
      <div style={{ height: 16 }} />
      <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--faint)', textAlign: 'center' }}>AIWine · Martinborough, Aotearoa</div>

      <PrefsScreen open={settings === 'prefs'} onClose={() => setSettings(null)} onSaved={() => force(x => x + 1)} />
      <DeliveryScreen open={settings === 'delivery'} onClose={() => setSettings(null)} />
      <NotifyScreen open={settings === 'notify'} onClose={() => setSettings(null)} />
      <PrivacyScreen open={settings === 'privacy'} onClose={() => setSettings(null)} />
      <HelpScreen open={settings === 'help'} onClose={() => setSettings(null)} />
    </Screen>
  );
}

Object.assign(window, { Profile, Membership, InstallRow });
