function CookScreen({ onBack }) {
  useKitchenStore();
  const now = useNow();
  const data = window.KITCHEN_DATA.cook;
  const [activeCat, setActiveCat] = React.useState(data.categories[0].id);
  const [done, setDone] = React.useState(() => new Set());

  // Статус блюда по дедлайну. На сенсорном ТВ повар должен мгновенно
  // видеть «вот это горит, делай в первую очередь».
  const dishUrgency = (deadline) => {
    if (!deadline || !/^\d{2}:\d{2}$/.test(deadline)) return null;
    const cur = now.getHours() * 60 + now.getMinutes();
    const [h, m] = deadline.split(':').map(Number);
    const dl = h * 60 + m;
    const diff = dl - cur;
    if (diff < 0) return { label: 'просрочено', tone: 'overdue', color: '#B8420F', bg: '#FFE4D6' };
    if (diff <= 30) return { label: 'горит', tone: 'urgent', color: '#B8420F', bg: '#FFE4D6' };
    if (diff <= 90) return { label: 'скоро', tone: 'soon',   color: '#7a5a0f', bg: '#FFF6DC' };
    return null;
  };

  // Сортировка: горящее сверху, готовое уходит вниз. Внутри одной группы —
  // по дедлайну. Если дедлайна нет — в конец.
  const URG_ORDER = { overdue: 0, urgent: 1, soon: 2 };
  const dishes = (data.dishes[activeCat] || []).slice().sort((a, b) => {
    const ad = done.has(a.id), bd = done.has(b.id);
    if (ad !== bd) return ad ? 1 : -1;
    const au = dishUrgency(a.deadline), bu = dishUrgency(b.deadline);
    const ao = au ? URG_ORDER[au.tone] : 99;
    const bo = bu ? URG_ORDER[bu.tone] : 99;
    if (ao !== bo) return ao - bo;
    return (a.deadline || '99:99').localeCompare(b.deadline || '99:99');
  });
  const totalDishes = Object.values(data.dishes).flat().length;
  const doneCount = Object.values(data.dishes).flat().filter(d => done.has(d.id)).length;

  const toggle = (id) => setDone(prev => {
    const next = new Set(prev);
    if (next.has(id)) next.delete(id); else next.add(id);
    return next;
  });

  return (
    <div className="screen-enter" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
      <RoleHeader
        color="cook"
        title="План на смену"
        subtitle={`Готово ${doneCount} из ${totalDishes} блюд`}
        onBack={onBack}
      />

      {/* Категории */}
      <div style={{
        display: 'flex', gap: 8, padding: '16px 32px',
        background: '#fff', borderBottom: '1px solid #e5e5e5',
        overflowX: 'auto', flexShrink: 0,
      }}>
        {data.categories.map(c => {
          const catDishes = data.dishes[c.id] || [];
          const catDone = catDishes.filter(d => done.has(d.id)).length;
          const isActive = activeCat === c.id;
          return (
            <button
              key={c.id}
              onClick={() => setActiveCat(c.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '14px 22px',
                background: isActive ? ROLE_COLORS.cook.main : '#f5f2ee',
                color: isActive ? '#fff' : '#333',
                border: 'none', borderRadius: 12,
                fontSize: 18, fontWeight: 700, cursor: 'pointer',
                fontFamily: 'inherit', whiteSpace: 'nowrap',
              }}>
              {c.label}
              <span style={{
                padding: '2px 10px', borderRadius: 999,
                background: isActive ? 'rgba(255,255,255,0.25)' : '#fff',
                fontSize: 14, fontWeight: 700,
              }}>{catDone}/{catDishes.length}</span>
            </button>
          );
        })}
      </div>

      {/* Карточки блюд */}
      <div style={{ flex: 1, overflow: 'auto', padding: 24, background: '#f8f6f2' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))',
          gap: 20,
        }}>
          {dishes.map(d => {
            const isDone = done.has(d.id);
            const hl = window.KITCHEN_STORE.getHighlight(`cook:${d.id}`);
            const urg = !isDone ? dishUrgency(d.deadline) : null;
            const borderCol = hl ? '#f5c400'
              : isDone ? '#0E7C3A'
              : urg && urg.tone === 'overdue' ? '#B8420F'
              : urg && urg.tone === 'urgent' ? '#E85D1E'
              : '#e5e0d5';
            return (
              <div key={d.id} className={hl ? 'flash-cell' : ''} style={{
                background: isDone ? '#f3f0ea' : '#fff',
                borderRadius: 16,
                padding: 24,
                border: `2px solid ${borderCol}`,
                opacity: isDone ? 0.75 : 1,
                position: 'relative',
              }}>
                <ChangeBadge highlight={hl} />
                <div style={{
                  display: 'flex', justifyContent: 'space-between',
                  alignItems: 'flex-start', gap: 12, marginBottom: 12,
                }}>
                  <h3 style={{
                    margin: 0, fontSize: 22, fontWeight: 800, color: '#111',
                    textDecoration: isDone ? 'line-through' : 'none',
                    flex: 1,
                  }}>{d.name}</h3>
                  <Pill
                    bg={urg ? urg.bg : ROLE_COLORS.cook.soft}
                    color={urg ? urg.color : ROLE_COLORS.cook.dark}>
                    {urg && urg.tone === 'overdue' ? `просрочено · ${d.deadline}` : `до ${d.deadline}`}
                  </Pill>
                </div>
                {urg && (
                  <div style={{
                    display: 'inline-block',
                    padding: '2px 10px', marginBottom: 8,
                    background: urg.color, color: '#fff',
                    borderRadius: 6, fontSize: 11, fontWeight: 800,
                    textTransform: 'uppercase', letterSpacing: 1,
                  }}>{urg.label}</div>
                )}

                <div style={{ display: 'flex', gap: 28, margin: '16px 0' }}>
                  <div>
                    <div style={{ fontSize: 13, color: '#888', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1 }}>Порций</div>
                    <div style={{ fontSize: 36, fontWeight: 800, color: '#111', lineHeight: 1 }}>{d.portions}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 13, color: '#888', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1 }}>Выход</div>
                    <div style={{ fontSize: 22, fontWeight: 700, color: '#333', paddingTop: 10 }}>{d.weight}</div>
                  </div>
                </div>

                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16 }}>
                  {d.diets.map(diet => (
                    <Pill key={diet} bg="#fff6dc" color="#7a5a0f" size="sm">{diet}</Pill>
                  ))}
                  <Pill bg="#f0f0f0" color="#666" size="sm">ТТК {d.recipe}</Pill>
                </div>

                <button
                  onClick={() => toggle(d.id)}
                  style={{
                    width: '100%', padding: '14px',
                    background: isDone ? '#0E7C3A' : '#fff',
                    color: isDone ? '#fff' : ROLE_COLORS.cook.main,
                    border: `2px solid ${isDone ? '#0E7C3A' : ROLE_COLORS.cook.main}`,
                    borderRadius: 10,
                    fontSize: 18, fontWeight: 700, cursor: 'pointer',
                    fontFamily: 'inherit',
                  }}>
                  {isDone ? '✓ Приготовлено' : 'Отметить готовым'}
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CookScreen });
