function PackerScreen({ onBack }) {
  // Подписка на стор: при правке на бэкенде ререндерим экран.
  useKitchenStore();
  const now = useNow();
  const mealStatus = getMealStatus(now);
  const activeMeal = mealStatus.current ? mealStatus.current.name
                   : mealStatus.next ? mealStatus.next.name
                   : null;
  const data = window.KITCHEN_DATA.packer;
  const [activeHospitalId, setActiveHospitalId] = React.useState(data.hospitals[0].id);
  const [done, setDone] = React.useState(() => new Set());
  const [collapsed, setCollapsed] = React.useState(() => new Set());

  const hospital = data.hospitals.find(h => h.id === activeHospitalId) || data.hospitals[0];

  const mealTotals = {};
  data.meals.forEach(m => {
    mealTotals[m] = hospital.dietGroups.reduce((sum, g) =>
      sum + g.rows.reduce((s, r) => s + (r.portions[m] || 0), 0), 0);
  });
  const grandTotal = data.meals.reduce((s, m) => s + mealTotals[m], 0);

  const allCellKeys = hospital.dietGroups.flatMap((g, gi) =>
    g.rows.flatMap((r, ri) =>
      data.meals.filter(m => r.portions[m] > 0).map(m => `${hospital.id}-${gi}-${ri}-${m}`)
    )
  );
  const doneCount = allCellKeys.filter(k => done.has(k)).length;

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

  const toggleCollapse = (key) => setCollapsed(prev => {
    const next = new Set(prev);
    if (next.has(key)) next.delete(key); else next.add(key);
    return next;
  });

  const dietColor = (diet) => {
    if (diet.startsWith("ВБД")) return { bg: '#FFE4D6', fg: '#B8420F', accent: '#E85D1E' };
    if (diet.startsWith("ОВД")) return { bg: '#DCF4E5', fg: '#065724', accent: '#0E7C3A' };
    if (diet.startsWith("ЩД"))  return { bg: '#E0E4FC', fg: '#1A2E91', accent: '#2F4BD4' };
    return { bg: '#F0E6FB', fg: '#4E1781', accent: '#7A2DB8' };
  };

  const colTemplate = `minmax(320px, 1fr) repeat(${data.meals.length}, 96px) 110px`;

  return (
    <div className="screen-enter" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
      <RoleHeader
        color="packer"
        title="Фасовка порций"
        subtitle={`${hospital.name} · фасовано ${doneCount} из ${allCellKeys.length}`}
        onBack={onBack}
      />

      {/* Табы больниц */}
      <div style={{
        display: 'flex', gap: 6, padding: '12px 24px',
        background: '#fff', borderBottom: '1px solid #e5e5e5',
        overflowX: 'auto', flexShrink: 0,
      }}>
        {data.hospitals.map(h => {
          const isActive = h.id === activeHospitalId;
          const total = h.dietGroups.reduce((s, g) => s + g.rows.reduce((ss, r) =>
            ss + Object.values(r.portions).reduce((x, y) => x + y, 0), 0), 0);
          return (
            <button
              key={h.id}
              onClick={() => setActiveHospitalId(h.id)}
              style={{
                display: 'flex', flexDirection: 'column', gap: 2,
                padding: '10px 16px',
                background: isActive ? ROLE_COLORS.packer.main : '#f5f2ee',
                color: isActive ? '#fff' : '#333',
                border: 'none', borderRadius: 10,
                fontSize: 15, fontWeight: 700, cursor: 'pointer',
                fontFamily: 'inherit', whiteSpace: 'nowrap',
                minWidth: 90,
              }}>
              <span>{h.short}</span>
              <span style={{ fontSize: 12, fontWeight: 600, opacity: 0.85 }}>{total} порц.</span>
            </button>
          );
        })}
      </div>

      {/* Таблица */}
      <div style={{ flex: 1, overflow: 'auto', padding: 20, background: '#f8f6f2' }}>
        {/* Заголовок таблицы */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: colTemplate,
          background: '#111', color: '#fff',
          fontSize: 13, fontWeight: 700,
          borderRadius: '10px 10px 0 0',
          position: 'sticky', top: 0, zIndex: 2,
        }}>
          <div style={{ padding: '12px 16px', borderRight: '1px solid #333' }}>Отделение / палата</div>
          {data.meals.map(m => {
            const isActive = m === activeMeal;
            return (
              <div key={m} style={{
                padding: '12px 8px', borderRight: '1px solid #333',
                textAlign: 'center', fontSize: 12,
                background: isActive ? '#f5c400' : 'transparent',
                color: isActive ? '#111' : '#fff',
                fontWeight: isActive ? 800 : 700,
                position: 'relative',
              }}>
                {m}
                {isActive && (
                  <div style={{
                    position: 'absolute', top: 1, right: 4,
                    fontSize: 9, fontWeight: 800,
                    color: '#111', textTransform: 'uppercase',
                  }}>● сейчас</div>
                )}
              </div>
            );
          })}
          <div style={{ padding: '12px 8px', textAlign: 'center' }}>Итого</div>
        </div>

        {/* Группы по диетам */}
        {hospital.dietGroups.map((group, gi) => {
          const col = dietColor(group.diet);
          const gKey = `${hospital.id}-${gi}`;
          const isCollapsed = collapsed.has(gKey);
          const groupMealTotals = {};
          data.meals.forEach(m => {
            groupMealTotals[m] = group.rows.reduce((s, r) => s + (r.portions[m] || 0), 0);
          });
          const groupTotal = data.meals.reduce((s, m) => s + groupMealTotals[m], 0);

          return (
            <div key={gi} style={{ marginBottom: 2 }}>
              {/* Заголовок группы */}
              <div
                onClick={() => toggleCollapse(gKey)}
                style={{
                  display: 'grid',
                  gridTemplateColumns: colTemplate,
                  background: col.bg,
                  cursor: 'pointer',
                  borderTop: `3px solid ${col.accent}`,
                }}>
                <div style={{
                  padding: '14px 16px',
                  display: 'flex', alignItems: 'center', gap: 10,
                  borderRight: `1px solid ${col.accent}33`,
                }}>
                  <span style={{
                    display: 'inline-block',
                    transform: isCollapsed ? 'rotate(-90deg)' : 'none',
                    transition: 'transform 150ms',
                    fontSize: 14, color: col.fg,
                  }}>▼</span>
                  <span style={{
                    padding: '4px 12px', background: col.accent, color: '#fff',
                    borderRadius: 6, fontSize: 14, fontWeight: 800,
                  }}>{hospital.short} · {group.diet}</span>
                  <span style={{ fontSize: 14, color: col.fg, fontWeight: 600 }}>{group.fullName}</span>
                  <span style={{ fontSize: 13, color: col.fg, opacity: 0.7, marginLeft: 'auto', marginRight: 12 }}>
                    {group.rows.length} отд.
                  </span>
                </div>
                {data.meals.map(m => (
                  <div key={m} style={{
                    padding: '14px 4px', textAlign: 'center',
                    borderRight: `1px solid ${col.accent}33`,
                    color: col.fg, fontWeight: 700, fontSize: 15,
                  }}>{groupMealTotals[m] || ''}</div>
                ))}
                <div style={{
                  padding: '14px 4px', textAlign: 'center',
                  color: col.fg, fontWeight: 800, fontSize: 17,
                }}>{groupTotal}</div>
              </div>

              {/* Строки отделений */}
              {!isCollapsed && group.rows.map((row, ri) => {
                const rowTotal = Object.values(row.portions).reduce((s, n) => s + n, 0);
                return (
                  <div key={ri} style={{
                    display: 'grid',
                    gridTemplateColumns: colTemplate,
                    background: '#fff',
                    borderTop: '1px solid #f0ece2',
                  }}>
                    <div style={{
                      padding: '10px 16px 10px 44px',
                      fontSize: 15, color: '#222', fontWeight: 500,
                      borderRight: '1px solid #f0ece2',
                      display: 'flex', alignItems: 'center',
                    }}>
                      {row.dept}
                    </div>
                    {data.meals.map(m => {
                      const val = row.portions[m] || 0;
                      const key = `${hospital.id}-${gi}-${ri}-${m}`;
                      const isDone = done.has(key);
                      const hlKey = `packer:${hospital.id}:${group.diet}:${row.dept}:${m}`;
                      const hl = window.KITCHEN_STORE.getHighlight(hlKey);
                      if (val === 0 && !hl) {
                        return <div key={m} style={{ padding: '10px 4px', borderRight: '1px solid #f0ece2', textAlign: 'center', color: '#ccc' }}>—</div>;
                      }
                      const isActiveCol = m === activeMeal;
                      return (
                        <div
                          key={m}
                          onClick={() => toggle(key)}
                          className={hl ? 'flash-cell' : ''}
                          style={{
                            padding: '10px 4px', textAlign: 'center',
                            borderRight: '1px solid #f0ece2',
                            cursor: 'pointer',
                            background: isDone ? '#DCF4E5'
                                       : isActiveCol ? '#FFF8DD'
                                       : 'transparent',
                            fontWeight: isActiveCol ? 800 : 600,
                            fontSize: isActiveCol ? 18 : 16,
                            color: isDone ? '#065724' : '#111',
                            position: 'relative',
                          }}>
                          {isDone && <span style={{ position: 'absolute', top: 2, right: 4, fontSize: 10, color: '#0E7C3A' }}>✓</span>}
                          <ChangeBadge highlight={hl} />
                          {val}
                        </div>
                      );
                    })}
                    <div style={{
                      padding: '10px 4px', textAlign: 'center',
                      fontWeight: 700, fontSize: 16, color: '#111',
                      background: '#faf8f4',
                    }}>{rowTotal}</div>
                  </div>
                );
              })}
            </div>
          );
        })}

        {/* Итого по больнице */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: colTemplate,
          background: '#111', color: '#fff',
          fontSize: 15, fontWeight: 800,
          borderRadius: '0 0 10px 10px',
          marginTop: 2,
        }}>
          <div style={{ padding: '14px 16px', borderRight: '1px solid #333' }}>
            ИТОГО по больнице «{hospital.short}»
          </div>
          {data.meals.map(m => (
            <div key={m} style={{ padding: '14px 4px', borderRight: '1px solid #333', textAlign: 'center' }}>
              {mealTotals[m]}
            </div>
          ))}
          <div style={{ padding: '14px 4px', textAlign: 'center', fontSize: 18 }}>{grandTotal}</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PackerScreen });
