// ─────────────────────────────────────────────
// DEV_App.jsx — Dev UI root
// Views: apps | app-detail
// ─────────────────────────────────────────────

function DEVApp() {
  const [authReady,    setAuthReady]    = React.useState(false);
  const [jwt,          setJwt]          = React.useState(null);
  const [currentUser,  setCurrentUser]  = React.useState(null);

  // View routing
  const [view,         setView]         = React.useState('apps');   // apps | app-detail
  const [currentApp,   setCurrentApp]   = React.useState(null);     // full app row

  // ── Auth check on mount ──────────────────────
  React.useEffect(() => {
    const stored = localStorage.getItem(window.jwtKey());
    if (!stored) { setAuthReady(true); return; }
    fetch(`${API_BASE}/v6/auth/session`, {
      headers: { Authorization: `Bearer ${stored}` }
    })
      .then(r => r.json())
      .then(data => {
        if (data.status === 'ok') {
          setJwt(stored);
          setCurrentUser({ ...data.user, userId: data.user.uid || data.user.userId });
        } else {
          localStorage.removeItem(window.jwtKey());
        }
      })
      .catch(() => localStorage.removeItem(window.jwtKey()))
      .finally(() => setAuthReady(true));
  }, []);

  function handleLogin(token, user) {
    localStorage.setItem(window.jwtKey(), token);
    setJwt(token);
    setCurrentUser({ ...user, userId: user.uid || user.userId });
  }

  function handleLogout() {
    localStorage.removeItem(window.jwtKey());
    setJwt(null);
    setCurrentUser(null);
    setView('apps');
    setCurrentApp(null);
  }

  function openApp(appRow) {
    setCurrentApp(appRow);
    setView('app-detail');
  }

  function goApps() {
    setCurrentApp(null);
    setView('apps');
  }

  // ── Not ready ────────────────────────────────
  if (!authReady) return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'center',
      height:'100vh', color:'#64748b', fontFamily:'DM Sans, sans-serif', fontSize:14 }}>
      Loading…
    </div>
  );

  // ── Not logged in ────────────────────────────
  if (!jwt) return (
    <DEVLogin onLogin={handleLogin} />
  );

  // ── App ──────────────────────────────────────
  return (
    <div style={{ minHeight:'100vh', background:'#f0f2f5', fontFamily:'DM Sans, sans-serif' }}>
      <DEVNavBar
        currentUser={currentUser}
        view={view}
        currentApp={currentApp}
        onApps={goApps}
        onLogout={handleLogout}
      />

      <div style={{ maxWidth:1200, margin:'0 auto', padding:'32px 24px' }}>

        {view === 'apps' && (
          <DEVAppList
            jwt={jwt}
            currentUser={currentUser}
            onOpenApp={openApp}
          />
        )}

        {view === 'app-detail' && currentApp && (
          <DEVAppDetail
            jwt={jwt}
            currentUser={currentUser}
            app={currentApp}
            onBack={goApps}
            onAppUpdate={updated => setCurrentApp(updated)}
          />
        )}

      </div>
    </div>
  );
}
