// ТВ-овощник: овощи по приёмам пищи, под каждым овощем — список блюд.

function KitchenWorkerScreenTV({ onBack }) {
  useKitchenStore();
  const now = useNow();
  const auto = useTVAutoScroll('kitchen');
  const [selectedDate, setSelectedDate] = useSelectedDate('kitchen');
  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 kw = (slice.data && slice.data.kitchenWorker) || {};
  const meals = kw.meals || [];
  const fallback = kw.items || [];
  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 #7A2DB8',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: '#7A2DB8', 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' }}>
            Заготовки на смену
          </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} />
      </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 && meals.length === 0 && fallback.length === 0 && (
          <div style={{ textAlign: 'center', color: '#888', padding: 60, fontSize: 22 }}>
            На эту дату овощей не нашлось
          </div>
        )}

        {meals.map((mg, mi) => (
          <section key={mi} style={{ marginBottom: 20 }}>
            <div style={{
              padding: '12px 22px',
              background: mg.total ? '#111' : '#7A2DB8',
              color: '#fff',
              borderRadius: '14px 14px 0 0',
              fontSize: 22, fontWeight: 800,
              display: 'flex', justifyContent: 'space-between',
            }}>
              <span>{mg.meal}</span>
              <span style={{ fontSize: 14, opacity: 0.9, fontWeight: 600 }}>
                {mg.items.length} поз.
              </span>
            </div>
            <div style={{
              background: '#fff', borderRadius: '0 0 14px 14px',
              border: mg.total ? '2px solid #111' : '2px solid #7A2DB8',
              borderTop: 'none',
            }}>
              {mg.items.map((it, i) => (
                <div key={i} style={{
                  padding: '14px 22px',
                  borderTop: i === 0 ? 'none' : '1px solid #f0ece2',
                }}>
                  <div style={{
                    display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
                  }}>
                    <div style={{ fontSize: 22, fontWeight: 800, color: '#111' }}>{it.name}</div>
                    <div style={{ fontVariantNumeric: 'tabular-nums' }}>
                      <span style={{ fontSize: 36, fontWeight: 800, color: '#111' }}>{it.qty}</span>
                      <span style={{ fontSize: 18, color: '#666', fontWeight: 600, marginLeft: 6 }}>{it.unit}</span>
                    </div>
                  </div>
                  {!mg.total && it.dishes && it.dishes.length > 0 && (
                    <div style={{ marginTop: 8, fontSize: 15, color: '#444', lineHeight: 1.5 }}>
                      <div style={{ fontWeight: 700, color: '#7A2DB8', marginBottom: 2 }}>В блюдах:</div>
                      {it.dishes.map((dn, di) => (
                        <div key={di} style={{
                          display: 'flex', justifyContent: 'space-between', gap: 12,
                          padding: '2px 0',
                        }}>
                          <span>· {dn.name}</span>
                          <span style={{ fontWeight: 800, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                            {dn.kg} кг
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </section>
        ))}

        {meals.length === 0 && fallback.length > 0 && (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',
            gap: 12,
          }}>
            {fallback.map((it, i) => (
              <div key={i} style={{
                background: '#fff', borderRadius: 14,
                border: '2px solid #7A2DB8',
                padding: '14px 16px',
              }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: '#111' }}>{it.name}</div>
                <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 6 }}>
                  <span style={{ fontSize: 32, fontWeight: 800, color: '#111' }}>{it.qty}</span>
                  <span style={{ fontSize: 16, color: '#666', fontWeight: 600 }}>{it.unit}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { KitchenWorkerScreenTV });
