import { useState, useEffect } from 'react';
import './App.css';
import './TenantTheme.css';
import { useAuth } from './context/AuthContext';
import { useIam } from './context/IamContext';
import LoginGateway from './components/LoginGateway';
import SupremeDashboard from './layouts/SupremeDashboard';
import TenantDashboard from './layouts/TenantDashboard';

import AuthenticatorPWA from './components/AuthenticatorPWA';

function App() {
  const { isAuthenticated, isLoading } = useAuth();
  const { identity } = useIam();

  if (window.location.pathname === '/authenticator') {
    return <AuthenticatorPWA />;
  }

  if (isLoading) {
    return <div style={{width: '100vw', height: '100vh', background: 'black', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#00f3ff', fontFamily: 'monospace'}}>INITIALIZING QUANTUM STATE...</div>;
  }

  // Auth Guard: Memblokir akses Dasbor jika belum Login!
  if (!isAuthenticated) {
    return <LoginGateway />;
  }

  // Mencegah Race Condition: Menunggu IamContext menyelesasikan ekstraksi JWT
  if (!identity) {
    return <div style={{width: '100vw', height: '100vh', background: 'black', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a855f7', fontFamily: 'monospace', letterSpacing: '2px'}}>EXTRACTING QUANTUM IDENTITY...</div>;
  }

  // SHAPESHIFTING UI (FASE 40) - Pemisahan Mutlak DOM Tree
  if (identity.role === 'supreme_admin') {
    return <SupremeDashboard />;
  }

  if (identity.role === 'tenant') {
    return <TenantDashboard />;
  }

  // Fallback Darurat
  return <div style={{color: 'red', padding: '50px'}}>CRITICAL ERROR: ROLE NOT RECOGNIZED</div>;
}

export default App;
