// screens/cookmode.jsx — fullscreen, kitchen-optimized step-by-step
const CookMode = ({ locale, onExit }) => {
  const r = RECIPE;
  const [step, setStep] = useState(0);
  const [timerSec, setTimerSec] = useState(0);
  const [timerRun, setTimerRun] = useState(false);
  const [done, setDone] = useState({});
  const [dark, setDark] = useState(true);

  // Force dark on cookmode
  useEffect(() => {
    const root = document.documentElement;
    const prev = root.getAttribute('data-theme');
    if (dark) root.setAttribute('data-theme', 'dark');
    else root.setAttribute('data-theme', 'light');
    return () => { if (prev) root.setAttribute('data-theme', prev); };
  }, [dark]);

  useEffect(() => {
    let t;
    if (timerRun && timerSec > 0) {
      t = setInterval(() => setTimerSec(s => Math.max(0, s - 1)), 1000);
    }
    return () => clearInterval(t);
  }, [timerRun, timerSec]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onExit();
      if (e.key === 'ArrowRight') next();
      if (e.key === 'ArrowLeft') prev();
      if (e.key === ' ') { e.preventDefault(); setDone(d => ({ ...d, [step]: !d[step] })); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  const next = () => setStep(s => Math.min(r.steps.length - 1, s + 1));
  const prev = () => setStep(s => Math.max(0, s - 1));

  const current = r.steps[step];

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 50,
      background: 'var(--bg)', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column',
      animation: 'fadeUp .25s var(--ease)',
    }}>
      {/* top bar */}
      <header style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '14px 24px',
        borderBottom: '1px solid var(--line)',
      }}>
        <button onClick={onExit} className="btn btn-ghost btn-sm">
          <Icon name="close" size={14} /> {t(locale, 'exit_cook')}
        </button>
        <div style={{ flex: 1, textAlign: 'center' }}>
          <div className="eyebrow" style={{ color: 'var(--accent)' }}>
            <Icon name="flame" size={11} /> {t(locale, 'cook_mode')}
          </div>
          <div style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 2 }}>
            {r.titleI18n[locale] || r.title}
          </div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-ghost btn-sm" onClick={()=>setDark(d=>!d)} aria-label="Theme">
            <Icon name={dark ? 'sun' : 'moon'} size={14} />
          </button>
          <button className="btn btn-ghost btn-sm" aria-label="Keep screen awake">
            <Icon name="sparkle" size={12} /> Screen awake
          </button>
        </div>
      </header>

      {/* progress */}
      <div style={{ padding: '0 24px', display: 'flex', gap: 6, paddingTop: 14 }}>
        {r.steps.map((_, i) => (
          <button key={i} onClick={()=>setStep(i)} aria-label={`Step ${i+1}`}
                  style={{
                    flex: 1, height: 4, borderRadius: 999, border: 0,
                    background: i <= step ? 'var(--accent)' : 'var(--line-strong)',
                    transition: 'background .25s var(--ease)', cursor: 'pointer',
                  }} />
        ))}
      </div>

      {/* main content */}
      <main style={{
        flex: 1, overflow: 'auto', padding: 'clamp(24px, 4vw, 56px)',
        display: 'grid', gridTemplateColumns: '1fr 1.1fr',
        gap: 'clamp(24px, 4vw, 56px)', alignItems: 'center',
      }} className="cook-grid">
        <div>
          <div className="row" style={{ gap: 10, marginBottom: 'var(--s-6)' }}>
            <div className="display" style={{
              fontSize: 'clamp(64px, 10vw, 140px)', lineHeight: 1,
              color: 'var(--accent)', fontWeight: 600, fontVariantNumeric: 'tabular-nums',
            }}>{String(step + 1).padStart(2, '0')}</div>
            <div style={{ alignSelf: 'flex-end', paddingBottom: 18 }}>
              <div className="eyebrow" style={{ marginBottom: 6 }}>
                {t(locale, 'step')} {step + 1} {t(locale, 'of')} {r.steps.length}
              </div>
            </div>
          </div>

          <h1 className="display" style={{
            fontSize: 'clamp(32px, 4vw, 52px)', margin: '0 0 var(--s-5)',
            lineHeight: 1.05,
          }}>{current.title}</h1>

          <p style={{
            fontSize: 'clamp(18px, 1.6vw, 22px)', lineHeight: 1.5,
            color: 'var(--ink)', margin: '0 0 var(--s-6)', maxWidth: 540,
          }}>{current.body}</p>

          {current.timer && (
            <Timer min={current.timer} sec={timerSec} setSec={setTimerSec}
                   run={timerRun} setRun={setTimerRun} locale={locale} />
          )}

          <div className="row" style={{ gap: 10, marginTop: 'var(--s-8)' }}>
            <button className="btn btn-ghost btn-lg" onClick={prev} disabled={step === 0}
                    style={{ opacity: step === 0 ? 0.4 : 1, fontSize: 18 }}>
              <Icon name="arrowL" size={18} /> {t(locale, 'previous')}
            </button>
            {step < r.steps.length - 1 ? (
              <button className="btn btn-primary btn-lg" onClick={next}
                      style={{ fontSize: 18, paddingInline: 32 }}>
                {t(locale, 'next')} <Icon name="arrowR" size={18} />
              </button>
            ) : (
              <button className="btn btn-primary btn-lg" onClick={onExit}
                      style={{ fontSize: 18, paddingInline: 32 }}>
                <Icon name="check" size={18} /> Done
              </button>
            )}
          </div>

          <div style={{ marginTop: 'var(--s-8)', fontSize: 12, color: 'var(--ink-mute)',
                        fontFamily: 'var(--font-mono)', letterSpacing: '.06em' }}>
            <span>← → STEPS</span><span style={{ marginInline: 14, opacity: .4 }}>·</span>
            <span>SPACE MARK DONE</span><span style={{ marginInline: 14, opacity: .4 }}>·</span>
            <span>ESC EXIT</span>
          </div>
        </div>

        <Photo tone={current.tone || 'butter'} label={`step ${step + 1}`}
               ratio="4/5" radius="var(--r-5)"
               style={{ boxShadow: 'var(--shadow-lg)' }} />
      </main>

      {/* bottom bar: ingredients glance */}
      <footer style={{
        borderTop: '1px solid var(--line)',
        padding: '14px 24px',
        display: 'flex', alignItems: 'center', gap: 14, overflowX: 'auto',
      }}>
        <span className="eyebrow" style={{ whiteSpace: 'nowrap', color: 'var(--ink-mute)' }}>For this step</span>
        {ingredientsForStep(step).map((it, i) => (
          <span key={i} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px', borderRadius: 999,
            background: 'var(--bg-sunken)', border: '1px solid var(--line)',
            fontSize: 13, color: 'var(--ink-soft)', whiteSpace: 'nowrap',
          }}>
            <span className="num" style={{ color: 'var(--ink-strong)', fontWeight: 600 }}>{it.amt}</span>
            {it.name}
          </span>
        ))}
      </footer>

      <style>{`
        @media (max-width: 880px){
          .cook-grid { grid-template-columns: 1fr !important; gap: 24px !important; }
          .cook-grid > div:last-child { aspect-ratio: 4/3 !important; max-height: 38vh; }
        }
      `}</style>
    </div>
  );
};

const Timer = ({ min, sec, setSec, run, setRun, locale }) => {
  const totalSec = sec > 0 ? sec : min * 60;
  const mm = Math.floor(totalSec / 60).toString().padStart(2, '0');
  const ss = (totalSec % 60).toString().padStart(2, '0');
  return (
    <div className="row" style={{
      gap: 18, padding: 'var(--s-4) var(--s-5)',
      background: 'var(--accent-tint)', borderRadius: 'var(--r-4)',
      border: '1px solid var(--accent-soft)', width: 'fit-content',
    }}>
      <Icon name="timer" size={28} />
      <div className="display num" style={{
        fontSize: 48, fontWeight: 600, color: 'var(--ink-strong)',
        lineHeight: 1, letterSpacing: '-0.02em',
      }}>{mm}:{ss}</div>
      <button className="btn btn-primary btn-sm" onClick={()=>{
        if (sec === 0) setSec(min * 60);
        setRun(r => !r);
      }}>
        {run ? <><Icon name="pause" size={12} /> Pause</> : <><Icon name="play" size={12} /> Start</>}
      </button>
      <button className="btn btn-ghost btn-sm" onClick={()=>{ setRun(false); setSec(0); }}>Reset</button>
    </div>
  );
};

// quick map of steps→ingredient subset (illustrative)
function ingredientsForStep(stepIdx) {
  const map = [
    [{ amt: '227 g', name: 'butter' }],
    [{ amt: '200 g', name: 'brown sugar' }, { amt: '100 g', name: 'sugar' }, { amt: '2', name: 'eggs' }, { amt: '1', name: 'yolk' }, { amt: '10 g', name: 'vanilla' }],
    [{ amt: '280 g', name: 'AP flour' }, { amt: '60 g', name: 'bread flour' }, { amt: '6 g', name: 'salt' }, { amt: '5 g', name: 'baking soda' }, { amt: '300 g', name: 'chocolate' }],
    [{ amt: '24 h', name: 'in fridge' }],
    [{ amt: '375 °F', name: 'oven' }, { amt: '60 g', name: 'per ball' }],
    [{ amt: '2 g', name: 'flaky salt' }],
  ];
  return map[stepIdx] || [];
}

Object.assign(window, { CookMode });
