// Корневой компонент. Двухступенчатая привязка устройства:
//   1) BranchSelect — выбор филиала (один раз при первой настройке ТВ).
//   2) RoleSelect   — выбор роли в этом филиале.
//   3) Экран роли   — повар / кладовщик / фасовщик / кухонный сотрудник.
//
// Оба выбора живут в localStorage. Кнопка «Сменить роль» в шапке возвращает
// в RoleSelect, шестерёнка слева внизу — даёт сменить и филиал.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "baseFontSize": 16,
  "density": "normal"
}/*EDITMODE-END*/;

const LS_BRANCH = 'pishcheblok:branchId';
const LS_ROLE   = 'pishcheblok:role';

function App() {
  // Подписка на стор: любая дельта от бэкенда дёргает ререндер всего App.
  useKitchenStore();

  const [branchId, setBranchId] = React.useState(() => {
    try { return localStorage.getItem(LS_BRANCH) || null; } catch (_) { return null; }
  });
  const [role, setRole] = React.useState(() => {
    try { return localStorage.getItem(LS_ROLE) || null; } catch (_) { return null; }
  });
  const [loadError, setLoadError] = React.useState(null);

  // Когда branchId известен (с прошлого запуска или только что выбран),
  // загружаем его данные. При смене филиала перезагружаем.
  React.useEffect(() => {
    if (!branchId) return;
    setLoadError(null);
    window.KITCHEN_STORE.loadBranch(branchId).catch(err => {
      setLoadError(String(err.message || err));
    });
  }, [branchId]);

  const pickBranch = (id) => {
    try { localStorage.setItem(LS_BRANCH, id); } catch (_) {}
    setBranchId(id);
  };
  const pickRole = (r) => {
    try { localStorage.setItem(LS_ROLE, r); } catch (_) {}
    setRole(r);
  };
  const resetRole = () => {
    try { localStorage.removeItem(LS_ROLE); } catch (_) {}
    setRole(null);
  };
  const resetBranch = () => {
    if (!confirm('Сменить филиал? Текущая настройка устройства будет сброшена.')) return;
    try { localStorage.removeItem(LS_BRANCH); localStorage.removeItem(LS_ROLE); } catch (_) {}
    setRole(null);
    setBranchId(null);
  };

  // ---------- роутинг ----------
  // 1) Нет филиала → BranchSelect.
  // 2) Филиал есть, но данные ещё не подгрузились (или ошибка) → плашка.
  // 3) Данные есть, но роль не выбрана → RoleSelect.
  // 4) Иначе экран роли.

  let body;
  if (!branchId) {
    body = <BranchSelect onPick={pickBranch} />;
  } else if (loadError && !window.KITCHEN_DATA) {
    body = <LoadFailed message={loadError} onRetry={() => setBranchId(b => b)} onResetBranch={resetBranch} />;
  } else if (!window.KITCHEN_DATA) {
    body = <LoadingScreen branchId={branchId} />;
  } else if (!role) {
    body = <RoleSelect onPick={pickRole} />;
  } else if (role === 'cook')    body = <CookScreen onBack={resetRole} />;
  else if (role === 'store')     body = <StorekeeperScreen onBack={resetRole} />;
  else if (role === 'packer')    body = <PackerScreen onBack={resetRole} />;
  else if (role === 'kitchen')   body = <KitchenWorkerScreen onBack={resetRole} />;
  else { resetRole(); body = null; }

  // ---------- Tweaks (старая edit-mode-панель из прототипа) ----------
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || !e.data.type) return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  React.useEffect(() => {
    document.documentElement.style.fontSize = tweaks.baseFontSize + 'px';
    document.body.style.setProperty('--density', tweaks.density);
  }, [tweaks]);

  const updateTweak = (key, val) => {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  };

  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      {body}
      <ConnectionDot />
      <StaleBadge />
      <ChangeToasts />
      {branchId && <SettingsGear onResetBranch={resetBranch} />}
      <DevPanel />
      {tweaksOpen && (
        <div style={{
          position: 'fixed', bottom: 20, right: 20,
          width: 300, background: '#fff',
          border: '2px solid #111', borderRadius: 14,
          padding: 18, boxShadow: '0 12px 40px rgba(0,0,0,0.2)',
          zIndex: 9999, fontSize: 14,
        }}>
          <div style={{ fontSize: 16, fontWeight: 800, marginBottom: 12 }}>Tweaks</div>
          <label style={{ display: 'block', marginBottom: 12 }}>
            <div style={{ fontWeight: 600, marginBottom: 4 }}>Размер текста: {tweaks.baseFontSize}px</div>
            <input type="range" min="14" max="22" value={tweaks.baseFontSize}
              onChange={e => updateTweak('baseFontSize', +e.target.value)}
              style={{ width: '100%' }} />
          </label>
          <label style={{ display: 'block' }}>
            <div style={{ fontWeight: 600, marginBottom: 4 }}>Плотность</div>
            <select value={tweaks.density}
              onChange={e => updateTweak('density', e.target.value)}
              style={{ width: '100%', padding: 8, fontSize: 14, borderRadius: 8 }}>
              <option value="compact">Компактная</option>
              <option value="normal">Обычная</option>
              <option value="comfort">Комфортная</option>
            </select>
          </label>
        </div>
      )}
    </div>
  );
}

// Спиннер для случая «филиал выбран, данные ещё едут».
function LoadingScreen({ branchId }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'grid', placeItems: 'center',
      background: 'linear-gradient(180deg, #f8f6f2 0%, #ece8e0 100%)',
      color: '#555',
    }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: 1, color: '#111', marginBottom: 14 }}>ПИЩЕБЛОК</div>
        <div style={{ fontSize: 18 }}>Загрузка данных филиала {branchId}…</div>
      </div>
    </div>
  );
}

// Если бэкенд не отвечает и кеша по этому филиалу нет.
function LoadFailed({ message, onRetry, onResetBranch }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'grid', placeItems: 'center',
      background: '#fff8f3', color: '#7a1f0a',
      padding: 32, textAlign: 'center',
    }}>
      <div style={{ maxWidth: 540 }}>
        <div style={{ fontSize: 48, marginBottom: 12 }}>⚠</div>
        <div style={{ fontSize: 24, fontWeight: 800, marginBottom: 8 }}>Нет связи с сервером</div>
        <div style={{ fontSize: 16, color: '#a04020', marginBottom: 18 }}>{message}</div>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <button onClick={onRetry} style={{
            padding: '12px 22px', background: '#111', color: '#fff',
            border: 'none', borderRadius: 10, fontSize: 16, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>Попробовать снова</button>
          <button onClick={onResetBranch} style={{
            padding: '12px 22px', background: '#fff', color: '#111',
            border: '2px solid #111', borderRadius: 10, fontSize: 16, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>Сменить филиал</button>
        </div>
      </div>
    </div>
  );
}

// Шестерёнка в углу: даёт сбросить филиал. Скрыта на экране BranchSelect.
function SettingsGear({ onResetBranch }) {
  const [open, setOpen] = React.useState(false);
  const branch = window.KITCHEN_BRANCH;
  return (
    <>
      <button
        onClick={() => setOpen(true)}
        title="Настройки устройства"
        style={{
          position: 'fixed', right: 14, bottom: 14,
          width: 44, height: 44, borderRadius: 999,
          background: '#fff', color: '#444',
          border: '1px solid #ccc',
          fontSize: 22, cursor: 'pointer',
          fontFamily: 'inherit',
          boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
          zIndex: 8500,
        }}>⚙</button>
      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',
          zIndex: 9500, display: 'grid', placeItems: 'center',
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: '#fff', borderRadius: 16, padding: 24,
            minWidth: 320, maxWidth: 460,
            boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
          }}>
            <div style={{ fontSize: 22, fontWeight: 800, marginBottom: 16 }}>Настройки устройства</div>
            <div style={{ fontSize: 15, color: '#555', marginBottom: 6 }}>Текущий филиал</div>
            <div style={{
              padding: '12px 16px', background: '#f5f2ee', borderRadius: 10,
              fontSize: 18, fontWeight: 700, marginBottom: 18,
            }}>{branch ? branch.fullName || branch.name : '—'}</div>
            <button onClick={() => { setOpen(false); onResetBranch(); }} style={{
              width: '100%', padding: 14, background: '#B8420F', color: '#fff',
              border: 'none', borderRadius: 10, fontSize: 16, fontWeight: 700,
              cursor: 'pointer', fontFamily: 'inherit', marginBottom: 8,
            }}>Сменить филиал</button>
            <button onClick={() => setOpen(false)} style={{
              width: '100%', padding: 14, background: '#fff', color: '#444',
              border: '1px solid #ccc', borderRadius: 10, fontSize: 15, fontWeight: 600,
              cursor: 'pointer', fontFamily: 'inherit',
            }}>Закрыть</button>
          </div>
        </div>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
