/* ───────────────────────────────────────────────
   Happy Guts — per-sensitivity Section pages
   Exposed: SectionScreen
   ─────────────────────────────────────────────── */

const SECTION_INFO = {
  gluten: {
    about: 'Gluten is a protein in wheat, barley and rye that gives dough its stretch. People with coeliac disease or non-coeliac sensitivity can react to even small traces hidden in sauces, processed meats and beer.',
    tipTitle: 'Naturally gluten-free', tips: ['Rice, corn & quinoa', 'Plain meat, fish & eggs', 'Fruit & vegetables'],
  },
  salicylates: {
    about: 'Salicylates are natural chemicals plants make to defend themselves. They concentrate in many fruits, vegetables, herbs, spices, tea and some additives — and in aspirin. Peeling produce and choosing very ripe, mild fruit lowers the dose.',
    tipTitle: 'Lower-salicylate picks', tips: ['Peeled pear & potato', 'Cabbage & celery', 'Plain meat & rice'],
  },
  oxalates: {
    about: 'Oxalates are compounds found across many plants, highest in leafy greens, nuts, seeds and some roots. For sensitive people a high intake may add to kidney-stone risk and other symptoms. Boiling and draining greens lowers the load.',
    tipTitle: 'Lower-oxalate picks', tips: ['White rice & eggs', 'Cabbage & cucumber', 'Most fresh meat & fish'],
  },
  amines: {
    about: 'Amines build up as proteins break down — so aged, cured, fermented, canned and overripe foods are highest. Histamine is the best-known. Eating food very fresh and avoiding leftovers keeps amines low.',
    tipTitle: 'Lower-amine habits', tips: ['Buy & cook meat fresh', 'Skip aged cheese', 'Eat fruit before it over-ripens'],
  },
};

const GROUPS = [
  { v: 'safe', label: 'Lower', levels: ['Nil', 'Low'] },
  { v: 'mod',  label: 'Some',  levels: ['Med'] },
  { v: 'high', label: 'Higher',levels: ['High', 'V.High'] },
  { v: 'unknown', label: 'Unknown', levels: ['Unknown'] },
];

function SectionScreen({ ckey, sens, setSens, go }) {
  const c = window.COMPOUNDS.find(x => x.key === ckey);
  const info = SECTION_INFO[ckey];
  const [group, setGroup] = React.useState('safe');
  if (!c) return null;

  const setting = sens[ckey];
  const settingLabel = setting === 'yes' ? "You're avoiding this" : setting === 'maybe' ? "You're keeping an eye on this" : "Not a concern for you";

  const grp = GROUPS.find(g => g.v === group);
  const foods = window.FOODS
    .filter(f => grp.levels.includes(f.levels[ckey]))
    .sort((a, b) => window.LEVEL_VALUE[a.levels[ckey]] - window.LEVEL_VALUE[b.levels[ckey]] || a.name.localeCompare(b.name));

  const tint = `color-mix(in oklch, var(${c.cssVar}) 14%, white)`;

  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 22 }}>
      {/* colored header */}
      <div style={{ background: tint, padding: '4px 20px 22px', borderRadius: '0 0 28px 28px' }}>
        <window.TopBar onBack={() => go('home')} title="" right={
          <span className="eyebrow" style={{ color: `var(${c.cssVar})` }}>Sensitivity</span>
        } />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '6px 0 0' }}>
          <span style={{ width: 52, height: 52, borderRadius: 16, background: `var(${c.cssVar})`, flexShrink: 0,
            boxShadow: `0 6px 16px color-mix(in oklch, var(${c.cssVar}) 45%, transparent)` }} />
          <div>
            <h1 style={{ fontSize: 30 }}>{c.name}</h1>
            <p style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 2 }}>{c.blurb}</p>
          </div>
        </div>
      </div>

      {/* your reaction */}
      <div style={{ padding: '18px 20px 0' }}>
        <div className="card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
            <span style={{ fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap' }}>Your reaction</span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{settingLabel}</span>
          </div>
          <window.YesNoMaybe value={setting} onChange={v => setSens(s => ({ ...s, [ckey]: v }))} />
        </div>
      </div>

      {/* about */}
      <div style={{ padding: '14px 20px 0' }}>
        <div className="card" style={{ padding: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>What it is</div>
          <p style={{ fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>{info.about}</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 14 }}>
            {info.tips.map(t => (
              <span key={t} style={{ fontSize: 12.5, fontWeight: 600, color: `var(${c.cssVar})`,
                background: tint, borderRadius: 999, padding: '6px 12px' }}>{t}</span>
            ))}
          </div>
        </div>
      </div>

      {/* foods by level */}
      <div style={{ padding: '20px 20px 0' }}>
        <window.SectionHead title={`Foods by ${c.name.toLowerCase()} level`} />
        <div style={{ marginTop: 12 }}>
          <window.Segmented value={group} onChange={setGroup} options={GROUPS} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginTop: 14 }}>
          {foods.length === 0 && <div style={{ textAlign: 'center', color: 'var(--ink-3)', padding: 30, fontSize: 14 }}>Nothing here.</div>}
          {foods.map(f => {
            const meta = window.levelMeta(f.levels[ckey]);
            const { verdict } = window.computeVerdict(f, sens);
            return (
              <button key={f.id} className="btn" onClick={() => go('food', { id: f.id })} style={{
                justifyContent: 'flex-start', gap: 13, padding: 12, background: 'var(--card)',
                boxShadow: 'var(--shadow-1)', borderRadius: 16, width: '100%' }}>
                <window.FoodTile food={f} size={44} radius={12} />
                <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <window.VerdictDot verdict={verdict} size={8} />
                    <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{f.name}</span>
                  </div>
                  <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
                    <window.CompoundBar level={f.levels[ckey]} height={7} />
                    <span className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: meta.color, width: 56, textAlign: 'right' }}>{meta.label}</span>
                  </div>
                  {window.prepDeltas(f).includes(ckey) && (() => {
                    // green when cooking lowers the level, amber when it raises it
                    const down = (window.LEVEL_VALUE[f.cooked[ckey]] ?? 99) < (window.LEVEL_VALUE[f.levels[ckey]] ?? 99);
                    const ink = down ? 'var(--safe-ink)' : 'var(--caution-ink)';
                    return (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 7,
                      fontSize: 11, fontWeight: 700, color: ink, background: down ? 'var(--safe-tint)' : 'var(--caution-tint)',
                      borderRadius: 999, padding: '3px 9px' }}>
                      <window.Icon name="flame" size={12} color={ink} />
                      Cooked → {window.levelMeta(f.cooked[ckey]).label}
                    </span>
                    );
                  })()}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SectionScreen, SECTION_INFO });
