import { useState, useEffect } from 'react';
import Topbar       from './components/Topbar';
import TokenBar     from './components/TokenBar';
import Scenario1Tab from './tabs/Scenario1Tab';
import Scenario2Tab from './tabs/Scenario2Tab';
import ApiTab       from './tabs/ApiTab';
import AdminTab     from './tabs/AdminTab';
import IntelTab     from './tabs/IntelTab';
import { getToken, clearToken } from './api';

const TABS = [
  { id: 'scenario1', label: '🔬 Scenario 1: Behavior' },
  { id: 'scenario2', label: '🚨 Scenario 2: Attacks'  },
  { id: 'api',       label: '🔧 API Testing'           },
  { id: 'admin',     label: '🛡️ Admin Dashboard'       },
  { id: 'intel',     label: '🧠 Intelligence'          },
];

export default function App() {
  const [activeTab,     setActiveTab]     = useState('scenario1');
  const [token,         setToken]         = useState(getToken);
  const [serverStatus,  setServerStatus]  = useState('checking');

  const refreshToken = () => setToken(getToken());
  const handleClear  = () => { clearToken(); setToken(''); };

  const ping = async () => {
    setServerStatus('checking');
    try {
      const r = await fetch('/health');
      setServerStatus(r.ok ? 'online' : 'error');
    } catch {
      setServerStatus('offline');
    }
  };

  useEffect(() => { ping(); }, []);

  return (
    <div className="app">
      <Topbar serverStatus={serverStatus} onRefresh={ping} />

      <div className="container">
        <div className="hero">
          <h1>Adaptive Authentication <span>Framework</span></h1>
          <p>
            Production-ready risk-based auth &mdash; JWT &bull; 2FA &bull;
            Behavioral Analysis &bull; Anomaly Detection
          </p>
        </div>

        <TokenBar token={token} onRefresh={refreshToken} onClear={handleClear} />

        <nav className="main-tabs" role="tablist">
          {TABS.map(t => (
            <button
              key={t.id}
              role="tab"
              aria-selected={activeTab === t.id}
              className={activeTab === t.id ? 'active' : ''}
              onClick={() => setActiveTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </nav>

        <div role="tabpanel">
          {activeTab === 'scenario1' && <Scenario1Tab onTokenSave={refreshToken} />}
          {activeTab === 'scenario2' && <Scenario2Tab onTokenSave={refreshToken} />}
          {activeTab === 'api'       && <ApiTab       onTokenSave={refreshToken} />}
          {activeTab === 'admin'     && <AdminTab     onTokenSave={refreshToken} />}
          {activeTab === 'intel'     && <IntelTab     onTokenSave={refreshToken} />}
        </div>
      </div>
    </div>
  );
}
