// ТВ-версия кладовщика. Те же три вкладки + drill-down иерархия.

// Булки по весу: белый — 0,5 кг/булка, серый — 0,6 кг/булка.
function breadLoavesTV(name, kg) {
  const n = String(name || '').toLowerCase();
  let perLoaf = 0;
  if (/белый/.test(n)) perLoaf = 0.5;
  else if (/серый/.test(n)) perLoaf = 0.6;
  else if (/хлеб/.test(n)) perLoaf = 0.5;
  else return null;
  if (!kg || kg <= 0) return 0;
  return Math.ceil(kg / perLoaf);
}

function StorekeeperScreenTV({ onBack }) {
  useKitchenStore();
  const now = useNow();
  const auto = useTVAutoScroll('store');
  const [selectedDate, setSelectedDate] = useSelectedDate('storekeeper');
  const store = window.KITCHEN_STORE;
  const branch = window.KITCHEN_BRANCH;

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

  const slice = store.getDataForDate(selectedDate);
  const sk = slice.data && slice.data.storekeeper;
  const sections = (sk && sk.sections) || [];

  const [activeSection, setActiveSection] = React.useState(null);
  React.useEffect(() => {
    if (sections.length === 0) { setActiveSection(null); return; }
    if (!activeSection || !sections.find(s => s.type === activeSection)) {
      setActiveSection(sections[0].type);
    }
  }, [sections]);

  const section = sections.find(s => s.type === activeSection) || sections[0];
  const time = now.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });

  return (
    <div className="screen-enter" style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column',
      background: '#f8f6f2',
    }}>
      <header style={{
        display: 'flex', alignItems: 'center', gap: 20,
        padding: '14px 28px',
        background: '#fff',
        borderBottom: '6px solid #1D6FBF',
        flexShrink: 0,
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: '#1D6FBF', 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' }}>
            {section ? section.label : 'Нет данных'}
          </h1>
        </div>
        <TVBackButton onBack={onBack} />
        <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>

      <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} />
        {sections.length > 0 && (
          <div style={{ display: 'flex', gap: 8, marginLeft: 'auto' }}>
            {sections.map(s => {
              const active = s.type === activeSection;
              return (
                <button
                  key={s.type}
                  onClick={() => setActiveSection(s.type)}
                  style={{
                    padding: '8px 18px',
                    background: active ? '#1D6FBF' : '#f5f7fa',
                    color: active ? '#fff' : '#333',
                    border: 'none', borderRadius: 12,
                    fontSize: 15, fontWeight: 800,
                    cursor: 'pointer', fontFamily: 'inherit',
                  }}>
                  {s.label}
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div ref={auto.ref} style={{ flex: 1, overflow: 'auto', padding: 18 }}>
        {slice.isLoading && (
          <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
            Загружаю данные на {selectedDate}…
          </div>
        )}

        {!slice.isLoading && !section && (
          <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
            На эту дату данных нет
          </div>
        )}

        {section && section.kind === 'productList' && (
          <ProductListTV items={section.items || []} />
        )}

        {section && section.kind === 'hospitalDishKg' && (section.hospitals || []).map((h, hi) => {
          // Структура: больница → пост (отделение) → блюдо × кг.
          // Бекенд отдаёт h.departments[], плюс плоский h.dishes для запаса.
          const depts = Array.isArray(h.departments) && h.departments.length
            ? h.departments
            : [{ dept: '', dishes: h.dishes || [] }];
          const totalKg = depts.reduce((s, dep) =>
            s + (dep.dishes || []).reduce((ss, d) => ss + (d.kg || 0), 0), 0);
          return (
            <section key={hi} style={{ marginBottom: 18 }}>
              <div style={{
                padding: '12px 22px', background: '#1D6FBF', color: '#fff',
                borderRadius: '14px 14px 0 0',
                fontSize: 22, fontWeight: 800,
                display: 'flex', justifyContent: 'space-between',
              }}>
                <span>{h.name}</span>
                <span style={{ fontVariantNumeric: 'tabular-nums' }}>
                  {Math.round(totalKg * 100) / 100} кг
                </span>
              </div>
              <div style={{
                background: '#fff', borderRadius: '0 0 14px 14px',
                border: '2px solid #1D6FBF', borderTop: 'none',
              }}>
                {depts.map((dep, depi) => {
                  if (!(dep.dishes || []).length) return null;
                  return (
                    <div key={depi} style={{ borderTop: depi === 0 ? 'none' : '2px solid #e9e3d3' }}>
                      {dep.dept && dep.dept !== '—' && (
                        <div style={{
                          padding: '8px 22px',
                          background: '#fdf7ec',
                          fontSize: 14, fontWeight: 800, color: '#5a4b1a',
                          textTransform: 'uppercase', letterSpacing: 1,
                        }}>· {dep.dept}</div>
                      )}
                      {(dep.dishes || []).map((d, i) => (
                        <div key={i} style={{
                          display: 'grid',
                          gridTemplateColumns: 'minmax(0, 1fr) 140px 130px',
                          alignItems: 'center', gap: 10,
                          padding: '12px 22px 12px 38px',
                          borderTop: '1px dotted #f0ece2',
                        }}>
                          <div style={{ fontSize: 20, fontWeight: 700, color: '#111' }}>{d.name}</div>
                          <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                            <span style={{ fontSize: 28, fontWeight: 800, color: '#111' }}>{d.kg}</span>
                            <span style={{ fontSize: 14, color: '#666', marginLeft: 5 }}>кг</span>
                          </div>
                          <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#134B82' }}>
                            {breadLoavesTV(d.name, d.kg) != null ? (<>
                              <span style={{ fontSize: 24, fontWeight: 800 }}>{breadLoavesTV(d.name, d.kg)}</span>
                              <span style={{ fontSize: 13, color: '#6a86a8', marginLeft: 4 }}>бул.</span>
                            </>) : <span style={{ color: '#bbb' }}>—</span>}
                          </div>
                        </div>
                      ))}
                    </div>
                  );
                })}
              </div>
            </section>
          );
        })}

        {section && !section.kind && (() => {
          // Инвертируем буфет: больница → приём → отделение → блюда.
          const hospMap = new Map();
          const order = [];
          for (const mg of (section.meals || [])) {
            for (const h of (mg.hospitals || [])) {
              const depts = (h.departments || []).filter(dep => (dep.dishes || []).length);
              if (!depts.length) continue;
              const hname = String(h.name || '').trim() || '—';
              let e = hospMap.get(hname);
              if (!e) { e = { name: hname, meals: [] }; hospMap.set(hname, e); order.push(hname); }
              e.meals.push({ meal: mg.meal, deadline: mg.deadline, departments: depts });
            }
          }
          const hospitals = order.map(n => hospMap.get(n));
          const _pwgB = (w) => { const m = String(w || '').match(/([\d.,]+)/); return m ? (parseFloat(m[1].replace(',', '.')) || 0) : 0; };
          return hospitals.map((h, hi) => {
            // Итого по больнице — суммируем каждое блюдо по всем приёмам.
            const agg = new Map();
            const postAgg = new Map();
            const postOrder = [];
            for (const mg of h.meals) for (const dep of mg.departments) {
              const deptName = dep.dept || '—';
              if (!postAgg.has(deptName)) { postAgg.set(deptName, new Map()); postOrder.push(deptName); }
              const pMap = postAgg.get(deptName);
              for (const d of dep.dishes) {
                const wg = _pwgB(d.weight);
                const cur = agg.get(d.name) || { portions: 0, kg: 0, weight: d.weight || '', weightVaries: false };
                cur.portions += d.portions || 0;
                cur.kg += ((d.portions || 0) * wg) / 1000;
                if ((d.weight || '') !== cur.weight) cur.weightVaries = true;
                agg.set(d.name, cur);
                const pcur = pMap.get(d.name) || { portions: 0, kg: 0, weight: d.weight || '', weightVaries: false };
                pcur.portions += d.portions || 0;
                pcur.kg += ((d.portions || 0) * wg) / 1000;
                if ((d.weight || '') !== pcur.weight) pcur.weightVaries = true;
                pMap.set(d.name, pcur);
              }
            }
            const totRows = [...agg.entries()]
              .map(([name, v]) => ({ name, portions: v.portions, kg: Math.round(v.kg * 1000) / 1000, weight: v.weightVaries ? '' : v.weight }))
              .sort((a, b) => a.name.localeCompare(b.name));
            const postBlocks = postOrder.map(deptName => ({
              dept: deptName,
              rows: [...postAgg.get(deptName).entries()]
                .map(([name, v]) => ({ name, portions: v.portions, kg: Math.round(v.kg * 1000) / 1000, weight: v.weightVaries ? '' : v.weight }))
                .sort((a, b) => a.name.localeCompare(b.name)),
            }));
            const showPostBlocks = postBlocks.length > 1 ? postBlocks : [];
            return (
            <section key={hi} style={{ marginBottom: 18 }}>
              <div style={{
                padding: '12px 22px', background: '#1D6FBF', color: '#fff',
                borderRadius: '14px 14px 0 0',
                fontSize: 22, fontWeight: 800,
              }}>
                {h.name}
              </div>
              <div style={{
                background: '#fff', borderRadius: '0 0 14px 14px',
                border: '2px solid #1D6FBF', borderTop: 'none',
              }}>
                {/* Итого по больнице — суммарно по всем приёмам буфета. */}
                <div style={{
                  padding: '8px 22px', background: '#eef3f0',
                  fontSize: 14, fontWeight: 800, color: '#0E5A2A',
                  textTransform: 'uppercase', letterSpacing: 1,
                }}>Итого по больнице (все приёмы)</div>
                {totRows.map((r, i) => (
                  <div key={'tot' + i} style={{
                    display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 110px 80px 90px',
                    alignItems: 'center', gap: 10,
                    padding: '9px 22px 9px 38px',
                    borderTop: '1px dotted #f0ece2', background: '#f7faf8',
                  }}>
                    <div style={{ fontSize: 18, fontWeight: 700, color: '#111' }}>{r.name}</div>
                    <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                      <span style={{ fontSize: 24, fontWeight: 800, color: '#0E5A2A' }}>{r.portions}</span>
                      <span style={{ fontSize: 12, color: '#789', marginLeft: 4 }}>порц.</span>
                    </div>
                    <div style={{ textAlign: 'right', fontSize: 13, color: '#666' }}>{r.weight || ''}</div>
                    <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                      <span style={{ fontSize: 18, fontWeight: 700, color: '#0E5A2A' }}>{r.kg}</span>
                      <span style={{ fontSize: 12, color: '#789', marginLeft: 3 }}>кг</span>
                    </div>
                  </div>
                ))}
                {showPostBlocks.map((pb, pbi) => (
                  <React.Fragment key={'pb' + pbi}>
                    <div style={{
                      padding: '9px 22px', background: '#dff0e3',
                      fontSize: 14, fontWeight: 800, color: '#0E5A2A',
                      textTransform: 'uppercase', letterSpacing: 1,
                      borderTop: '2px solid #c4e0cb',
                    }}>Итого · {pb.dept} (все приёмы)</div>
                    {pb.rows.map((r, ri) => (
                      <div key={'pbr' + pbi + '-' + ri} style={{
                        display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 110px 80px 90px',
                        alignItems: 'center', gap: 10,
                        padding: '9px 22px 9px 38px',
                        borderTop: '1px dotted #f0ece2', background: '#f1faf3',
                      }}>
                        <div style={{ fontSize: 18, fontWeight: 700, color: '#111' }}>{r.name}</div>
                        <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                          <span style={{ fontSize: 24, fontWeight: 800, color: '#0E5A2A' }}>{r.portions}</span>
                          <span style={{ fontSize: 12, color: '#789', marginLeft: 4 }}>порц.</span>
                        </div>
                        <div style={{ textAlign: 'right', fontSize: 13, color: '#666' }}>{r.weight || ''}</div>
                        <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                          <span style={{ fontSize: 18, fontWeight: 700, color: '#0E5A2A' }}>{r.kg}</span>
                          <span style={{ fontSize: 12, color: '#789', marginLeft: 3 }}>кг</span>
                        </div>
                      </div>
                    ))}
                  </React.Fragment>
                ))}
                {h.meals.map((mg, mi) => (
                  <div key={mi} style={{ borderTop: mi === 0 ? 'none' : '3px solid #e9e3d3' }}>
                    <div style={{
                      padding: '8px 22px', background: '#eaf2fb',
                      fontSize: 15, fontWeight: 800, color: '#134B82',
                    }}>{mg.meal}{mg.deadline && ` · ${mg.deadline}`}</div>
                    {mg.departments.map((dep, depi) => (
                      <div key={depi} style={{ borderTop: depi === 0 ? 'none' : '1px solid #f0ece2' }}>
                        {dep.dept && (
                          <div style={{
                            padding: '6px 22px 6px 38px',
                            background: '#fdf7ec', fontSize: 13, fontWeight: 800,
                            color: '#7a5a0f', textTransform: 'uppercase', letterSpacing: 1,
                          }}>· {dep.dept}</div>
                        )}
                        <div style={{
                          display: 'grid',
                          gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
                          gap: 1, padding: 1,
                        }}>
                          {dep.dishes.map((d, i) => {
                            const totKg = Math.round(((d.portions || 0) * _pwgB(d.weight)) / 1000 * 1000) / 1000;
                            return (
                            <div key={d.id || i} style={{
                              padding: '12px 14px',
                              background: '#fff',
                              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                              outline: '1px solid #f0ece2',
                            }}>
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{
                                  fontSize: 15, fontWeight: 600, color: '#111',
                                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                                }} title={d.name}>{d.name}</div>
                                {d.weight && (
                                  <div style={{ fontSize: 12, color: '#888' }}>{d.weight}</div>
                                )}
                              </div>
                              <div style={{ textAlign: 'right' }}>
                                <span style={{ fontSize: 22, fontWeight: 800, color: '#111' }}>{d.portions}</span>
                                <span style={{ fontSize: 12, color: '#888', marginLeft: 4 }}>порц.</span>
                              </div>
                              <div style={{ textAlign: 'right', minWidth: 70, fontVariantNumeric: 'tabular-nums', color: '#0E5A2A' }}>
                                <span style={{ fontSize: 18, fontWeight: 800 }}>{totKg}</span>
                                <span style={{ fontSize: 11, color: '#789', marginLeft: 2 }}>кг</span>
                              </div>
                            </div>
                            );
                          })}
                        </div>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            </section>
            );
          });
        })()}
      </div>
    </div>
  );
}

function ProductListTV({ items }) {
  if (!items.length) {
    return <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
      Список пуст
    </div>;
  }
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
      gap: 12,
    }}>
      {items.map((it, i) => (
        <div key={i} style={{
          background: '#fff',
          borderRadius: 14,
          border: '2px solid #1D6FBF',
          padding: '14px 16px',
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          <div style={{ fontSize: 18, fontWeight: 700, color: '#111', lineHeight: 1.2 }}>{it.name}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{
              fontSize: 32, fontWeight: 800, color: '#111',
              fontVariantNumeric: 'tabular-nums',
            }}>{it.qty}</span>
            <span style={{ fontSize: 16, color: '#666', fontWeight: 600 }}>{it.unit}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { StorekeeperScreenTV });
