/* ───────────────────────────────────────────────
   Happy Guts — Onboarding + Home
   Exposed: Onboarding, HomeScreen, BrandMark
   ─────────────────────────────────────────────── */
const { useState } = React;

function BrandMark({ size = 34 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
      <div style={{
        width: size, height: size, borderRadius: size * 0.32, background: 'var(--spark)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        boxShadow: '0 4px 12px oklch(0.66 0.20 33 / .4)',
      }}>
        <svg width={size * 0.62} height={size * 0.62} viewBox="0 0 24 24" fill="none">
          <path d="M12 21c-5-3-8-6.5-8-11A4.6 4.6 0 0 1 12 7a4.6 4.6 0 0 1 8 3c0 4.5-3 8-8 11Z" fill="#fff"/>
          <path d="M9.5 11.5c1 1.2 2 1.2 2.5 1.2s1.5 0 2.5-1.2" stroke="var(--spark)" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
      </div>
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size * 0.5, letterSpacing: '-0.03em' }}>
        Happy Guts
      </span>
    </div>
  );
}

/* ── ONBOARDING ─────────────────────────────── */
function Onboarding({ initial, onComplete }) {
  const COMPOUNDS = window.COMPOUNDS;
  const [step, setStep] = useState('welcome'); // welcome | 0..3 | review
  const [sens, setSens] = useState(initial || { gluten: 'no', salicylates: 'no', oxalates: 'no', amines: 'no' });
  const set = (k, v) => setSens(s => ({ ...s, [k]: v }));

  if (step === 'welcome') {
    return (
      <div className="scroll" style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '0 24px' }}>
        <div style={{ height: 64 }} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <BrandMark size={42} />
          <h1 style={{ fontSize: 40, lineHeight: 1.05, marginTop: 28, color: 'var(--ink)' }}>
            Eat with<br/>confidence again.
          </h1>
          <p style={{ fontSize: 17, color: 'var(--ink-2)', marginTop: 16, lineHeight: 1.45, maxWidth: 300 }}>
            Tell us what your body reacts to, and we'll flag every food, recipe and product for you — at a glance.
          </p>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, flexWrap: 'wrap' }}>
            {COMPOUNDS.map(c => (
              <span key={c.key} style={{
                fontSize: 13, fontWeight: 700, color: `var(${c.cssVar})`,
                background: 'var(--card)', boxShadow: 'var(--shadow-1)',
                borderRadius: 999, padding: '8px 13px',
              }}>{c.name}</span>
            ))}
          </div>
        </div>
        <div style={{ paddingBottom: 40 }}>
          <button className="btn btn-spark btn-block" onClick={() => setStep(0)}>
            Get started
            <window.Icon name="arrowR" size={20} color="#fff" />
          </button>
          <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-3)', marginTop: 14 }}>
            Takes about a minute · change anytime
          </p>
        </div>
      </div>
    );
  }

  if (step === 'review') {
    return (
      <div className="scroll" style={{ height: '100%', padding: '52px 20px 40px' }}>
        <div className="eyebrow">Step 3 of 3</div>
        <h1 style={{ fontSize: 30, marginTop: 8 }}>Here's your profile</h1>
        <p style={{ fontSize: 15.5, color: 'var(--ink-2)', marginTop: 10, lineHeight: 1.45 }}>
          Tap any answer to adjust. You can always change these later in Settings.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 22 }}>
          {COMPOUNDS.map(c => (
            <div key={c.key} className="card" style={{ padding: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <span style={{ width: 10, height: 10, borderRadius: 99, background: `var(${c.cssVar})` }} />
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17 }}>{c.name}</span>
              </div>
              <window.YesNoMaybe value={sens[c.key]} onChange={v => set(c.key, v)} />
            </div>
          ))}
        </div>
        <button className="btn btn-spark btn-block" style={{ marginTop: 22 }} onClick={() => onComplete(sens)}>
          Start using Happy Guts
        </button>
        <button className="btn btn-block" style={{ background: 'transparent', color: 'var(--ink-3)', marginTop: 4 }}
          onClick={() => setStep(3)}>Back</button>
      </div>
    );
  }

  // per-compound guided step
  const i = step;
  const c = COMPOUNDS[i];
  const pct = ((i + 1) / 4) * 100;
  const opts = [
    { v: 'yes',   t: 'Yes, I react to this',       c: 'var(--avoid)' },
    { v: 'maybe', t: 'Maybe / I\'m not sure',      c: 'var(--caution)' },
    { v: 'no',    t: 'No, this is fine for me',    c: 'var(--safe)' },
  ];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '52px 24px 32px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <button className="btn" onClick={() => setStep(i === 0 ? 'welcome' : i - 1)} style={{
          width: 36, height: 36, background: 'var(--card)', boxShadow: 'var(--shadow-1)',
        }}><window.Icon name="chevL" size={19} /></button>
        <div style={{ flex: 1, height: 6, borderRadius: 99, background: 'var(--bg-2)', overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: 'var(--spark)', borderRadius: 99, transition: 'width .3s' }} />
        </div>
        <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{i + 1}/4</span>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: 0 }}>
        <div style={{ flexShrink: 0 }}>
          <div style={{
            width: 84, height: 84, borderRadius: 24, background: `color-mix(in oklch, var(${c.cssVar}) 16%, white)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22,
          }}>
            <span style={{ width: 30, height: 30, borderRadius: 10, background: `var(${c.cssVar})` }} />
          </div>
          <div className="eyebrow" style={{ color: `var(${c.cssVar})` }}>Sensitivity {i + 1}</div>
          <h1 style={{ fontSize: 33, marginTop: 8 }}>Do you react to {c.name.toLowerCase()}?</h1>
          <p style={{ fontSize: 16, color: 'var(--ink-2)', marginTop: 12, lineHeight: 1.45 }}>{c.blurb}</p>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 26, flexShrink: 0 }}>
          {opts.map(o => {
            const on = sens[c.key] === o.v;
            return (
              <button key={o.v} className="btn" onClick={() => { set(c.key, o.v); setTimeout(() => setStep(i < 3 ? i + 1 : 'review'), 180); }}
                style={{
                  justifyContent: 'space-between', padding: '17px 18px', fontSize: 16, fontWeight: 700,
                  background: on ? `color-mix(in oklch, ${o.c} 14%, white)` : 'var(--card)',
                  color: on ? o.c : 'var(--ink)',
                  boxShadow: on ? `inset 0 0 0 2px ${o.c}` : 'var(--shadow-1)',
                }}>
                {o.t}
                <span style={{
                  width: 22, height: 22, borderRadius: 99, flexShrink: 0,
                  background: on ? o.c : 'transparent', boxShadow: on ? 'none' : 'inset 0 0 0 2px var(--line-2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{on && <window.Icon name="check" size={14} color="#fff" strokeWidth={3} />}</span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ── QUICK ACTIONS (home top cards, 3 layouts) ── */
function QuickActions({ go, layout }) {
  const items = [
    { key: 'foods',   icon: 'foods',   label: 'Foods',          sub: 'Browse & check',  target: 'foods' },
    { key: 'recipes', icon: 'recipes', label: 'Recipes',        sub: 'Safe meal ideas', target: 'recipes' },
    { key: 'lists',   icon: 'list',    label: 'Shopping Lists', sub: 'Plan your shop',  target: 'lists' },
    { key: 'scan',    icon: 'scan',    label: 'Barcode Scan',   sub: 'Check a product', target: 'scan', primary: true },
  ];

  const Card = ({ it, variant }) => {
    const primary = it.primary;
    const wide = variant === 'wide';
    const rowy = variant === 'row';
    return (
      <button className="btn" onClick={() => go(it.target)} style={{
        flexDirection: rowy ? 'row' : 'column',
        alignItems: rowy ? 'center' : 'flex-start',
        justifyContent: rowy ? 'flex-start' : 'space-between',
        gap: rowy ? 14 : (wide ? 10 : 12),
        textAlign: 'left', padding: rowy ? 14 : 16, borderRadius: 22,
        minHeight: rowy ? 0 : (wide ? 104 : 116),
        background: primary ? 'var(--spark)' : 'var(--card)',
        boxShadow: primary ? '0 8px 22px oklch(0.66 0.20 33 / .32)' : 'var(--shadow-1)',
        color: primary ? '#fff' : 'var(--ink)',
        width: '100%',
      }}>
        <span style={{
          width: 42, height: 42, borderRadius: 12, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: primary ? 'rgba(255,255,255,.2)' : 'var(--bg-2)',
        }}>
          <window.Icon name={it.icon} size={23} color={primary ? '#fff' : 'var(--ink)'} />
        </span>
        <div style={{ flex: rowy ? 1 : 'none' }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>{it.label}</div>
          <div style={{ fontSize: 12.5, fontWeight: 600, opacity: primary ? 0.85 : 0.5, marginTop: 1 }}>{it.sub}</div>
        </div>
        {rowy && <window.Icon name="chevR" size={20} color={primary ? '#fff' : 'var(--ink-3)'} />}
      </button>
    );
  };

  if (layout === 'list') {
    return <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {items.map(it => <Card key={it.key} it={it} variant="row" />)}
    </div>;
  }
  if (layout === 'feature') {
    const scan = items.find(i => i.primary);
    const rest = items.filter(i => !i.primary);
    return <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <Card it={scan} variant="wide" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {rest.map(it => <Card key={it.key} it={it} variant="col" />)}
      </div>
    </div>;
  }
  // grid (default)
  return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
    {items.map(it => <Card key={it.key} it={it} variant="col" />)}
  </div>;
}

/* ── HOME ──────────────────────────────────── */
function HomeScreen({ sens, go, t }) {
  const active = window.activeCompounds(sens);
  const safePicks = window.FOODS
    .map(f => ({ f, v: window.computeVerdict(f, sens).verdict }))
    .filter(x => x.v === 'safe').slice(0, 8);
  const watchOut = window.FOODS
    .map(f => ({ f, v: window.computeVerdict(f, sens).verdict }))
    .filter(x => x.v === 'avoid').slice(0, 6);

  const hour = new Date().getHours();
  const greet = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';

  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 24 }}>
      {/* header */}
      <div style={{ padding: '8px 20px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div className="eyebrow">{greet}</div>
          <h1 style={{ fontSize: 26, marginTop: 3 }}>Let's eat well.</h1>
        </div>
        <button className="btn" onClick={() => go('settings')} style={{
          width: 42, height: 42, background: 'var(--card)', boxShadow: 'var(--shadow-1)',
        }}><window.Icon name="sliders" size={22} /></button>
      </div>

      {/* install nudge (hidden once installed, or snoozed) */}
      <window.InstallBanner style={{ margin: '10px 20px 0' }} />

      {/* quick actions */}
      <div style={{ padding: '10px 20px 4px' }}>
        <QuickActions go={go} layout={t.homeLayout} />
      </div>

      {/* sensitivities summary */}
      <div style={{ padding: '18px 20px 4px' }}>
        <SectionHead title="Your sensitivities" actionLabel="Manage" onAction={() => go('settings')} />
        {active.length === 0 ? (
          <div className="card" style={{ padding: 16, marginTop: 10, display: 'flex', gap: 12, alignItems: 'center' }}>
            <window.Icon name="info" size={22} color="var(--ink-3)" />
            <div style={{ flex: 1, fontSize: 14, color: 'var(--ink-2)' }}>No sensitivities set yet.</div>
            <button className="btn btn-ghost" style={{ padding: '8px 14px', fontSize: 13 }} onClick={() => go('settings')}>Set up</button>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4, marginTop: 10 }} className="scroll">
            {window.COMPOUNDS.map(c => {
              const setting = sens[c.key];
              const label = setting === 'yes' ? 'Avoiding' : setting === 'maybe' ? 'Cautious' : 'Fine';
              const dim = setting === 'no';
              return (
                <button key={c.key} className="btn" onClick={() => go('section', { key: c.key })} style={{
                  flexDirection: 'column', alignItems: 'flex-start', gap: 8, padding: 14, minWidth: 124,
                  background: 'var(--card)', boxShadow: 'var(--shadow-1)', opacity: dim ? 0.6 : 1, borderRadius: 18,
                }}>
                  <span style={{ width: 14, height: 14, borderRadius: 5, background: `var(${c.cssVar})` }} />
                  <div style={{ textAlign: 'left' }}>
                    <div style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>{c.name}</div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: dim ? 'var(--ink-3)' : `var(${c.cssVar})` }}>{label}</div>
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* safe picks */}
      {safePicks.length > 0 && (
        <div style={{ padding: '18px 0 4px' }}>
          <div style={{ padding: '0 20px' }}>
            <SectionHead title="Good for you today" actionLabel="See all" onAction={() => go('foods')} />
          </div>
          <div style={{ display: 'flex', gap: 12, overflowX: 'auto', padding: '12px 20px 4px' }} className="scroll">
            {safePicks.map(({ f }) => (
              <button key={f.id} className="btn" onClick={() => go('food', { id: f.id })} style={{
                flexDirection: 'column', alignItems: 'flex-start', gap: 10, padding: 14, minWidth: 142,
                background: 'var(--card)', boxShadow: 'var(--shadow-1)', borderRadius: 20,
              }}>
                <window.FoodTile food={f} size={48} radius={14} />
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{f.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>{f.cat}</div>
                </div>
                <window.VerdictPill verdict="safe" />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* watch out */}
      {t.showWatchOut && watchOut.length > 0 && (
        <div style={{ padding: '14px 20px 4px' }}>
          <SectionHead title="Worth avoiding" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
            {watchOut.slice(0, 3).map(({ f }) => (
              <button key={f.id} className="btn" onClick={() => go('food', { id: f.id })} style={{
                justifyContent: 'flex-start', gap: 12, padding: 12, background: 'var(--card)',
                boxShadow: 'var(--shadow-1)', borderRadius: 16,
              }}>
                <window.FoodTile food={f} size={40} radius={11} />
                <div style={{ flex: 1, textAlign: 'left' }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{f.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{f.note}</div>
                </div>
                <window.VerdictDot verdict="avoid" size={12} />
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function SectionHead({ title, actionLabel, onAction }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
      <h2 style={{ fontSize: 19 }}>{title}</h2>
      {actionLabel && (
        <button className="btn" onClick={onAction} style={{
          background: 'transparent', color: 'var(--spark-ink)', fontSize: 13.5, fontWeight: 700, padding: 0,
        }}>{actionLabel}</button>
      )}
    </div>
  );
}

Object.assign(window, { Onboarding, HomeScreen, BrandMark, QuickActions, SectionHead });
