import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Navigate, Route, Routes, useParams } from 'react-router-dom';
import './styles.css';
import { SessionProvider, useSession } from './lib/session';
import { AppShell } from './components/AppShell';
import { HomePage } from './pages/Home';
import { SettingsPage } from './pages/Settings';
import { CreateStorePage } from './pages/CreateStore';
import { ForgotPasswordPage, LoginPage, ResetPasswordPage, SignupPage, VerifyEmailPage } from './pages/auth';
import { Illustration } from './components/Icon';

function Loading() {
  return <div className="auth"><p role="status" style={{ color: 'var(--text-muted)' }}>Loading…</p></div>;
}

/** Signed-out visitors go to log in; signed-in ones with no store go to store creation. */
function RequireStore() {
  const { me, loading } = useSession();
  const { storeId } = useParams();
  if (loading) return <Loading />;
  if (!me) return <Navigate to="/login" replace />;
  if (!me.stores.length) return <Navigate to="/stores/new" replace />;
  if (!me.stores.some((s) => s.storeId === storeId)) return <Navigate to={`/s/${me.stores[0].storeId}`} replace />;
  return <AppShell />;
}

function RequireAuth({ children }: { children: React.ReactNode }) {
  const { me, loading } = useSession();
  if (loading) return <Loading />;
  if (!me) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

function GuestOnly({ children }: { children: React.ReactNode }) {
  const { me, loading } = useSession();
  if (loading) return <Loading />;
  if (me) return <Navigate to={me.stores.length ? `/s/${me.stores[0].storeId}` : '/stores/new'} replace />;
  return <>{children}</>;
}

function Landing() {
  const { me, loading } = useSession();
  if (loading) return <Loading />;
  if (!me) return <Navigate to="/login" replace />;
  return <Navigate to={me.stores.length ? `/s/${me.stores[0].storeId}` : '/stores/new'} replace />;
}

function NotFound() {
  return (
    <div className="empty">
      <div className="art"><Illustration kind="box" /></div>
      <h2>We can’t find that page</h2>
      <p>The link may be old, or the page may not be built yet.</p>
      <a className="btn btn-primary" href="/">Go to your store</a>
    </div>
  );
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <BrowserRouter>
      <SessionProvider>
        <Routes>
          <Route path="/" element={<Landing />} />
          <Route path="/login" element={<GuestOnly><LoginPage /></GuestOnly>} />
          <Route path="/signup" element={<GuestOnly><SignupPage /></GuestOnly>} />
          <Route path="/forgot-password" element={<GuestOnly><ForgotPasswordPage /></GuestOnly>} />
          <Route path="/reset-password" element={<ResetPasswordPage />} />
          <Route path="/verify-email" element={<VerifyEmailPage />} />
          <Route path="/stores/new" element={<RequireAuth><CreateStorePage /></RequireAuth>} />
          <Route path="/s/:storeId" element={<RequireStore />}>
            <Route index element={<HomePage />} />
            <Route path="settings" element={<SettingsPage />} />
            <Route path="*" element={<NotFound />} />
          </Route>
          <Route path="*" element={<NotFound />} />
        </Routes>
      </SessionProvider>
    </BrowserRouter>
  </StrictMode>,
);
