/* ───────────────────────────────────────────────
   Happy Guts — Foods list + Food detail
   Exposed: FoodsScreen, FoodDetail, FoodRow, verdictExplain
   ─────────────────────────────────────────────── */

function verdictExplain(food, sens, prep) {
  const { verdict, flags } = window.computeVerdict(food, sens, prep);
  const bad = flags.filter(f => f.status === 'bad');
  const watch = flags.filter(f => f.status === 'watch');
  const unknown = flags.filter(f => f.status === 'unknown');
  const names = fs => fs.map(f => f.name.toLowerCase()).join(' & ');
  const unk = unknown.length ? ` No data yet for ${names(unknown)}.` : '';
  if (verdict === 'avoid')
    return `High in ${names(bad)} — which you're avoiding.${unk}`;
  if (verdict === 'caution') {
    if (watch.length) return `Moderate ${names(watch)} — fine in small amounts.${unk}`;
    return `No data yet for ${names(unknown)} — go carefully until it's been checked.`;
  }
  const active = window.activeCompounds(sens);
  if (active.length === 0) return 'Set up your sensitivities to get a personal rating.';
  return `Low in everything you're sensitive to. Enjoy.`;
}

/* ── FOOD ROW ─────────────────────────────── */
function FoodRow({ food, sens, go, trailing }) {
  const { verdict } = window.computeVerdict(food, sens);
  return (
    <button className="btn" onClick={() => go('food', { id: food.id })} style={{
      justifyContent: 'flex-start', gap: 13, padding: 12, width: '100%',
      background: 'var(--card)', boxShadow: 'var(--shadow-1)', borderRadius: 16,
    }}>
      <window.FoodTile food={food} size={46} radius={13} />
      <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
        {/* name wraps up to 2 lines instead of running under the verdict pill */}
        <div style={{
          fontWeight: 700, fontSize: 15.5, color: 'var(--ink)', lineHeight: 1.25,
          whiteSpace: 'normal', overflowWrap: 'anywhere',
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>{food.name}</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {food.cat} · {food.note}
        </div>
      </div>
      {/* the pill keeps its own column — text can never sit behind it */}
      <div style={{ flexShrink: 0, display: 'flex' }}>
        {trailing || <window.VerdictPill verdict={verdict} />}
      </div>
    </button>
  );
}

/* ── FOODS LIST ───────────────────────────── */
function FoodsScreen({ sens, go }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');

  const rows = window.FOODS
    .map(f => ({ f, v: window.computeVerdict(f, sens).verdict }))
    .filter(({ f }) => f.name.toLowerCase().includes(q.toLowerCase()) || f.cat.toLowerCase().includes(q.toLowerCase()))
    .filter(({ v }) => filter === 'all' || v === filter)
    .sort((a, b) => a.f.name.localeCompare(b.f.name));

  const counts = window.FOODS.reduce((acc, f) => {
    acc[window.computeVerdict(f, sens).verdict]++; return acc;
  }, { safe: 0, caution: 0, avoid: 0 });

  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 20 }}>
      <window.TopBar title="Foods" sub={`${window.FOODS.length} foods · checked for you`} large />

      <div style={{ padding: '6px 20px 0' }}>
        {/* search */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--card)',
          boxShadow: 'var(--shadow-1)', borderRadius: 14, padding: '11px 14px' }}>
          <window.Icon name="search" size={20} color="var(--ink-3)" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search foods or categories"
            style={{ border: 'none', background: 'transparent', flex: 1, fontSize: 15.5, fontFamily: 'var(--font-body)',
              color: 'var(--ink)', outline: 'none' }} />
          {q && <button className="btn" onClick={() => setQ('')} style={{ background: 'transparent', padding: 2 }}>
            <window.Icon name="x" size={18} color="var(--ink-3)" /></button>}
        </div>

        {/* verdict filter */}
        <div style={{ marginTop: 12 }}>
          <window.Segmented value={filter} onChange={setFilter} small options={[
            { v: 'all', label: 'All' },
            { v: 'safe', label: `Good ${counts.safe}` },
            { v: 'caution', label: `Easy ${counts.caution}` },
            { v: 'avoid', label: `Avoid ${counts.avoid}` },
          ]} />
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, padding: '14px 20px 0' }}>
        {rows.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', padding: 40, fontSize: 14 }}>No foods match.</div>
        )}
        {rows.map(({ f }) => <FoodRow key={f.id} food={f} sens={sens} go={go} />)}
      </div>
    </div>
  );
}

/* ── FOOD DETAIL ──────────────────────────── */
function FoodDetail({ id, sens, go, onAddToList }) {
  const food = window.FOODS.find(f => f.id === id);
  const [added, setAdded] = React.useState(false);
  const [prep, setPrep] = React.useState((food && food.prepDefault) || 'raw');
  if (!food) return null;
  const canPrep = window.hasPrep(food);
  const effLevels = window.effectiveLevels(food, prep);
  const deltas = window.prepDeltas(food);
  const { verdict, flags } = window.computeVerdict(food, sens, prep);
  const m = window.VERDICT_META[verdict];
  const active = window.activeCompounds(sens);

  // alternatives: safer foods in same category
  const alts = window.FOODS
    .filter(f => f.id !== food.id && f.cat === food.cat && window.computeVerdict(f, sens).verdict === 'safe')
    .slice(0, 4);
  const altFallback = alts.length === 0
    ? window.FOODS.filter(f => f.id !== food.id && window.computeVerdict(f, sens).verdict === 'safe').slice(0, 4)
    : alts;

  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 24 }}>
      <window.TopBar onBack={() => go('foods')} title="" right={
        <button className="btn" style={{ width: 38, height: 38, background: 'var(--card)', boxShadow: 'var(--shadow-1)' }}>
          <window.Icon name="star" size={20} color="var(--ink-3)" />
        </button>
      } />

      {/* header: square thumbnail beside the title */}
      <div style={{ padding: '0 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
        <window.FoodImage food={food} size={112} radius={24} />
        <div style={{ minWidth: 0 }}>
          <div className="eyebrow">{food.cat}</div>
          <h1 style={{ fontSize: 26, marginTop: 4 }}>{food.name}</h1>
        </div>
      </div>
      <div style={{ padding: '0 20px' }}>
        <p style={{ fontSize: 14.5, color: 'var(--ink-3)', marginTop: 12 }}>{food.note}</p>

        {/* verdict banner */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, background: m.tint, borderRadius: 18,
          padding: 16, marginTop: 16 }}>
          <window.VerdictDot verdict={verdict} size={16} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, color: m.ink }}>{m.label}</div>
            <div style={{ fontSize: 13.5, color: m.ink, opacity: 0.85, marginTop: 2, lineHeight: 1.35 }}>
              {verdictExplain(food, sens, prep)}
            </div>
          </div>
        </div>
      </div>

      {/* compound breakdown */}
      <div style={{ padding: '22px 20px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <window.SectionHead title="Compound breakdown" />
          {canPrep && (
            <div style={{ width: 150, flexShrink: 0 }}>
              <window.Segmented value={prep} onChange={setPrep} small
                options={[{ v: 'raw', label: 'Raw' }, { v: 'cooked', label: 'Cooked' }]} />
            </div>
          )}
        </div>
        {canPrep && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, background: 'var(--bg-2)',
            borderRadius: 12, padding: '9px 12px' }}>
            <window.Icon name="flame" size={16} color="var(--spark-ink)" />
            <span style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>
              {deltas.includes('oxalates') && (window.LEVEL_VALUE[food.cooked.oxalates] ?? 99) < (window.LEVEL_VALUE[food.levels.oxalates] ?? 99)
                ? 'Boiling & draining lowers oxalates — switch states to compare.'
                : 'Cooking changes the levels below.'}
            </span>
          </div>
        )}
        <div className="card" style={{ padding: 18, marginTop: 12, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {window.COMPOUNDS.map(c => {
            const changed = canPrep && deltas.includes(c.key);
            return (
              <div key={c.key}>
                <window.CompoundRow c={c} level={effLevels[c.key]} setting={sens[c.key]} />
                {changed && (
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginLeft: 104, marginTop: 4 }} className="mono">
                    RAW {window.levelMeta(food.levels[c.key]).label} → COOKED {window.levelMeta(food.cooked[c.key]).label}
                  </div>
                )}
              </div>
            );
          })}
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)',
            borderTop: '1px solid var(--line)', paddingTop: 12 }} className="mono">
            <span>NIL</span><span>LOW</span><span>MED</span><span>HIGH</span><span>V.HIGH</span>
          </div>
        </div>
        {active.length === 0 && (
          <p style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.4 }}>
            Greyed-out rows are compounds you're not sensitive to. Set them in Settings to personalise this.
          </p>
        )}
      </div>

      {/* alternatives */}
      {altFallback.length > 0 && verdict !== 'safe' && (
        <div style={{ padding: '22px 0 0' }}>
          <div style={{ padding: '0 20px' }}><window.SectionHead title="Safer swaps" /></div>
          <div style={{ display: 'flex', gap: 12, overflowX: 'auto', padding: '12px 20px 4px' }} className="scroll">
            {altFallback.map(f => (
              <button key={f.id} className="btn" onClick={() => go('food', { id: f.id })} style={{
                flexDirection: 'column', alignItems: 'flex-start', gap: 9, padding: 13, minWidth: 130,
                background: 'var(--card)', boxShadow: 'var(--shadow-1)', borderRadius: 18 }}>
                <window.FoodTile food={f} size={44} radius={13} />
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>{f.name}</div>
                </div>
                <window.VerdictPill verdict="safe" />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* add to list */}
      <div style={{ padding: '24px 20px 0' }}>
        <button className="btn btn-spark btn-block" onClick={() => { onAddToList(food.id); setAdded(true); setTimeout(() => setAdded(false), 1600); }}>
          {added ? <><window.Icon name="check" size={20} color="#fff" strokeWidth={3} /> Added to list</>
                 : <><window.Icon name="plus" size={20} color="#fff" /> Add to shopping list</>}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { FoodsScreen, FoodDetail, FoodRow, verdictExplain });
