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';

// ═══ ERROR BOUNDARY ═══
function ErrorBoundary({ children }: { children: React.ReactNode }) {
  const [error, setError] = useState<Error | null>(null);

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

  if (error) {
    return (
      <div className="min-h-screen bg-[#0a0a0f] flex items-center justify-center">
        <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-8 max-w-md text-center">
          <div className="text-3xl mb-4">⚠️</div>
          <h2 className="text-lg font-bold text-white mb-2">Something went wrong</h2>
          <p className="text-sm text-red-300 mb-4">{error.message}</p>
          <button onClick={() => { setError(null); window.location.hash = ''; }}
            className="px-4 py-2 bg-red-500/20 hover:bg-red-500/30 border border-red-500/30 rounded-lg text-sm text-white transition">
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}

// ═══ HASH ROUTER ═══
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, setPageState] = useState<Page>(getPage());

  useEffect(() => {
    const handler = () => setPageState(getPage());
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);

  const navigate = (p: Page) => {
    window.location.hash = p === 'landing' ? '' : p;
    setPageState(p);
  };

  return [page, navigate];
}

// ═══ NAVIGATION BAR ═══
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">
          <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-emerald-500 to-cyan-500 flex items-center justify-center text-xs font-bold">T</div>
          <span className="font-bold text-sm">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 py-1.5 rounded-lg text-xs font-medium transition-all ${
                page === l.id
                  ? 'bg-emerald-500/10 text-emerald-300 border border-emerald-500/20'
                  : 'text-gray-500 hover:text-gray-300 border border-transparent'
              }`}>
              <span className="mr-1">{l.icon}</span>{l.label}
            </button>
          ))}
        </div>
      </div>
    </nav>
  );
}

// ═══ LOADING SKELETON ═══
export function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-4 p-6">
      <div className="h-4 bg-white/[0.05] rounded w-1/3"></div>
      <div className="h-32 bg-white/[0.03] rounded-xl"></div>
      <div className="h-4 bg-white/[0.05] rounded w-2/3"></div>
      <div className="h-4 bg-white/[0.05] rounded w-1/2"></div>
    </div>
  );
}

// ═══ MAIN APP ═══
export default function App() {
  const [page, navigate] = useHashRouter();

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