/* ───────────────────────────────────────────────
   Happy Guts — Recipes, Shopping, Scan, Settings
   Exposed: RecipesScreen, ShoppingScreen, SettingsScreen, Switch  (ScanScreen: app/scanner.jsx)
   ─────────────────────────────────────────────── */

function Switch({ on, onChange, color = 'var(--spark)' }) {
  return (
    <button className="btn" onClick={() => onChange(!on)} style={{
      width: 50, height: 30, borderRadius: 999, padding: 0, flexShrink: 0,
      background: on ? color : 'var(--line-2)', justifyContent: 'flex-start',
      transition: 'background .2s',
    }}>
      <span style={{
        width: 24, height: 24, borderRadius: 99, background: '#fff', margin: 3,
        transform: on ? 'translateX(20px)' : 'translateX(0)',
        transition: 'transform .2s cubic-bezier(.2,.8,.2,1)', boxShadow: '0 1px 3px rgba(0,0,0,.25)',
      }} />
    </button>
  );
}

function recipeVerdict(recipe, sens) {
  let worst = 'safe';
  for (const id of recipe.ingredients) {
    const f = window.FOODS.find(x => x.id === id);
    if (!f) continue;
    const v = window.computeVerdict(f, sens).verdict;
    if (v === 'avoid') worst = 'avoid';
    else if (v === 'caution' && worst !== 'avoid') worst = 'caution';
  }
  return worst;
}

/* ── RECIPES ──────────────────────────────── */
function RecipesScreen({ sens, go }) {
  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 20 }}>
      <window.TopBar title="Recipes" sub="Meals built around your safe list" large />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '8px 20px 0' }}>
        {window.RECIPES.map(r => {
          const verdict = recipeVerdict(r, sens);
          return (
            <div key={r.id} className="card" style={{ overflow: 'hidden' }}>
              <div className="ph" style={{ height: 124 }}>
                <span>recipe photo · {r.id}.jpg</span>
                <div style={{ position: 'absolute', top: 12, left: 12 }}><window.VerdictPill verdict={verdict} /></div>
              </div>
              <div style={{ padding: 16 }}>
                <h2 style={{ fontSize: 19 }}>{r.name}</h2>
                <div style={{ display: 'flex', gap: 14, marginTop: 7, color: 'var(--ink-3)', fontSize: 13, fontWeight: 600 }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }}><window.Icon name="clock" size={15} color="var(--ink-3)" />{r.time}</span>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }}><window.Icon name="plate" size={15} color="var(--ink-3)" />Serves {r.serves}</span>
                </div>
                <p style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 10, lineHeight: 1.45 }}>{r.blurb}</p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 13 }}>
                  {r.ingredients.map(id => {
                    const f = window.FOODS.find(x => x.id === id);
                    if (!f) return null;
                    const v = window.computeVerdict(f, sens).verdict;
                    return (
                      <button key={id} className="btn" onClick={() => go('food', { id })} style={{
                        gap: 6, padding: '6px 11px 6px 8px', background: 'var(--bg-2)', borderRadius: 999,
                        fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>
                        <window.VerdictDot verdict={v} size={7} /> {f.name}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── SHOPPING LISTS ───────────────────────── */
function ShoppingScreen({ sens, list, setList, go }) {
  const [adding, setAdding] = React.useState(false);
  const done = list.items.filter(i => i.done).length;

  const toggle = (id) => setList(l => ({ ...l, items: l.items.map(i => i.id === id ? { ...i, done: !i.done } : i) }));
  const remove = (id) => setList(l => ({ ...l, items: l.items.filter(i => i.id !== id) }));
  const addFood = (foodId) => setList(l => l.items.some(i => i.foodId === foodId) ? l
    : ({ ...l, items: [...l.items, { id: 'x' + Date.now(), foodId, qty: '1', done: false }] }));

  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 20 }}>
      <window.TopBar title="Shopping Lists" sub={`${list.name} · ${done}/${list.items.length} done`} large
        right={<button className="btn btn-spark" onClick={() => setAdding(true)} style={{ width: 42, height: 42 }}>
          <window.Icon name="plus" size={22} color="#fff" /></button>} />

      {/* progress */}
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{ height: 8, borderRadius: 99, background: 'var(--bg-2)', overflow: 'hidden' }}>
          <div style={{ width: (list.items.length ? done / list.items.length * 100 : 0) + '%', height: '100%',
            background: 'var(--safe)', borderRadius: 99, transition: 'width .3s' }} />
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, padding: '16px 20px 0' }}>
        {list.items.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', padding: 40, fontSize: 14 }}>
            List is empty. Tap + to add foods.
          </div>
        )}
        {list.items.map(item => {
          const f = window.FOODS.find(x => x.id === item.foodId);
          if (!f) return null;
          const { verdict } = window.computeVerdict(f, sens);
          return (
            <div key={item.id} className="card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12 }}>
              <button className="btn" onClick={() => toggle(item.id)} style={{
                width: 28, height: 28, borderRadius: 9, flexShrink: 0,
                background: item.done ? 'var(--safe)' : 'transparent',
                boxShadow: item.done ? 'none' : 'inset 0 0 0 2px var(--line-2)' }}>
                {item.done && <window.Icon name="check" size={17} color="#fff" strokeWidth={3} />}
              </button>
              <window.FoodTile food={f} size={40} radius={11} />
              <button className="btn" onClick={() => go('food', { id: f.id })} style={{
                flex: 1, textAlign: 'left', background: 'transparent', padding: 0, flexDirection: 'column', alignItems: 'flex-start', gap: 1 }}>
                <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)',
                  textDecoration: item.done ? 'line-through' : 'none', opacity: item.done ? 0.5 : 1 }}>{f.name}</span>
                <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{item.qty}</span>
              </button>
              <window.VerdictDot verdict={verdict} size={11} />
              <button className="btn" onClick={() => remove(item.id)} style={{ background: 'transparent', padding: 4 }}>
                <window.Icon name="trash" size={18} color="var(--ink-3)" />
              </button>
            </div>
          );
        })}
      </div>

      <window.Sheet open={adding} onClose={() => setAdding(false)} title="Add to list">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {window.FOODS.filter(f => !list.items.some(i => i.foodId === f.id)).map(f => {
            const { verdict } = window.computeVerdict(f, sens);
            return (
              <button key={f.id} className="btn" onClick={() => addFood(f.id)} style={{
                justifyContent: 'flex-start', gap: 12, padding: 11, background: 'var(--card)',
                boxShadow: 'var(--shadow-1)', borderRadius: 14 }}>
                <window.FoodTile food={f} size={38} radius={10} />
                <span style={{ flex: 1, textAlign: 'left', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>{f.name}</span>
                <window.VerdictDot verdict={verdict} size={10} />
                <window.Icon name="plus" size={20} color="var(--spark)" />
              </button>
            );
          })}
        </div>
      </window.Sheet>
    </div>
  );
}

/* SCAN lives in app/scanner.jsx (camera + barcode reader + product lookup) */

/* ── SETTINGS ─────────────────────────────── */
function SettingsScreen({ sens, setSens, notif, setNotif, go, onReset }) {
  const Row = ({ children, last }) => (
    <div style={{ padding: '14px 16px', borderBottom: last ? 'none' : '1px solid var(--line)' }}>{children}</div>
  );
  return (
    <div className="scroll" style={{ height: '100%', paddingBottom: 24 }}>
      <window.TopBar title="Settings" large onBack={() => go('home')} />

      {/* sensitivities */}
      <div style={{ padding: '6px 20px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 10, paddingLeft: 2 }}>Your sensitivities</div>
        <div className="card" style={{ overflow: 'hidden' }}>
          {window.COMPOUNDS.map((c, idx) => (
            <div key={c.key} style={{ padding: '15px 16px', borderBottom: idx < 3 ? '1px solid var(--line)' : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 11 }}>
                <span style={{ width: 10, height: 10, borderRadius: 99, background: `var(${c.cssVar})` }} />
                <span style={{ fontWeight: 700, fontSize: 15.5 }}>{c.name}</span>
                <button className="btn" onClick={() => go('section', { key: c.key })}
                  style={{ marginLeft: 'auto', background: 'transparent', padding: 2 }}>
                  <window.Icon name="info" size={18} color="var(--ink-3)" /></button>
              </div>
              <window.YesNoMaybe value={sens[c.key]} onChange={v => setSens(s => ({ ...s, [c.key]: v }))} />
            </div>
          ))}
        </div>
      </div>

      {/* notifications */}
      <div style={{ padding: '20px 20px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 10, paddingLeft: 2 }}>Notifications</div>
        <div className="card" style={{ overflow: 'hidden' }}>
          {[
            { k: 'push',   t: 'Push notifications', s: 'Allow Happy Guts to alert you' },
            { k: 'expiry', t: 'Fresh-food reminders', s: 'Nudge before fresh foods go high-amine' },
            { k: 'newSafe',t: 'New safe foods',      s: 'When foods you can eat are added' },
          ].map((row, i) => (
            <div key={row.k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              borderBottom: i < 2 ? '1px solid var(--line)' : 'none' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 15 }}>{row.t}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 1 }}>{row.s}</div>
              </div>
              <Switch on={notif[row.k]} onChange={v => setNotif(n => ({ ...n, [row.k]: v }))} />
            </div>
          ))}
        </div>
      </div>

      {/* app: install status, offline, build */}
      <div style={{ padding: '20px 20px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 10, paddingLeft: 2 }}>App</div>
        <window.InstallCard />
      </div>

      {/* data */}
      <div style={{ padding: '20px 20px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 10, paddingLeft: 2 }}>Data</div>
        <div className="card" style={{ overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
            <window.Icon name="info" size={20} color="var(--ink-3)" />
            <div style={{ flex: 1, fontSize: 13.5, color: 'var(--ink-2)' }}>Your profile is stored on this device.</div>
          </div>
          <button className="btn" onClick={onReset} style={{ width: '100%', justifyContent: 'flex-start', gap: 12,
            padding: '14px 16px', background: 'transparent', color: 'var(--avoid)', fontWeight: 700, fontSize: 15 }}>
            <window.Icon name="trash" size={20} color="var(--avoid)" /> Reset & redo setup
          </button>
        </div>
        <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-3)', marginTop: 18 }} className="mono">
          Happy Guts · v0.1 preview
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { RecipesScreen, ShoppingScreen, SettingsScreen, Switch, recipeVerdict });
