import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { initDB } from './db/database';
import { seedDatabase } from './db/seed';
import { getDB } from './db/database';
import { useAppStore } from './stores/useAppStore';
import './index.css';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      networkMode: 'offlineFirst',
      staleTime: 5 * 60 * 1000,
      retry: 0,
    },
  },
});

function LoadingScreen() {
  return (
    <div className="min-h-screen bg-slate-900 flex items-center justify-center">
      <div className="text-center">
        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-maritime-blue/20 flex items-center justify-center animate-pulse">
          <svg className="w-8 h-8 text-maritime-blue" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-white">MaritimeTrack</h1>
        <p className="text-slate-400 mt-2">Initializing database...</p>
      </div>
    </div>
  );
}

function AppRoot() {
  const [ready, setReady] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const setDBReady = useAppStore((s) => s.setDBReady);

  useEffect(() => {
    async function bootstrap() {
      try {
        await initDB();
        const db = await getDB();

        const cnt = await db.query('SELECT COUNT(*) as c FROM vessels') as unknown as { c: number }[];
        if ((cnt[0]?.c ?? 0) === 0) {
          await seedDatabase(db as unknown as {
            exec(sql: string, params?: unknown[]): Promise<void>;
            query(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;
          });
        }
        localStorage.setItem('marinetrack_seeded', 'true');

        const deviceId = localStorage.getItem('marinetrack_device_id');
        if (!deviceId) {
          const { ulid } = await import('ulid');
          localStorage.setItem('marinetrack_device_id', ulid());
        }

        setDBReady(true);
        setReady(true);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to initialize');
      }
    }

    bootstrap();

    const handleOnline = () => useAppStore.getState().setOnline(true);
    const handleOffline = () => useAppStore.getState().setOnline(false);
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  if (error) {
    return (
      <div className="min-h-screen bg-slate-900 flex items-center justify-center">
        <div className="text-center p-8">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-maritime-red/20 flex items-center justify-center">
            <svg className="w-8 h-8 text-maritime-red" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h1 className="text-xl font-bold text-white mb-2">Initialization Failed</h1>
          <p className="text-slate-400 mb-2">{error}</p>
          <div className="text-xs text-slate-500 bg-slate-800 rounded-lg p-3 mt-3 text-left space-y-1">
            <div>SharedArrayBuffer: {typeof SharedArrayBuffer !== 'undefined' ? 'Available' : 'NOT AVAILABLE'}</div>
            <div>OPFS: {typeof navigator?.storage?.getDirectory === 'function' ? 'Supported' : 'Not supported'}</div>
            <div>Browser: {navigator.userAgent}</div>
          </div>
          <button
            onClick={() => window.location.reload()}
            className="mt-4 px-6 py-3 bg-maritime-blue text-white rounded-lg hover:bg-maritime-blue/90 transition-colors min-h-[56px]"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  if (!ready) {
    return <LoadingScreen />;
  }

  return (
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  );
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <AppRoot />
  </React.StrictMode>,
);
