import React, { useState, useEffect, Suspense, lazy } from 'react';
import { Layout } from './components/layout/Layout.tsx';
import { ErrorBoundary } from './components/ui/ErrorBoundary.tsx';
import { useLenis } from './hooks/useLenis.ts';

const HomePage = lazy(() => import('./pages/HomePage.tsx').then(m => ({ default: m.default })));
const DiagnosticsPage = lazy(() => import('./pages/DiagnosticsPage.tsx').then(m => ({ default: m.default })));
const IncidentsPage = lazy(() => import('./pages/IncidentsPage.tsx').then(m => ({ default: m.default })));
const SystemPage = lazy(() => import('./pages/SystemPage.tsx').then(m => ({ default: m.default })));
const NotFoundPage = lazy(() => import('./pages/NotFoundPage.tsx').then(m => ({ default: m.default })));

const LoadingFallback = () => (
  <div className="flex items-center justify-center min-h-screen">
    <div className="text-center">
      <div className="w-8 h-8 border-2 border-[var(--brand-500)] border-t-transparent rounded-full animate-spin mx-auto mb-4" />
      <p className="text-[var(--ink-muted)]">Loading diagnostics...</p>
    </div>
  </div>
);

const App: React.FC = () => {
  const [route, setRoute] = useState(window.location.hash || '#/');

  useLenis();

  useEffect(() => {
    const handleHashChange = () => {
      setRoute(window.location.hash || '#/');
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  const hash = route.split('?')[0];

  const renderPage = () => {
    switch (hash) {
      case '#/':
        return <HomePage />;
      case '#/diagnostics':
        return <DiagnosticsPage />;
      case '#/incidents':
        return <IncidentsPage />;
      case '#/system':
        return <SystemPage />;
      default:
        return <NotFoundPage />;
    }
  };

  return (
    <ErrorBoundary>
      <Layout>
        <Suspense fallback={<LoadingFallback />}>
          {renderPage()}
        </Suspense>
      </Layout>
    </ErrorBoundary>
  );
};

export default App;