// ТВ-версия экрана повара. Drill-down как у помощника повара:
//   Шаг 1: карточки приёмов (Завтрак/Обед/Полдник/Ужин) с превью названий блюд.
//   Шаг 2: выбран приём — полный список блюд с рецептурой (продукт · брутто · нетто).

function CookScreenTV({ onBack }) {
  useKitchenStore();
  const now = useNow();
  const auto = useTVAutoScroll('cook');
  const [selectedDate, setSelectedDate] = useSelectedDate('cook');
  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.cook) || { categories: [], dishes: {} };
  const recipes = (slice.data && slice.data.recipes) || {};
  const branch = window.KITCHEN_BRANCH;

  const allDishes = Object.values(data.dishes || {})
    .flat()
    .filter(d => !/^Буфет/i.test(String(d.meal || '')));
  const MEAL_ORDER = ['Завтрак', 'Обед', 'Полдник', 'Ужин'];

  const byMeal = new Map();
  for (const d of allDishes) {
    const m = d.meal || 'Без приёма пищи';
    if (!byMeal.has(m)) byMeal.set(m, []);
    byMeal.get(m).push(d);
  }
  const mealGroups = [...byMeal.entries()]
    .sort((a, b) => {
      const ai = MEAL_ORDER.indexOf(a[0]);
      const bi = MEAL_ORDER.indexOf(b[0]);
      if (ai === -1 && bi === -1) return a[0].localeCompare(b[0]);
      if (ai === -1) return 1;
      if (bi === -1) return -1;
      return ai - bi;
    })
    .map(([meal, dishes]) => ({ meal, dishes }));

  function parseWeightGrams(w) {
    if (!w) return 0;
    const m = String(w).match(/([\d.,]+)/);
    if (!m) return 0;
    return parseFloat(m[1].replace(',', '.')) || 0;
  }
  function totalKg(dish) {
    // 1С отдаёт уже посчитанный точный вес блюда (Σ Выход × КоличВсего
    // с учётом флПроба — формула отчёта «Питание_ПроизводственноеЗадание»).
    if (dish.totalWeightG && dish.totalWeightG > 0) {
      return dish.totalWeightG / 1000;
    }
    // Фоллбэк: portions × weight (для совместимости со старым 1С).
    const g = parseWeightGrams(dish.weight);
    if (/Масса упаковки/i.test(dish.name || '')) return g / 1000;
    return (dish.portions * g) / 1000;
  }
  // Вес блюда до десятитысячных без округления (по требованию повара).
  function fmtKg4(kg) {
    const n = Math.round((Number(kg) || 0) * 10000) / 10000;
    const s = n.toFixed(4).replace(/\.?0+$/, '').replace('.', ',');
    return s || '0';
  }
  // Рецептура: per-portion × portions → tysячные.
  function fmtRecipeQty(value, unit) {
    const v = Number(value) || 0;
    if (v <= 0) return '';
    const n = Math.round(v * 1000) / 1000;
    const s = n.toFixed(3).replace(/\.?0+$/, '').replace('.', ',');
    const u = /^шт/i.test(String(unit || '')) ? 'шт' : 'кг';
    return `${s} ${u}`;
  }

  const [step, setStep] = React.useState('meals');
  const [activeMeal, setActiveMeal] = React.useState(null);

  // Автофокус первой карточки приёма при заходе на экран выбора — чтобы
  // на ТВ с пультом (D-pad) сразу был фокус на «Завтрак», а не на кнопке
  // «Сменить роль» вверху. Иначе на медленных WebView вертикальный переход
  // вниз на карточку не срабатывает и выбрать приём невозможно.
  const firstMealRef = React.useRef(null);
  const cardsWrapRef = React.useRef(null);
  React.useEffect(() => {
    if (step !== 'meals') return;
    const t = setTimeout(() => {
      try { firstMealRef.current && firstMealRef.current.focus(); } catch (_) {}
    }, 250);
    // Возврат фокуса ВНИЗ на карточки: WebView на части ТВ не находит
    // карточки при стрелке вниз с верхней панели (дата/роль). Перехватываем
    // ТОЛЬКО ArrowDown и ТОЛЬКО когда фокус выше карточек — ставим на первую.
    const onKey = (e) => {
      if (e.key !== 'ArrowDown') return;
      const wrap = cardsWrapRef.current;
      const ae = document.activeElement;
      if (wrap && ae && wrap.contains(ae)) return; // уже на карточках — не мешаем
      if (firstMealRef.current) { e.preventDefault(); try { firstMealRef.current.focus(); } catch (_) {} }
    };
    window.addEventListener('keydown', onKey, true);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey, true); };
  }, [step]);

  function backOne() {
    if (step === 'dishes') { setActiveMeal(null); return setStep('meals'); }
    return onBack();
  }

  const time = now.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });

  const headerLine = (title, subtitle) => (
    <header style={{
      display: 'flex', alignItems: 'center', gap: 20,
      padding: '14px 28px',
      background: '#fff',
      borderBottom: '6px solid #E85D1E',
      flexShrink: 0,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 14,
        background: '#E85D1E', color: '#fff',
        display: 'grid', placeItems: 'center',
        fontSize: 30, fontWeight: 800,
      }}>🍳</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1, color: '#888', textTransform: 'uppercase' }}>
          ПОВАР · {branch ? branch.name : ''}
        </div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800, color: '#111' }}>{title}</h1>
        {subtitle && (<div style={{ fontSize: 14, color: '#555', marginTop: 2 }}>{subtitle}</div>)}
      </div>
      <TVBackButton onBack={backOne} label={step === 'meals' ? 'Сменить роль' : 'К приёмам'} />
      <AutoScrollToggle enabled={auto.enabled} onToggle={auto.toggle} />
      <div style={{
        padding: '8px 16px', background: '#111', color: '#fff',
        borderRadius: 12, fontSize: 24, fontWeight: 800, letterSpacing: 1,
        fontVariantNumeric: 'tabular-nums',
      }}>{time}</div>
    </header>
  );

  // ========== Шаг 1: карточки приёмов с превью блюд ==========
  if (step === 'meals') {
    return (
      <div className="screen-enter" style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column',
        background: '#f8f6f2',
      }}>
        {headerLine(`План на смену · ${allDishes.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>

        {/* Экран ВЫБОРА приёма — без автопрокрутки: карточки статичны, чтобы
            фокус с пульта стабильно заходил на них (на медленных WebView
            движущийся контейнер ломает spatial-навигацию). */}
        <div style={{ flex: 1, padding: 16, background: '#f8f6f2', minHeight: 0, overflow: 'auto' }}>
          {mealGroups.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
              На эту дату блюд не нашлось
            </div>
          ) : (
            <div ref={cardsWrapRef} style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: 14,
              alignItems: 'flex-start',
            }}>
              {mealGroups.map(({ meal, dishes }, mi) => {
                const sorted = dishes.slice().sort((a, b) => a.name.localeCompare(b.name));
                const totalKgAll = sorted.reduce((s, d) => s + totalKg(d), 0);
                const colCount = Math.max(1, Math.min(mealGroups.length, 4));
                return (
                  <button
                    key={meal}
                    ref={mi === 0 ? firstMealRef : null}
                    onClick={() => { setActiveMeal(meal); setStep('dishes'); }}
                    style={{
                      flex: `1 1 calc(${100 / colCount}% - 14px)`,
                      minWidth: 220,
                      background: '#fff', borderRadius: 16,
                      border: '3px solid #E85D1E',
                      padding: 0, overflow: 'hidden',
                      textAlign: 'left',
                      cursor: 'pointer',
                      fontFamily: 'inherit',
                      display: 'flex', flexDirection: 'column',
                    }}>
                    <div style={{
                      padding: '16px 18px',
                      background: '#E85D1E', color: '#fff',
                      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10,
                    }}>
                      <div style={{ fontSize: 30, fontWeight: 800, lineHeight: 1.1 }}>{meal}</div>
                      <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                        <span style={{ fontSize: 26, fontWeight: 800 }}>{fmtKg4(totalKgAll)}</span>
                        <span style={{ fontSize: 14, opacity: 0.9, marginLeft: 4 }}>кг</span>
                      </div>
                    </div>
                    <div style={{ padding: '6px 18px 4px', fontSize: 13, color: '#888', fontWeight: 700 }}>
                      {sorted.length} блюд
                    </div>
                    <div style={{ padding: '4px 18px 16px', fontSize: 15, color: '#222', lineHeight: 1.5 }}>
                      {sorted.map((d, i) => (
                        <div key={d.id} style={{
                          display: 'flex', justifyContent: 'space-between', gap: 8,
                          padding: '6px 0',
                          borderBottom: i === sorted.length - 1 ? 'none' : '1px dotted #eee5d5',
                        }}>
                          <span style={{ wordBreak: 'break-word' }}>{d.name}</span>
                          <span style={{ fontWeight: 800, color: '#B8420F', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                            {fmtKg4(totalKg(d))} кг
                          </span>
                        </div>
                      ))}
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }

  // ========== Шаг 2: блюда выбранного приёма + рецептура ==========
  if (step === 'dishes' && activeMeal) {
    const mg = mealGroups.find(g => g.meal === activeMeal);
    const dishes = (mg ? mg.dishes : []).slice().sort((a, b) => a.name.localeCompare(b.name));
    const totalKgAll = dishes.reduce((s, d) => s + totalKg(d), 0);

    return (
      <div className="screen-enter" style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column',
        background: '#f8f6f2',
      }}>
        {headerLine(activeMeal, `Итого ${fmtKg4(totalKgAll)} кг · ${dishes.length} блюд`)}

        <div ref={auto.ref} style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {dishes.length === 0 && (
            <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
              Блюд нет
            </div>
          )}
          {dishes.map(d => {
            const kg = totalKg(d);
            const recipe = recipes[d.id] || [];
            const hl = store.getHighlight('cook:' + d.id);
            return (
              <section key={d.id} style={{
                background: '#fff', borderRadius: 14,
                border: hl ? '3px solid #d32f2f' : '2px solid #E85D1E',
                marginBottom: 14, overflow: 'hidden',
                boxShadow: hl ? '0 0 0 4px rgba(211,47,47,0.25)' : 'none',
                animation: hl ? 'flashBg 2s ease-in-out infinite' : 'none',
              }}>
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'minmax(0, 1fr) auto 160px',
                  alignItems: 'center', gap: 14,
                  padding: '14px 20px',
                  background: hl ? '#d32f2f' : '#E85D1E', color: '#fff',
                }}>
                  <div style={{ fontSize: 22, fontWeight: 800 }}>{d.name}</div>
                  {hl ? (
                    <div style={{
                      background: '#fff', color: '#d32f2f',
                      padding: '4px 12px', borderRadius: 999,
                      fontSize: 16, fontWeight: 800,
                      whiteSpace: 'nowrap',
                      fontVariantNumeric: 'tabular-nums',
                    }}>{hl.old} → {hl.new} порц.</div>
                  ) : <div />}
                  <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                    <span style={{ fontSize: 32, fontWeight: 800 }}>{fmtKg4(kg)}</span>
                    <span style={{ fontSize: 15, opacity: 0.9, marginLeft: 4 }}>кг</span>
                  </div>
                </div>
                {recipe.length === 0 ? (
                  <div style={{ padding: '12px 20px', fontSize: 13, color: '#888' }}>
                    Рецептура не задана
                  </div>
                ) : (
                  <>
                    <div style={{
                      display: 'grid',
                      gridTemplateColumns: 'minmax(0, 1fr) 140px',
                      padding: '8px 20px',
                      background: '#fdf7f0',
                      fontSize: 11, fontWeight: 800, letterSpacing: 1,
                      color: '#7a5a0f', textTransform: 'uppercase',
                    }}>
                      <div>Продукт</div>
                      <div style={{ textAlign: 'right' }}>Нетто</div>
                    </div>
                    {recipe.map((p, pi) => (
                      <div key={pi} style={{
                        display: 'grid',
                        gridTemplateColumns: 'minmax(0, 1fr) 140px',
                        alignItems: 'center',
                        padding: '8px 20px',
                        borderTop: '1px solid #f0ece2',
                        fontSize: 15,
                      }}>
                        <div style={{ color: '#222' }}>{p.name}</div>
                        <div style={{ textAlign: 'right', fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>
                          {fmtRecipeQty(p.netto * d.portions, p.unit) || '—'}
                        </div>
                      </div>
                    ))}
                  </>
                )}
              </section>
            );
          })}
        </div>
      </div>
    );
  }

  return null;
}

Object.assign(window, { CookScreenTV });
