import { useState, useEffect } from 'react';
import { LandingPage } from './pages/LandingPage';
import { GeneratePage } from './pages/GeneratePage';
import { AnalyzePage } from './pages/AnalyzePage';
import { HistoryPage } from './pages/HistoryPage';
import { SettingsPage } from './pages/SettingsPage';

type Page = 'landing' | 'generate' | 'analyze' | 'history' | 'settings';

function useHashRouter(): [Page, (p: Page) => void] {
  const getPage = (): Page => {
    const hash = window.location.hash.slice(1) || 'landing';
    if (['landing', 'generate', 'analyze', 'history', 'settings'].includes(hash)) return hash as Page;
    return 'landing';
  };
  const [page, setPage] = useState<Page>(getPage());
  useEffect(() => {
    const handler = () => setPage(getPage());
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);
  const navigate = (p: Page) => {
    window.location.hash = p === 'landing' ? '' : p;
    setPage(p);
    window.scrollTo(0, 0);
  };
  return [page, navigate];
}

function Navbar({ page, onNavigate }: { page: Page; onNavigate: (p: Page) => void }) {
  if (page === 'landing') return null;

  const links: { id: Page; label: string; icon: string }[] = [
    { id: 'generate', label: 'Generate', icon: '⚡' },
    { id: 'analyze', label: 'Analyze', icon: '🔬' },
    { id: 'history', label: 'History', icon: '📋' },
    { id: 'settings', label: 'Settings', icon: '⚙️' },
  ];

  return (
    <nav className="sticky top-0 z-50 bg-[#0a0a0f]/80 backdrop-blur-xl border-b border-white/[0.04]">
      <div className="max-w-[1400px] mx-auto px-6 py-3 flex items-center justify-between">
        <button onClick={() => onNavigate('landing')} className="flex items-center gap-2.5 hover:opacity-80 transition">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-cyan-500 flex items-center justify-center text-xs font-black shadow-md shadow-emerald-500/20">T</div>
          <span className="font-bold text-sm tracking-tight">TestGenius<span className="text-emerald-400">.ai</span></span>
        </button>
        <div className="flex gap-1">
          {links.map(l => (
            <button key={l.id} onClick={() => onNavigate(l.id)}
              className={`px-3.5 py-2 rounded-lg text-xs font-medium transition-all ${
                page === l.id
                  ? 'bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 shadow-sm shadow-emerald-500/5'
                  : 'text-gray-500 hover:text-gray-300 border border-transparent hover:border-white/[0.06]'
              }`}>
              <span className="mr-1.5">{l.icon}</span>{l.label}
            </button>
          ))}
        </div>
      </div>
    </nav>
  );
}

function ErrorFallback({ error, onReset }: { error: string; onReset: () => void }) {
  return (
    <div className="min-h-screen bg-[#0a0a0f] flex items-center justify-center p-8">
      <div className="bg-red-500/5 border border-red-500/20 rounded-2xl p-10 max-w-md text-center">
        <div className="text-4xl mb-5">⚠️</div>
        <h2 className="text-lg font-bold text-white mb-2">Something went wrong</h2>
        <p className="text-sm text-red-300/80 mb-6">{error}</p>
        <button onClick={onReset}
          className="px-6 py-2.5 bg-white/[0.05] hover:bg-white/[0.08] border border-white/[0.08] rounded-xl text-sm font-medium transition">
          Try Again
        </button>
      </div>
    </div>
  );
}

export default function App() {
  const [page, navigate] = useHashRouter();
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const handler = (e: ErrorEvent) => { setError(e.message); e.preventDefault(); };
    window.addEventListener('error', handler);
    return () => window.removeEventListener('error', handler);
  }, []);

  if (error) return <ErrorFallback error={error} onReset={() => { setError(null); navigate('landing'); }} />;

  return (
    <div className="min-h-screen bg-[#0a0a0f] text-white">
      <Navbar page={page} onNavigate={navigate} />
      <main className="animate-fade-in">
        {page === 'landing' && <LandingPage onNavigate={navigate} />}
        {page === 'generate' && <GeneratePage />}
        {page === 'analyze' && <AnalyzePage />}
        {page === 'history' && <HistoryPage />}
        {page === 'settings' && <SettingsPage />}
      </main>
    </div>
  );
}
