import { lazy, Suspense, useEffect, type ReactElement } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from '@lilith/ui-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AppShell } from './layout/AppShell';
import { initApiConfig } from './api/client';
import { useDashboardRefresh } from './hooks/useSync';
import { STALE_TIME } from './hooks/refreshConfig';

const DashboardTab = lazy(() =>
  import('./tabs/Dashboard').then((m) => ({ default: m.DashboardTab })),
);
const MessagesTab = lazy(() =>
  import('./tabs/Messages').then((m) => ({ default: m.MessagesTab })),
);
const PhotosTab = lazy(() =>
  import('./tabs/Photos').then((m) => ({ default: m.PhotosTab })),
);
const MailTab = lazy(() =>
  import('./tabs/Mail').then((m) => ({ default: m.MailTab })),
);
const SettingsTab = lazy(() =>
  import('./tabs/Settings').then((m) => ({ default: m.SettingsTab })),
);
const ContactsTab = lazy(() =>
  import('./tabs/Contacts').then((m) => ({ default: m.ContactsTab })),
);
const CalendarTab = lazy(() =>
  import('./tabs/Calendar').then((m) => ({ default: m.CalendarTab })),
);
const RemindersTab = lazy(() =>
  import('./tabs/Reminders').then((m) => ({ default: m.RemindersTab })),
);
const NotesTab = lazy(() =>
  import('./tabs/Notes').then((m) => ({ default: m.NotesTab })),
);

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 2,
      staleTime: STALE_TIME,
    },
  },
});

function TabLoader(): ReactElement {
  return (
    <div
      role="status"
      aria-live="polite"
      style={{ padding: 24, fontSize: 13, color: '#8a8a9a', textAlign: 'center' }}
    >
      Loading…
    </div>
  );
}

function AppRefresh(): null {
  useDashboardRefresh();
  return null;
}

export function App(): ReactElement {
  useEffect(() => {
    initApiConfig();
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <AppRefresh />
      <BrowserRouter>
        <AppShell>
          <Suspense fallback={<TabLoader />}>
            <Routes>
              <Route path="/" element={<Navigate to="/dashboard" replace />} />
              <Route path="/dashboard" element={<DashboardTab />} />
              <Route path="/messages" element={<MessagesTab />} />
              <Route path="/photos" element={<PhotosTab />} />
              <Route path="/mail" element={<MailTab />} />
              <Route path="/calendar" element={<CalendarTab />} />
              <Route path="/reminders" element={<RemindersTab />} />
              <Route path="/notes" element={<NotesTab />} />
              <Route path="/contacts" element={<ContactsTab />} />
              <Route path="/settings" element={<SettingsTab />} />
              <Route path="*" element={<Navigate to="/dashboard" replace />} />
            </Routes>
          </Suspense>
        </AppShell>
      </BrowserRouter>
    </QueryClientProvider>
  );
}
