import { useEffect } from "react";
import {
  isRouteErrorResponse,
  Link,
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "react-router";

import type { Route } from "./+types/root";
import "./app.css";
import { AuthProvider } from "~/lib/auth-context"
import { DataProvider } from "~/lib/data-context";
import Nav from "~/components/Nav";

export const links: Route.LinksFunction = () => [
  { rel: "preconnect", href: "https://fonts.googleapis.com" },
  {
    rel: "preconnect",
    href: "https://fonts.gstatic.com",
    crossOrigin: "anonymous",
  },
  {
    rel: "stylesheet",
    href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap",
  },
];

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        {/* Runs before React hydrates to avoid flash of wrong theme */}
        <script dangerouslySetInnerHTML={{ __html: `(function(){try{var t=localStorage.getItem('pi-theme'),d=matchMedia('(prefers-color-scheme:dark)').matches;if(t==='dark'||(t!=='light'&&d))document.documentElement.classList.add('dark')}catch(e){}})()` }} />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export function HydrateFallback() {
  return (
    <div className="min-h-screen flex flex-col items-center justify-center">
      <div className="w-8 h-8 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin" />
    </div>
  );
}

export default function App() {
  useEffect(() => {
    // When a new service worker activates after a deploy it calls skipWaiting(),
    // which fires 'controllerchange' on any already-open page. At that point the
    // page's prerendered HTML came from the old SW cache while the new JS bundle
    // is already loaded, causing a React hydration mismatch (error #418). Reloading
    // here ensures the HTML and JS always come from the same build.
    navigator.serviceWorker?.addEventListener('controllerchange', () => {
      window.location.reload()
    })
  }, [])

  return (
    <AuthProvider>
      <DataProvider>
      <div className="min-h-screen flex flex-col">
        <Nav />
        <div className="flex-1 flex flex-col">
          <Outlet />
        </div>
        <footer className="border-t border-stone-200 dark:border-stone-800 py-4 px-4 md:px-8">
          <div className="max-w-5xl mx-auto flex items-center justify-between gap-4 text-xs text-stone-400 dark:text-stone-500">
            <div className="flex items-center gap-4">
              <Link to="/faq" className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors">FAQ</Link>
              <Link to="/kanban?uri=at%3A%2F%2Fdid%3Aplc%3Abhdsqspk6a3qtp6baxbyumxb%2Fsite.standard.document%2F3mn6tvs7gycga" className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors">Roadmap</Link>
              <Link to="/tos" className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors">Terms</Link>
              <Link to="/privacy" className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors">Privacy</Link>
            </div>
            <div className="flex items-center gap-4">
              <a
                href="https://bsky.app/profile/lemma.pub"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Lemma on Bluesky"
                title="Lemma on Bluesky"
                className="opacity-50 hover:opacity-100 transition-opacity"
              >
                <img src="/Bluesky_Logo.svg" alt="Bluesky" className="h-5 w-5" />
              </a>
              <a
                href="https://tangled.org/lemma.pub/lemma"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Source code on Tangled"
                title="Source code on Tangled"
                className="opacity-50 hover:opacity-100 transition-opacity"
              >
                <img src="/tangled_black.svg" alt="Tangled" className="h-5 dark:hidden" />
                <img src="/tangled_white.svg" alt="Tangled" className="h-5 hidden dark:block" />
              </a>
            </div>
          </div>
        </footer>
      </div>
      </DataProvider>
    </AuthProvider>
  );
}

export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  let message = "Oops!";
  let details = "An unexpected error occurred.";
  let stack: string | undefined;

  if (isRouteErrorResponse(error)) {
    message = error.status === 404 ? "404" : "Error";
    details =
      error.status === 404
        ? "The requested page could not be found."
        : error.statusText || details;
  } else if (import.meta.env.DEV && error && error instanceof Error) {
    details = error.message;
    stack = error.stack;
  }

  return (
    <main className="pt-16 p-4 container mx-auto">
      <h1>{message}</h1>
      <p>{details}</p>
      {stack && (
        <pre className="w-full p-4 overflow-x-auto">
          <code>{stack}</code>
        </pre>
      )}
    </main>
  );
}
