// ТВ-версия помощника повара. Drill-down: больница → приём (с превью блюд) → таблица.
// Буфетные приёмы исключены — за них отвечает кладовщик.

function PackerScreenTV({ onBack }) {
  useKitchenStore();
  const now = useNow();
  // Автоскролл на этом экране отключён — экран фиксированный по запросу
  // оператора (плыл и было неудобно). Контейнеры просто скроллятся вручную.
  const auto = { ref: null, enabled: false, toggle: () => {} };
  const [selectedDate, setSelectedDate] = useSelectedDate('packer');
  const store = window.KITCHEN_STORE;

  React.useEffect(() => {
    if (selectedDate && selectedDate !== store.today()) {
      store.loadDate(selectedDate);
    }
  }, [selectedDate]);

  const slice = store.getDataForDate(selectedDate);
  const data = slice.data && slice.data.packer;
  const dishesByDiet = (slice.data && slice.data.dishesByDiet) || {};
  const branch = window.KITCHEN_BRANCH;
  const allMeals = (data && data.meals) || [];
  const hospitals = (data && data.hospitals) || [];

  const meals = allMeals.filter(m => !/^Буфет/i.test(String(m)));

  const [step, setStep] = React.useState('hospital');
  const [hospitalId, setHospitalId] = React.useState(null);
  const [meal, setMeal] = React.useState(null);
  const [sortBy, setSortBy] = React.useState('portions');
  const [sortDir, setSortDir] = React.useState('asc');
  const setSort = (col) => {
    if (col === sortBy) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('asc'); }
  };

  // Автофокус первой карточки выбора (больница / приём) при заходе на шаг —
  // чтобы фокус с пульта сразу был на ней, а не на кнопке «Назад» вверху.
  const firstCardRef = React.useRef(null);
  const cardsWrapRef = React.useRef(null);
  React.useEffect(() => {
    if (step !== 'hospital' && step !== 'meal') return;
    const t = setTimeout(() => {
      try { firstCardRef.current && firstCardRef.current.focus(); } catch (_) {}
    }, 250);
    // Возврат фокуса вниз на карточки (см. коммент в CookScreenTV).
    const onKey = (e) => {
      if (e.key !== 'ArrowDown') return;
      const wrap = cardsWrapRef.current;
      const ae = document.activeElement;
      if (wrap && ae && wrap.contains(ae)) return;
      if (firstCardRef.current) { e.preventDefault(); try { firstCardRef.current.focus(); } catch (_) {} }
    };
    window.addEventListener('keydown', onKey, true);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey, true); };
  }, [step]);

  // Шаг 3 (таблица блюд): блоки блюд — не кнопки, поэтому WebView на части ТВ
  // не листает список стрелками. Сами скроллим контейнер по ↑/↓, а автофокус
  // ставим на первую кнопку сортировки (←→ переключают сортировку, OK жмёт).
  const tableScrollRef = React.useRef(null);
  const firstSortRef = React.useRef(null);
  React.useEffect(() => {
    if (step !== 'table') return;
    const t = setTimeout(() => {
      try { firstSortRef.current && firstSortRef.current.focus(); } catch (_) {}
    }, 250);
    const onKey = (e) => {
      if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
      const el = tableScrollRef.current;
      if (!el) return;
      e.preventDefault();
      el.scrollBy({ top: e.key === 'ArrowDown' ? 160 : -160, behavior: 'smooth' });
    };
    window.addEventListener('keydown', onKey, true);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey, true); };
  }, [step]);

  const hospital = hospitals.find(h => h.id === hospitalId);
  const time = now.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });

  const dietColor = (diet) => {
    if (diet.includes('ВБД')) return { bg: '#FFE4D6', fg: '#B8420F' };
    if (diet.includes('ОВД')) return { bg: '#DCF4E5', fg: '#0E7C3A' };
    if (diet.includes('ЩД'))  return { bg: '#E0E4FC', fg: '#1A2E91' };
    return { bg: '#F0E6FB', fg: '#4E1781' };
  };

  function mealTotalForHospital(h, m) {
    return h.dietGroups.reduce((s, g) =>
      s + g.rows.reduce((ss, r) => ss + (r.portions[m] || 0), 0), 0);
  }
  function hospitalTotal(h) {
    return meals.reduce((s, m) => s + mealTotalForHospital(h, m), 0);
  }
  function mealsForHospital(h) {
    return meals.filter(m => mealTotalForHospital(h, m) > 0);
  }
  function dishListForHospitalMeal(h, m) {
    const acc = new Map();
    for (const g of h.dietGroups) {
      const dishesHere = (dishesByDiet[g.diet] && dishesByDiet[g.diet][m]) || [];
      if (!dishesHere.length) continue;
      const portions = g.rows.reduce((s, r) => s + (r.portions[m] || 0), 0);
      if (portions <= 0) continue;
      for (const d of dishesHere) {
        const prev = acc.get(d.name) || { name: d.name, weight: d.weight, total: 0 };
        prev.total += portions;
        acc.set(d.name, prev);
      }
    }
    return [...acc.values()].sort((a, b) => b.total - a.total);
  }

  function backOne() {
    if (step === 'table') return setStep('meal');
    if (step === 'meal') { setHospitalId(null); return setStep('hospital'); }
    return onBack();
  }

  const headerLine = (title, subtitle) => (
    <header style={{
      display: 'flex', alignItems: 'center', gap: 20,
      padding: '7px 14px',
      background: '#fff',
      borderBottom: '3px solid #0E7C3A',
      flexShrink: 0,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 7,
        background: '#0E7C3A', color: '#fff',
        display: 'grid', placeItems: 'center',
        fontSize: 16, fontWeight: 800,
      }}>🥡</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: 1, color: '#888', textTransform: 'uppercase' }}>
          ПОМОЩНИК ПОВАРА · {branch ? branch.name : ''}
        </div>
        <h1 style={{ margin: 0, fontSize: 16, fontWeight: 800, color: '#111' }}>{title}</h1>
        {subtitle && (<div style={{ fontSize: 11, color: '#555', marginTop: 1 }}>{subtitle}</div>)}
      </div>
      <TVBackButton onBack={backOne} label={step === 'hospital' ? 'Сменить роль' : 'Назад'} />
      <div style={{
        padding: '5px 10px', background: '#111', color: '#fff',
        borderRadius: 8, fontSize: 14, fontWeight: 800, letterSpacing: 1,
        fontVariantNumeric: 'tabular-nums',
      }}>{time}</div>
    </header>
  );

  // ========== Шаг 1: больницы ==========
  if (step === 'hospital') {
    return (
      <div className="screen-enter" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: '#f8f6f2' }}>
        {headerLine('Выберите больницу', `${hospitals.length} больниц по заявке`)}
        <div style={{
          padding: '12px 28px', background: '#fff',
          borderBottom: '1px solid #e5e5e5', flexShrink: 0,
          display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
        }}>
          <DatePicker value={selectedDate} onChange={setSelectedDate} />
          <DateBadge date={selectedDate} isLive={slice.isLive} />
        </div>
        {/* Экран выбора больницы — без автопрокрутки (карточки статичны → фокус заходит). */}
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {hospitals.length === 0 && (
            <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
              Нет данных по заявке на питание
            </div>
          )}
          <div ref={cardsWrapRef} style={{
            display: 'flex', flexWrap: 'wrap', gap: 7,
          }}>
            {hospitals.map((h, hidx) => (
              <button
                key={h.id}
                ref={hidx === 0 ? firstCardRef : null}
                onClick={() => { setHospitalId(h.id); setStep('meal'); }}
                style={{
                  flex: '1 1 180px', minWidth: 180,
                  background: '#fff', borderRadius: 8,
                  border: '2px solid #0E7C3A',
                  padding: '7px 8px',
                  textAlign: 'left',
                  cursor: 'pointer',
                  fontFamily: 'inherit',
                  display: 'flex', flexDirection: 'column', gap: 3,
                }}>
                <div style={{ fontSize: 8, fontWeight: 800, color: '#0E7C3A', letterSpacing: 1 }}>
                  БОЛЬНИЦА
                </div>
                <div style={{ fontSize: 10, fontWeight: 800, color: '#111', lineHeight: 1.25 }}>{h.name}</div>
                <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'baseline', gap: 3 }}>
                  <span style={{ fontSize: 18, fontWeight: 800, color: '#111' }}>{hospitalTotal(h)}</span>
                  <span style={{ fontSize: 9, color: '#666', fontWeight: 600 }}>порц.</span>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ========== Шаг 2: приёмы пищи (с превью блюд на каждой карточке) ==========
  if (step === 'meal' && hospital) {
    const visible = mealsForHospital(hospital);
    return (
      <div className="screen-enter" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: '#f8f6f2' }}>
        {headerLine(hospital.name, `Выберите приём пищи · всего ${hospitalTotal(hospital)} порц.`)}
        {/* Экран выбора приёма — без автопрокрутки (карточки статичны → фокус заходит). */}
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {visible.length === 0 && (
            <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
              На сегодня приёмов нет
            </div>
          )}
          <div ref={cardsWrapRef} style={{
            display: 'flex', flexWrap: 'wrap', gap: 7,
          }}>
            {visible.map((m, midx) => {
              const total = mealTotalForHospital(hospital, m);
              const dishList = dishListForHospitalMeal(hospital, m);
              return (
                <button
                  key={m}
                  ref={midx === 0 ? firstCardRef : null}
                  onClick={() => { setMeal(m); setStep('table'); }}
                  style={{
                    flex: '1 1 220px', minWidth: 220,
                    background: '#fff', borderRadius: 8,
                    border: '2px solid #0E7C3A',
                    padding: '8px 10px',
                    textAlign: 'left',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    display: 'flex', flexDirection: 'column', gap: 3,
                  }}>
                  <div style={{
                    display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                  }}>
                    <div style={{ fontSize: 14, fontWeight: 800, color: '#111' }}>{m}</div>
                    <div>
                      <span style={{ fontSize: 18, fontWeight: 800, color: '#111' }}>{total}</span>
                      <span style={{ fontSize: 9, color: '#666', fontWeight: 600, marginLeft: 3 }}>порц.</span>
                    </div>
                  </div>
                  {dishList.length > 0 && (
                    <div style={{ marginTop: 2, fontSize: 9, color: '#222', lineHeight: 1.4 }}>
                      {dishList.map((d, i) => (
                        <div key={i} style={{
                          display: 'flex', justifyContent: 'space-between', gap: 5,
                          padding: '3px 0', borderBottom: i === dishList.length - 1 ? 'none' : '1px dotted #eee5d5',
                        }}>
                          <span style={{ wordBreak: 'break-word' }}>{d.name}</span>
                          <span style={{ fontWeight: 800, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                            {d.total} шт.
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ========== Шаг 3: таблица — группировка по блюдам ==========
  if (step === 'table' && hospital && meal) {
    const dishGroups = new Map();
    const fallbackRows = [];
    for (const g of hospital.dietGroups) {
      for (const r of g.rows) {
        const portions = r.portions[meal] || 0;
        if (portions <= 0) continue;
        const dishes = (dishesByDiet[g.diet] && dishesByDiet[g.diet][meal]) || [];
        if (dishes.length) {
          for (const d of dishes) {
            const groupKey = (d.name || '') + '|' + (d.weight || '');
            let dg = dishGroups.get(groupKey);
            if (!dg) {
              dg = { name: d.name, weight: d.weight, total: 0, rows: [] };
              dishGroups.set(groupKey, dg);
            }
            dg.total += portions;
            dg.rows.push({ diet: g.diet, dept: r.dept, portions });
          }
        } else {
          fallbackRows.push({ diet: g.diet, dept: r.dept, portions });
        }
      }
    }
    const dishList = [...dishGroups.values()].sort((a, b) => b.total - a.total);
    const _pwg = (w) => { const m = String(w || '').match(/([\d.,]+)/); return m ? (parseFloat(m[1].replace(',', '.')) || 0) : 0; };
    const sign = sortDir === 'desc' ? -1 : 1;
    const sortRows = (rows, dishWeight) => {
      const wg = _pwg(dishWeight);
      rows.sort((a, b) => {
        let av, bv;
        if (sortBy === 'diet') { av = a.diet; bv = b.diet; }
        else if (sortBy === 'dept') { av = a.dept; bv = b.dept; }
        else if (sortBy === 'kg') { av = a.portions * wg; bv = b.portions * wg; }
        else { av = a.portions; bv = b.portions; }
        if (typeof av === 'string') return sign * String(av).localeCompare(String(bv));
        return sign * (av - bv);
      });
    };
    for (const d of dishList) sortRows(d.rows, d.weight);
    sortRows(fallbackRows, '');
    const total = hospital.dietGroups.reduce((s, g) =>
      s + g.rows.reduce((ss, r) => ss + (r.portions[meal] || 0), 0), 0);

    const parseWeightGrams = (w) => {
      if (!w) return 0;
      const m = String(w).match(/([\d.,]+)/);
      return m ? (parseFloat(m[1].replace(',', '.')) || 0) : 0;
    };
    const deptKg = new Map();
    for (const d of dishList) {
      const wg = parseWeightGrams(d.weight);
      if (wg <= 0) continue;
      for (const r of d.rows) {
        deptKg.set(r.dept, (deptKg.get(r.dept) || 0) + (r.portions * wg) / 1000);
      }
    }
    const deptSummary = [...deptKg.entries()]
      .map(([dept, kg]) => ({ dept, kg: Math.round(kg * 10) / 10 }))
      .sort((a, b) => b.kg - a.kg);

    return (
      <div className="screen-enter" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: '#f8f6f2' }}>
        {headerLine(`${hospital.name} · ${meal}`, `Итого ${total} порц. · ${dishList.length} блюд`)}
        <div ref={tableScrollRef} style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {dishList.length === 0 && fallbackRows.length === 0 && (
            <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
              На этот приём пищи порций нет
            </div>
          )}

          {deptSummary.length > 0 && (
            <div style={{
              background: '#fff', borderRadius: 8,
              border: '1px solid #0E7C3A',
              marginBottom: 8, overflow: 'hidden',
            }}>
              <div style={{
                padding: '6px 11px', background: '#0E7C3A', color: '#fff',
                fontSize: 9, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase',
              }}>
                Общий вес блюд по отделениям
              </div>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))',
                gap: 1, padding: 1, background: '#f0ece2',
              }}>
                {deptSummary.map((d, i) => (
                  <div key={i} style={{
                    background: '#fff', padding: '6px 8px',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 5,
                  }}>
                    <span style={{ fontSize: 10, color: '#222', fontWeight: 600 }}>{d.dept}</span>
                    <span style={{ fontVariantNumeric: 'tabular-nums' }}>
                      <span style={{ fontSize: 14, fontWeight: 800, color: '#111' }}>{d.kg}</span>
                      <span style={{ fontSize: 9, color: '#666', marginLeft: 2 }}>кг</span>
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {dishList.length > 0 && (() => {
            const arrow = (col) => sortBy === col ? (sortDir === 'asc' ? ' ▲' : ' ▼') : '';
            const colStyle = (col) => ({
              padding: '5px 7px',
              background: sortBy === col ? '#0E7C3A' : '#f4f1eb',
              color: sortBy === col ? '#fff' : '#444',
              border: 'none', borderRadius: 5,
              fontSize: 9, fontWeight: 800,
              cursor: 'pointer', fontFamily: 'inherit',
            });
            return (
              <div style={{
                position: 'sticky', top: 0, zIndex: 5,
                background: '#f8f6f2', padding: '3px 0 6px',
                display: 'flex', alignItems: 'center', gap: 5,
                flexWrap: 'wrap',
              }}>
                <span style={{ fontSize: 8, fontWeight: 700, color: '#888', textTransform: 'uppercase', letterSpacing: 1, marginRight: 2 }}>Сортировка</span>
                <button ref={firstSortRef} onClick={() => setSort('diet')} style={colStyle('diet')}>Диета{arrow('diet')}</button>
                <button onClick={() => setSort('dept')} style={colStyle('dept')}>Отделение{arrow('dept')}</button>
                <button onClick={() => setSort('portions')} style={colStyle('portions')}>Порций{arrow('portions')}</button>
                <button onClick={() => setSort('kg')} style={colStyle('kg')}>Вес кг{arrow('kg')}</button>
              </div>
            );
          })()}

          {dishList.map((d, di) => (
            <div key={di} style={{
              background: '#fff', borderRadius: 8,
              border: '1px solid #0E7C3A',
              marginBottom: 7, overflow: 'hidden',
            }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'minmax(0, 1fr) 70px 60px',
                alignItems: 'center', gap: 6,
                padding: '7px 10px',
                background: '#0E7C3A', color: '#fff',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                  <span style={{ fontSize: 12, fontWeight: 800, lineHeight: 1.2 }}>{d.name}</span>
                  {d.weight && (
                    <span style={{
                      background: '#fff', color: '#0E7C3A',
                      padding: '1px 6px', borderRadius: 999,
                      fontSize: 9, fontWeight: 800,
                      whiteSpace: 'nowrap',
                    }}>{d.weight}</span>
                  )}
                </div>
                <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                  <span style={{ fontSize: 18, fontWeight: 800 }}>{d.total}</span>
                  <span style={{ fontSize: 9, opacity: 0.85, marginLeft: 3 }}>порц.</span>
                </div>
                <div style={{ textAlign: 'right', fontSize: 10, opacity: 0.9, fontVariantNumeric: 'tabular-nums' }}>
                  {(() => {
                    const wg = parseWeightGrams(d.weight);
                    return wg > 0 ? `${Math.round(d.total * wg / 1000 * 1000) / 1000} кг` : '';
                  })()}
                </div>
              </div>
              {d.rows.map((r, ri) => {
                const col = dietColor(r.diet);
                const hl = store.getHighlight(`packer:${hospital.id}:${r.diet}:${r.dept}:${meal}`);
                const wg = parseWeightGrams(d.weight);
                const kg = (r.portions * wg) / 1000;
                return (
                  <div key={ri} style={{
                    display: 'grid',
                    gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1.2fr) 80px 70px',
                    alignItems: 'center', gap: 5,
                    padding: '6px 10px',
                    borderTop: '1px solid #f0ece2',
                    background: hl ? '#ffe5e5' : '#fff',
                    boxShadow: hl ? 'inset 3px 0 0 #d32f2f' : 'none',
                  }}>
                    <div>
                      <span style={{
                        display: 'inline-block', padding: '2px 6px',
                        background: col.bg, color: col.fg,
                        borderRadius: 4, fontSize: 8, fontWeight: 800,
                      }}>{r.diet}</span>
                    </div>
                    <div style={{ fontSize: 10, color: '#222', fontWeight: 600 }}>{r.dept}</div>
                    <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 5 }}>
                      {hl && (
                        <span style={{
                          background: '#d32f2f', color: '#fff',
                          padding: '1px 5px', borderRadius: 999,
                          fontSize: 9, fontWeight: 800,
                        }}>{hl.old}→{hl.new}</span>
                      )}
                      <span style={{ fontSize: 18, fontWeight: 800, color: hl ? '#d32f2f' : '#111' }}>{r.portions}</span>
                      <span style={{ fontSize: 8, color: '#888' }}>порц.</span>
                    </div>
                    <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#0E7C3A' }}>
                      <span style={{ fontSize: 14, fontWeight: 800 }}>{Math.round(kg * 1000) / 1000}</span>
                      <span style={{ fontSize: 9, color: '#7a9c84', marginLeft: 2 }}>кг</span>
                    </div>
                  </div>
                );
              })}
            </div>
          ))}

          {fallbackRows.length > 0 && dishList.length === 0 && (
            <div style={{
              background: '#fff', borderRadius: 14,
              overflow: 'hidden',
              border: '2px solid #0E7C3A',
            }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 2fr) 140px',
                background: '#111', color: '#fff',
                padding: '14px 20px',
                fontSize: 14, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase',
              }}>
                <div>Диета / рацион</div>
                <div>Отделение / пост</div>
                <div style={{ textAlign: 'right' }}>Порций</div>
              </div>
              {fallbackRows.map((r, i) => {
                const col = dietColor(r.diet);
                return (
                  <div key={i} style={{
                    display: 'grid',
                    gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 2fr) 140px',
                    alignItems: 'center', padding: '16px 20px',
                    borderTop: i === 0 ? 'none' : '1px solid #f0ece2',
                  }}>
                    <div>
                      <div style={{
                        display: 'inline-block', padding: '5px 12px',
                        background: col.bg, color: col.fg,
                        borderRadius: 8, fontSize: 14, fontWeight: 800,
                      }}>{r.diet}</div>
                    </div>
                    <div style={{ fontSize: 22, color: '#222', fontWeight: 600 }}>{r.dept}</div>
                    <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                      <span style={{ fontSize: 40, fontWeight: 800, color: '#111' }}>{r.portions}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }

  return null;
}

Object.assign(window, { PackerScreenTV });
