/* ============================================================
   Root app — auth, hash-free state routing, role gating
   ============================================================ */
const { useState: useSR, useEffect: useER } = React;

function BootSplash() {
  return (
    <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 14, color: 'var(--ink-3)' }}>
      <span style={{ background: 'var(--accent)', color: '#fff', fontWeight: 800, fontSize: 13, letterSpacing: '.08em', padding: '8px 13px', borderRadius: 8 }}>LG AI 365</span>
      <Icon.clock className="spin" style={{ width: 22, height: 22 }} />
    </div>
  );
}

function loadRoute() {
  try { const r = JSON.parse(localStorage.getItem('lg_route')); if (r && r.name) return r; } catch (e) {}
  return { name: 'home' };
}

function AppInner() {
  const toast = useToast();
  const [user, setUser] = useSR(undefined); // undefined = checking
  const [route, setRoute] = useSR(loadRoute());

  useER(() => {
    const t = localStorage.getItem('lg_token');
    if (t) { window.api.setToken(t); window.api.me().then(setUser).catch(() => { setUser(null); }); }
    else setUser(null);
  }, []);

  const navigate = (r) => { setRoute(r); localStorage.setItem('lg_route', JSON.stringify(r)); };
  const onLogin = ({ token, user }) => { localStorage.setItem('lg_token', token); setUser(user); navigate({ name: 'home' }); };
  const onLogout = () => { window.api.logout(); localStorage.removeItem('lg_token'); localStorage.removeItem('lg_route'); setUser(null); setRoute({ name: 'home' }); };

  // Context project for the viewer. 프로세스·WBS is GLOBAL but still needs a project
  // for context (project.id / periodStart), so always keep one: prefer the 운영가이드
  // 표기(ON=active) project, else fall back to the first. The active check only gates
  // the 콘텐츠 tab below — WBS/프로세스 must never depend on it.
  const projQ = useAsync(() => (user ? window.api.getProjects().then((l) => l.find((p) => p.status === 'active') || l[0] || null) : Promise.resolve(null)), [user]);
  const project = projQ.data;

  if (user === undefined) return <BootSplash />;
  if (!user) return <Login onLogin={onLogin} />;

  // role gate: LGE cannot reach admin screens
  let r = route;
  if (user.role === 'LGE' && (r.name === 'audit' || r.name === 'users' || r.name === 'eplog' || r.name === 'epadmin')) r = { name: 'home' };
  if (user.role === 'LGE' && r.name === 'project' && r.tab === 'history') r = { ...r, tab: 'episodes' };

  let content;
  if (r.name === 'audit') content = <AuditLog user={user} toast={toast} />;
  else if (r.name === 'eplog') content = <EpisodeLog user={user} toast={toast} navigate={navigate} />;
  else if (r.name === 'epadmin') content = <EpisodeAdmin user={user} toast={toast} navigate={navigate} />;
  else if (r.name === 'users') content = <UserManagement user={user} toast={toast} />;
  else if (r.name === 'refs') content = <RefListScreen chip={r.chip} kind={r.kind} label={r.label} navigate={navigate} />;
  else { // home/project → the single operation
    if (projQ.loading) content = <ProjectLoading />;
    else if (projQ.error) content = <div className="page-wrap"><ErrorState onRetry={projQ.reload} msg={projQ.error} /></div>;
    else if (project) {
      const m = r.month || (project.months[0] && project.months[0].month) || null;
      const common = { project, month: m, user, navigate, toast };
      // 콘텐츠 tab only shows when a project is 표기 ON(active); otherwise "운영 중인 가이드
      // 없음". 프로세스·WBS (else) and history always render against the context project.
      if (r.tab === 'episodes') content = project.status === 'active'
        ? <EpisodeBrowse {...common} />
        : <div className="page-wrap"><EmptyState icon={<Icon.layers />} title="운영 중인 가이드가 없습니다" desc="운영가이드 표기(ON)된 운영 가이드가 없습니다." /></div>;
      else if (r.tab === 'history') content = <SubmitHistory {...common} />;
      else content = <ProcessCalendar {...common} route={r} />;
    } else content = <div className="page-wrap"><EmptyState icon={<Icon.layers />} title="운영 중인 가이드가 없습니다" desc="운영가이드 표기(ON)된 운영 가이드가 없습니다." /></div>;
  }

  return (
    <AppShell user={user} route={r} navigate={navigate} onLogout={onLogout} project={projQ.loading ? null : project}>
      {content}
    </AppShell>
  );
}

function ProjectLoading() {
  return (
    <div className="page-wrap">
      <Skel w={220} h={36} r={8} />
      <div style={{ marginTop: 20 }}><Skel h={66} r={12} /></div>
      {[0, 1].map((i) => (
        <div className="theme-box" key={i} style={{ marginTop: 16 }}>
          <Skel w="35%" h={18} />
          <div className="ep-grid" style={{ marginTop: 16 }}>{[0, 1, 2].map((j) => <Skel key={j} h={130} r={12} />)}</div>
        </div>
      ))}
    </div>
  );
}

function App() { return <ToastProvider><AppInner /></ToastProvider>; }

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