// app/screen-cook.jsx — hands-busy cook mode. One step at a time, ingredient
// check-off, and count-up (stopwatch) timers that tick gently upward.

// match the current step to an ingredient group by keyword overlap
function activeGroupForStep(groups, stepText) {
  if (!groups.length) return null;
  const t = (stepText || '').toLowerCase();
  let best = null, bestScore = 0;
  groups.forEach((g) => {
    if (!g.title) return;
    const words = g.title.toLowerCase().split(/\s+/).filter((w) => w.length > 2);
    const score = words.reduce((s, w) => s + (t.includes(w) ? 1 : 0), 0);
    if (score > bestScore) { bestScore = score; best = g; }
  });
  return bestScore > 0 ? best : null;
}

function CookCheckRow({ id, line, highlight, scale }) {
  const { checkedFor, toggleChecked, scaleQuantities } = useApp();
  const checked = checkedFor(id).has(line);
  const display = scale && scale !== 1 ? scaleQuantities(line, scale) : line;
  return (
    <li>
      <label onClick={() => toggleChecked(id, line)} style={{ display: 'flex', alignItems: 'flex-start',
        gap: 12, padding: '10px 4px', cursor: 'pointer' }}>
        <span style={{ width: 22, height: 22, borderRadius: 5, marginTop: 1, flexShrink: 0,
          border: checked ? 'none' : '1.5px solid var(--ink-3)',
          background: checked ? 'linear-gradient(135deg, #f0a850, #c97818)' : 'transparent',
          color: '#1a1208', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {checked && <Icon.check size={13} stroke={3} />}
        </span>
        <span style={{ fontFamily: 'Spectral', fontSize: 17, lineHeight: 1.45,
          color: checked ? 'var(--ink-3)' : 'var(--ink)',
          textDecoration: checked ? 'line-through' : 'none',
          fontWeight: highlight && !checked ? 500 : 400 }}>{display}</span>
      </label>
    </li>
  );
}

function CookIngredients({ recipe, activeGroup, dense, scale }) {
  const { parseIngredientGroups } = useApp();
  const groups = parseIngredientGroups(recipe.ingredients);
  if (groups.length <= 1 && !groups[0]?.title) {
    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {(groups[0]?.items || []).map((l, i) => <CookCheckRow key={i} id={recipe.id} line={l} scale={scale} highlight />)}
      </ul>
    );
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {groups.map((g, gi) => {
        const isActive = activeGroup && g.title === activeGroup.title;
        return (
          <div key={gi} style={{ padding: '14px 16px',
            background: isActive ? 'rgba(240,168,80,0.06)' : 'rgba(255,255,255,0.025)',
            border: isActive ? '1px solid rgba(240,168,80,0.30)' : '1px solid var(--hairline)',
            borderRadius: 14 }}>
            {g.title && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
                  letterSpacing: '0.24em', textTransform: 'uppercase',
                  color: isActive ? 'var(--olive)' : 'var(--ink-3)' }}>{g.title}</span>
                <span style={{ flex: 1, height: 1, background: 'var(--hairline-2)' }} />
                {isActive && <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--olive)' }}>now</span>}
              </div>
            )}
            <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
              {g.items.map((l, i) => <CookCheckRow key={i} id={recipe.id} line={l} scale={scale} highlight={isActive} />)}
            </ul>
          </div>
        );
      })}
    </div>
  );
}

// ── Timers ──
function TimerChip({ t }) {
  const { toggleTimer, removeTimer } = useApp();
  const now = useNow(t.running);
  const secs = timerElapsed(t, now);
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '8px 10px 8px 12px',
      borderRadius: 999, background: t.running ? 'rgba(240,168,80,0.10)' : 'rgba(255,255,255,0.04)',
      border: `1px solid ${t.running ? 'rgba(240,168,80,0.30)' : 'var(--hairline)'}` }}>
      <span style={{ width: 10, height: 10, borderRadius: 999,
        background: t.running ? 'var(--olive)' : 'var(--ink-3)',
        boxShadow: t.running ? '0 0 0 4px rgba(240,168,80,0.18), 0 0 14px rgba(240,168,80,0.4)' : 'none' }} />
      <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.05 }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 15, fontWeight: 500,
          color: t.running ? 'var(--olive)' : 'var(--ink)' }}>{fmtTime(secs)}</span>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 9, fontWeight: 600,
          letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)',
          maxWidth: 110, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.label}</span>
      </div>
      <button onClick={() => toggleTimer(t.id)} title={t.running ? 'pause' : 'resume'}
        style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-2)',
          fontSize: 12, width: 22, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {t.running ? '❙❙' : '▶'}
      </button>
      <button onClick={() => removeTimer(t.id)} title="remove" style={{ background: 'transparent',
        border: 'none', cursor: 'pointer', color: 'var(--ink-3)', display: 'flex' }}>
        <Icon.x size={13} />
      </button>
    </div>
  );
}

function StepNumeral({ n, size, stroke }) {
  return (
    <span style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontWeight: 500, fontSize: size,
      lineHeight: 0.84, letterSpacing: '-0.04em', color: 'transparent',
      WebkitTextStroke: `${stroke}px var(--olive)`, flexShrink: 0 }}>
      {String(n).padStart(2, '0')}
    </span>
  );
}

function CookMode({ recipe }) {
  const { layout, back, openRecipe, cookStep, setCookStep, state, addTimer, parseIngredientGroups, settings } = useApp();
  const total = recipe.directions.length;
  const step = Math.min(cookStep(recipe.id), Math.max(0, total - 1));
  const groups = parseIngredientGroups(recipe.ingredients);
  const activeGroup = activeGroupForStep(groups, recipe.directions[step]);
  const isMobile = layout === 'mobile';
  const isTablet = layout === 'tablet';

  const goPrev = () => setCookStep(recipe.id, Math.max(0, step - 1));
  const goNext = () => {
    if (step >= total - 1) { setCookStep(recipe.id, 0); openRecipe(recipe.id); }
    else setCookStep(recipe.id, step + 1);
  };
  const last = step >= total - 1;

  // ── servings scaler — scales displayed quantities + the cost figure live ──
  // baseServings is the recipe's NATIVE serving count (the scale reference — the
  // listed quantities are for this many). The initial "cook for" count follows
  // the user's intent: a planned meal → its plannedServings; an unplanned cook →
  // the user's default planning preference; falling back to the recipe's own.
  const baseServings = window.LCDomain.costInfo(recipe).servingsCount || 4;
  const plannedEntry = React.useMemo(() => Object.entries(state.plan || {})
    .filter(([, e]) => e && !e.skip && e.recipeId === recipe.id)
    .sort((a, b) => (a[0] < b[0] ? -1 : 1))
    .map(([, e]) => e)[0] || null, [state.plan, recipe.id]);
  const initialServings = (plannedEntry && plannedEntry.plannedServings)
    || (settings && settings.defaultPlanningServings) || baseServings;
  const [servings, setServings] = React.useState(initialServings);
  const scale = baseServings ? servings / baseServings : 1;

  const TopDock = (
    <header style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 8 : 20,
      padding: isMobile ? '38px 14px 12px' : '16px 32px',
      paddingTop: isMobile ? 'var(--lc-mobile-top, 38px)' : 16, borderBottom: '1px solid var(--hairline)',
      flexShrink: 0, flexWrap: 'wrap' }}>
      <button onClick={() => { openRecipe(recipe.id); }} style={{ display: 'inline-flex', alignItems: 'center',
        gap: 7, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--hairline)',
        borderRadius: 999, padding: isMobile ? '8px 12px' : '9px 14px', cursor: 'pointer',
        color: 'var(--ink-2)', fontFamily: 'Bricolage Grotesque', fontSize: 13, fontWeight: 500 }}>
        {isMobile ? '✕' : '← Exit'}
      </button>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0, flex: isMobile ? 1 : 'none' }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 600, fontSize: isMobile ? 12 : 15,
          color: 'var(--ink)', letterSpacing: '-0.02em', lineHeight: 1.1, whiteSpace: 'nowrap',
          overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? 180 : 320 }}>
          {recipe.name.split(' with ')[0]}
        </span>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 9, fontWeight: 600,
          letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
          Cook · {step + 1}/{total}
        </span>
      </div>

      {!isMobile && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 12 }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {Array.from({ length: total }).map((_, i) => (
              <span key={i} style={{ height: 4, width: i === step ? 30 : 14, borderRadius: 999,
                background: i <= step ? 'var(--olive)' : 'var(--paper-3)' }} />
            ))}
          </div>
        </div>
      )}

      <div style={{ marginLeft: isMobile ? 0 : 'auto', display: 'flex', gap: 8, alignItems: 'center',
        flexWrap: 'wrap' }}>
        {!isMobile && <CookScaleControl recipe={recipe} servings={servings} setServings={setServings} compact={isTablet} />}
        {state.timers.map((t) => <TimerChip key={t.id} t={t} />)}
        <button onClick={() => addTimer(activeGroup ? `${activeGroup.title}` : `Step ${step + 1}`)}
          title="Start a count-up timer" style={{ display: 'inline-flex', alignItems: 'center', gap: 6,
            height: 40, padding: '0 14px', borderRadius: 999, background: 'rgba(255,255,255,0.04)',
            border: '1px solid var(--hairline)', color: 'var(--ink-2)', cursor: 'pointer',
            fontFamily: 'Bricolage Grotesque', fontSize: 12, fontWeight: 500 }}>
          <Icon.clock size={15} />{isMobile ? '' : 'Start timer'}
        </button>
      </div>
    </header>
  );

  // mobile progress pips under dock
  const MobilePips = (
    <div style={{ padding: '8px 14px', display: 'flex', gap: 4, flexShrink: 0 }}>
      {Array.from({ length: total }).map((_, i) => (
        <span key={i} style={{ height: 4, flex: 1, borderRadius: 999,
          background: i <= step ? 'var(--olive)' : 'var(--paper-3)' }} />
      ))}
    </div>
  );

  const StepBlock = (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: isMobile ? 14 : 32 }}>
      <StepNumeral n={step + 1} size={isMobile ? 80 : (isTablet ? 150 : 200)} stroke={isMobile ? 1 : 1.5} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: isMobile ? 9 : 11, fontWeight: 600,
          letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--olive)' }}>
          Method · step {step + 1}{activeGroup ? ` · ${activeGroup.title}` : ''}
        </span>
        <p style={{ fontFamily: 'Spectral', fontWeight: 400, fontSize: isMobile ? 20 : (isTablet ? 24 : 28),
          lineHeight: 1.5, color: 'var(--ink)', margin: isMobile ? '10px 0 0' : '16px 0 0' }}>
          {recipe.directions[step]}
        </p>
      </div>
    </div>
  );

  const FooterBtns = (
    <div style={{ display: 'flex', gap: isMobile ? 8 : 12 }}>
      <FButton size={isMobile ? 'm' : 'l'} variant="ghost" onClick={goPrev}
        disabled={step === 0}
        style={{ minHeight: isMobile ? 54 : 64, opacity: step === 0 ? 0.4 : 1,
          padding: isMobile ? '14px 16px' : undefined }}>
        ←{isMobile ? '' : ' Previous step'}
      </FButton>
      <FButton size={isMobile ? 'l' : 'xl'} onClick={goNext}
        style={{ flex: 1, minHeight: isMobile ? 54 : 64, fontSize: isMobile ? 15 : undefined }}>
        {last ? 'Finish cooking' : 'Done — next step'} <span style={{ fontSize: isMobile ? 16 : 22 }}>→</span>
      </FButton>
    </div>
  );

  const IngredientPanel = (
    <>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
          letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--olive)' }}>
          {activeGroup ? 'For this step' : 'Ingredients'}
        </span>
        <span style={{ flex: 1, height: 1, background: 'var(--hairline-2)' }} />
      </div>
      {activeGroup && (
        <h3 style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 600, fontSize: 24, lineHeight: 1.05,
          letterSpacing: '-0.03em', color: 'var(--ink)', margin: '4px 0 0' }}>
          {activeGroup.title}<span style={{ fontFamily: 'Spectral', fontStyle: 'italic',
            fontWeight: 400, color: 'var(--olive)' }}>.</span>
        </h3>
      )}
      <div style={{ marginTop: 8 }}><CookIngredients recipe={recipe} activeGroup={activeGroup} scale={scale} /></div>
      <div style={{ marginTop: 'auto', paddingTop: 14, fontFamily: 'Spectral', fontStyle: 'italic',
        fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.5 }}>
        Tap items to check them off as you measure.
      </div>
    </>
  );

  if (isMobile) {
    return (
      <Shell chrome="none">
        {TopDock}
        {MobilePips}
        <div data-app-scroll style={{ flex: 1, overflowY: 'auto', minHeight: 0, padding: '14px 18px' }}>
          {StepBlock}
          <div style={{ marginTop: 18, display: 'flex', justifyContent: 'center' }}>
            <CookScaleControl recipe={recipe} servings={servings} setServings={setServings} compact />
          </div>
          <div style={{ marginTop: 16, padding: '14px 14px', background: 'rgba(240,168,80,0.06)',
            border: '1px solid rgba(240,168,80,0.30)', borderRadius: 12 }}>
            <CookIngredients recipe={recipe} activeGroup={activeGroup} scale={scale} dense />
          </div>
        </div>
        <div style={{ padding: '12px 18px 22px', borderTop: '1px solid var(--hairline)', flexShrink: 0 }}>
          {FooterBtns}
        </div>
      </Shell>
    );
  }

  return (
    <Shell chrome="none">
      {TopDock}
      <main style={{ flex: 1, display: 'grid', gridTemplateColumns: isTablet ? '1fr 320px' : '1fr 380px',
        minHeight: 0 }}>
        <section data-app-scroll style={{ padding: isTablet ? '28px 36px 24px' : '36px 56px 28px',
          display: 'flex', flexDirection: 'column', gap: 28, overflowY: 'auto', minHeight: 0 }}>
          {StepBlock}
          <div style={{ flex: 1 }} />
          <div style={{ paddingTop: 22, borderTop: '1px solid var(--hairline)' }}>{FooterBtns}</div>
        </section>
        <aside style={{ borderLeft: '1px solid var(--hairline)', padding: '28px 24px',
          display: 'flex', flexDirection: 'column', gap: 12, minHeight: 0, overflowY: 'auto' }}>
          {IngredientPanel}
        </aside>
      </main>
    </Shell>
  );
}

function CookScreen() {
  const { getRecipe, state } = useApp();
  const recipe = getRecipe(state.params.recipeId);
  if (!recipe) return <Shell chrome="none"><div style={{ padding: 48 }}>Recipe not found.</div></Shell>;
  return <CookMode recipe={recipe} />;
}

Object.assign(window, { CookScreen });
