import { ThemeProvider } from "next-themes";
import Script from "next/script";
import type { ReactNode } from "react";
import * as React from "react";
import type { LinksFunction } from "react-router";
import { Links, Meta, Outlet, Scripts, useLoaderData } from "react-router";
// buzzwareTech imports
import { SITE_DESCRIPTION, SITE_NAME } from "@buzzwaretech/constants";
import { cn } from "@buzzwaretech/utils";
// types
// assets
import favicon16 from "@/app/assets/favicon/favicon-16x16.png?url";
import favicon32 from "@/app/assets/favicon/favicon-32x32.png?url";
import faviconIco from "@/app/assets/favicon/favicon.ico?url";
import icon180 from "@/app/assets/icons/icon-180x180.png?url";
import icon512 from "@/app/assets/icons/icon-512x512.png?url";
import ogImage from "@/app/assets/og-image.png?url";
import globalStyles from "@/styles/globals.css?url";
import type { Route } from "./+types/root";
// components
// local
import { CustomErrorComponent } from "./error";
import { AppProvider } from "./provider";
// fonts
import "@fontsource-variable/inter";
import interVariableWoff2 from "@fontsource-variable/inter/files/inter-latin-wght-normal.woff2?url";
import "@fontsource/ibm-plex-mono";
import "@fontsource/material-symbols-rounded";

const APP_TITLE = "BuzzwareTech | Simple, project management tool.";

export const links: LinksFunction = () => [
  { rel: "icon", type: "image/png", sizes: "32x32", href: favicon32 },
  { rel: "icon", type: "image/png", sizes: "16x16", href: favicon16 },
  { rel: "shortcut icon", href: faviconIco },
  { rel: "manifest", href: "/site.webmanifest.json" },
  { rel: "apple-touch-icon", href: icon512 },
  { rel: "apple-touch-icon", sizes: "180x180", href: icon180 },
  { rel: "apple-touch-icon", sizes: "512x512", href: icon512 },
  { rel: "manifest", href: "/manifest.json" },
  { rel: "stylesheet", href: globalStyles },
  {
    rel: "preload",
    href: interVariableWoff2,
    as: "font",
    type: "font/woff2",
    crossOrigin: "anonymous",
  },
];

export async function loader() {
  const isSessionRecorderEnabled = parseInt(
    process.env.VITE_ENABLE_SESSION_RECORDER || "0",
  );
  const sessionRecorderKey = process.env.VITE_SESSION_RECORDER_KEY || "";

  return {
    isSessionRecorderEnabled,
    sessionRecorderKey,
  };
}

export function Layout({ children }: { children: ReactNode }) {
  // useLoaderData can throw when Layout is rendered by the error boundary
  // (e.g. hydration failure, missing backend). Guard with try/catch so the
  // shell never crashes and always produces consistent server/client HTML.
  let loaderData: { isSessionRecorderEnabled: number; sessionRecorderKey: string } | null = null;
  try {
    loaderData = useLoaderData<typeof loader>();
  } catch {
    // Error boundary context — loader data unavailable, use safe defaults
    loaderData = null;
  }

  const isSessionRecorderEnabled = loaderData?.isSessionRecorderEnabled ?? 0;
  const sessionRecorderKey = loaderData?.sessionRecorderKey ?? "";

  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#fff" />
        {/* Meta info for PWA */}
        <meta name="application-name" content="BuzzwareTech" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="default" />
        <meta name="apple-mobile-web-app-title" content={SITE_NAME} />
        <meta name="format-detection" content="telephone=no" />
        <meta name="mobile-web-app-capable" content="yes" />
        <Meta />
        <Links />
      </head>
      <body suppressHydrationWarning>
        <div id="context-menu-portal" />
        <div id="editor-portal" />
        <ThemeProvider
          themes={[
            "light",
            "dark",
            "light-contrast",
            "dark-contrast",
            "custom",
          ]}
          defaultTheme="system"
        >
          {children}
        </ThemeProvider>
        <Scripts />
        {mounted && !!isSessionRecorderEnabled && sessionRecorderKey && (
          <Script id="clarity-tracking">
            {`(function(c,l,a,r,i,t,y){
              c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
              t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
              y=l.getElementsByTagName(r)[0];if(y){y.parentNode.insertBefore(t,y);}
          })(window, document, "clarity", "script", "${sessionRecorderKey}");`}
          </Script>
        )}
      </body>
    </html>
  );
}

export const meta: Route.MetaFunction = () => [
  { title: APP_TITLE },
  { name: "description", content: SITE_DESCRIPTION },
  { property: "og:title", content: APP_TITLE },
  {
    property: "og:description",
    content:
      "Open-source project management tool to manage work items, cycles, and product roadmaps easily",
  },
  { property: "og:url", content: "https://app.buzzwaretech.com/" },
  { property: "og:image", content: ogImage },
  { property: "og:image:width", content: "1200" },
  { property: "og:image:height", content: "630" },
  {
    property: "og:image:alt",
    content: "BuzzwareTech - Modern project management",
  },
  {
    name: "keywords",
    content:
      "software development, plan, ship, software, accelerate, code management, release management, project management, work item tracking, agile, scrum, kanban, collaboration",
  },
  { name: "twitter:site", content: "@buzzwaretech" },
  { name: "twitter:card", content: "summary_large_image" },
  { name: "twitter:image", content: ogImage },
  { name: "twitter:image:width", content: "1200" },
  { name: "twitter:image:height", content: "630" },
  {
    name: "twitter:image:alt",
    content: "BuzzwareTech - Modern project management",
  },
];

export default function Root() {
  return (
    <AppProvider>
      <div
        className={cn(
          "relative flex h-screen w-full flex-col overflow-hidden bg-canvas",
          "desktop-app-container",
        )}
      >
        <main className="relative h-full w-full overflow-hidden">
          <Outlet />
        </main>
      </div>
    </AppProvider>
  );
}

export function HydrateFallback() {
  return (
    <div className="relative flex h-screen w-full items-center justify-center bg-canvas">
      <div className="flex items-center justify-center">
        {/* Simple safe spinner markup to avoid server/client mismatch */}
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-accent-primary border-t-transparent" />
      </div>
    </div>
  );
}

export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  return <CustomErrorComponent error={error} />;
}
