// Первичный экран: выбор филиала.
// Показывается один раз при первой настройке ТВ. Сохраняет выбор в localStorage,
// дальше при каждом запуске устройство сразу подгружает данные своего филиала.

function BranchSelect({ onPick }) {
  const [branches, setBranches] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const API = (window.PISHCHEBLOK_API || '') + '/api/v1';
    fetch(API + '/branches')
      .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
      .then(p => setBranches(p.branches))
      .catch(e => setError(String(e.message || e)));
  }, []);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column',
      background: 'linear-gradient(180deg, #f8f6f2 0%, #ece8e0 100%)',
    }}>
      <div style={{ textAlign: 'center', padding: '64px 32px 24px' }}>
        <div style={{
          display: 'inline-block', padding: '6px 16px',
          background: '#111', color: '#fff', borderRadius: 999,
          fontSize: 16, fontWeight: 700, letterSpacing: 1, marginBottom: 20,
        }}>ПИЩЕБЛОК · НАСТРОЙКА</div>
        <h1 style={{ margin: 0, fontSize: 56, fontWeight: 800, color: '#111', letterSpacing: -1 }}>
          Выберите филиал
        </h1>
        <p style={{ fontSize: 20, color: '#555', marginTop: 14, maxWidth: 720, margin: '14px auto 0' }}>
          К какой производственной площадке относится это рабочее место.
          Выбор сохраняется на устройстве, в дальнейшем экран сразу открывается со своими данными.
        </p>
      </div>

      <div style={{ flex: 1, padding: '16px 48px 48px', overflow: 'auto' }}>
        {error && (
          <div style={{
            maxWidth: 720, margin: '0 auto', padding: 20,
            background: '#fff8f3', border: '2px solid #B8420F',
            borderRadius: 16, color: '#7a1f0a', textAlign: 'center',
          }}>
            <div style={{ fontWeight: 800, marginBottom: 6 }}>Не удалось получить список филиалов</div>
            <div style={{ fontSize: 14 }}>{error}</div>
          </div>
        )}
        {!branches && !error && (
          <div style={{ textAlign: 'center', color: '#888', fontSize: 16, paddingTop: 32 }}>
            Загрузка списка филиалов…
          </div>
        )}
        {branches && (
          <div style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${Math.min(branches.length, 3)}, 1fr)`,
            gap: 24, maxWidth: 1280, margin: '0 auto',
          }}>
            {branches.map(b => (
              <button
                key={b.id}
                onClick={() => onPick(b.id)}
                style={{
                  display: 'flex', flexDirection: 'column',
                  padding: 36,
                  background: '#fff',
                  border: '3px solid #111',
                  borderRadius: 24,
                  cursor: 'pointer', textAlign: 'left',
                  fontFamily: 'inherit',
                  transition: 'transform 120ms, box-shadow 120ms',
                  boxShadow: '0 8px 24px rgba(0,0,0,0.06)',
                }}
                onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 16px 40px rgba(0,0,0,0.12)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.06)'; }}
              >
                <div style={{
                  width: 80, height: 80, borderRadius: 20,
                  background: '#111', color: '#fff',
                  display: 'grid', placeItems: 'center',
                  fontSize: 40, fontWeight: 800, marginBottom: 22,
                }}>{b.name[0]}</div>
                <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: 1, color: '#888', textTransform: 'uppercase', marginBottom: 4 }}>
                  Площадка
                </div>
                <h2 style={{ margin: 0, fontSize: 32, fontWeight: 800, color: '#111' }}>{b.name}</h2>
                {b.fullName && (
                  <p style={{ fontSize: 15, color: '#555', marginTop: 8, lineHeight: 1.4 }}>{b.fullName}</p>
                )}
                {b.address && (
                  <p style={{ fontSize: 14, color: '#888', marginTop: 6 }}>{b.address}</p>
                )}
                <div style={{
                  marginTop: 18, padding: '12px 18px',
                  background: '#111', color: '#fff',
                  borderRadius: 10, fontSize: 16, fontWeight: 700,
                  textAlign: 'center',
                }}>Выбрать →</div>
              </button>
            ))}
          </div>
        )}
      </div>

      <div style={{ textAlign: 'center', color: '#888', fontSize: 14, paddingBottom: 24 }}>
        Система управления пищеблоком · v2.4
      </div>
    </div>
  );
}

Object.assign(window, { BranchSelect });
