import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  Outlet,
  Link,
  createRootRouteWithContext,
  useRouter,
  HeadContent,
  Scripts,
} from "@tanstack/react-router";
import { useEffect, type ReactNode } from "react";

import appCss from "../styles.css?url";
import faviconAsset from "@/assets/favicon.png.asset.json";
import { reportLovableError } from "../lib/lovable-error-reporting";
import { supabase } from "@/integrations/supabase/client";
import { Toaster } from "sonner";

const SEO_KEYWORDS = [
  "Gatavase Bulky SMS","Gatavase Corporation","bulk SMS Uganda","bulk SMS Africa","SMS gateway Uganda",
  "send bulk SMS","SMS marketing Uganda","SMS API Uganda","SMS platform Africa","mass SMS sender",
  "promotional SMS","transactional SMS","OTP SMS Uganda","SMS verification Africa","mobile marketing Uganda",
  "SMS campaign software","SMS broadcasting","cheap SMS Uganda","affordable bulk SMS","SMS reseller Uganda",
  "MTN Uganda SMS","Airtel Uganda SMS","Africell Uganda SMS","UTL SMS","Smile SMS Uganda",
  "Lyca SMS Uganda","SMS to MTN","SMS to Airtel","short code Uganda","long code SMS",
  "sender ID Uganda","branded SMS sender","SMS delivery reports","SMS analytics","SMS dashboard",
  "contact management","contact groups SMS","CSV contact import","SMS templates","scheduled SMS",
  "SMS automation Uganda","business SMS Kampala","church SMS Uganda","school SMS Uganda","SACCO SMS",
  "NGO SMS Uganda","political SMS Uganda","election SMS","event SMS reminders","appointment reminders SMS",
  "two way SMS","SMS chat platform","SMS reply Uganda","mobile money SMS","MTN MoMo payments",
  "Airtel Money billing","mobile money SMS billing","M-Pesa SMS Africa","SMS for Kenya","SMS for Tanzania",
  "SMS for Rwanda","SMS for Burundi","SMS for South Sudan","SMS for DRC","SMS for Nigeria",
  "SMS for Ghana","SMS for Zambia","SMS for Malawi","SMS for Ethiopia","SMS for Cameroon",
  "pan African SMS","cross border SMS","international SMS Uganda","SMS pricing UGX","UGX 125000 SMS plan",
  "5000 SMS bundle","SMS subscription Uganda","SMS REST API","SMS webhook","developer SMS API",
  "SMS Node.js","SMS Python","SMS PHP integration","SMS WordPress plugin","ecommerce SMS Uganda",
  "Shopify SMS Uganda","WooCommerce SMS","SMS for hotels","SMS for restaurants","SMS for clinics",
  "SMS for hospitals","SMS for pharmacies","SMS for real estate","SMS for logistics","SMS for banks",
  "SMS for microfinance","SMS for telecoms","SMS for retailers","SMS for agents","SMS for distributors",
  "SMS marketing platform","reliable SMS gateway","high delivery SMS","instant SMS delivery","Uganda SMS reseller"
].join(", ");


function NotFoundComponent() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="font-display text-7xl font-bold text-gradient-brand">404</h1>
        <h2 className="mt-4 text-xl font-semibold text-foreground">Page not found</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          The page you're looking for doesn't exist or has been moved.
        </p>
        <div className="mt-6">
          <Link to="/" className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90">
            Go home
          </Link>
        </div>
      </div>
    </div>
  );
}

function ErrorComponent({ error, reset }: { error: unknown; reset: () => void }) {
  console.error(error);
  const router = useRouter();
  useEffect(() => {
    reportLovableError(error, { boundary: "tanstack_root_error_component" });
  }, [error]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-xl font-semibold tracking-tight text-foreground">This page didn't load</h1>
        <p className="mt-2 text-sm text-muted-foreground">Something went wrong. Try again or head home.</p>
        <div className="mt-6 flex flex-wrap justify-center gap-2">
          <button
            onClick={() => { router.invalidate(); reset(); }}
            className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
          >Try again</button>
          <a href="/" className="rounded-md border border-input bg-background px-4 py-2 text-sm font-medium hover:bg-accent">Go home</a>
        </div>
      </div>
    </div>
  );
}

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { title: "Gatavase Bulky SMS — Bulk SMS Platform for Uganda & Africa" },
      { name: "description", content: "Uganda's reliable bulk SMS platform. Send promotional, transactional & OTP messages to MTN, Airtel & Africell from UGX 125,000 / 5,000 SMS." },
      { name: "author", content: "Gatavase Corporation" },
      { name: "keywords", content: SEO_KEYWORDS },
      { name: "robots", content: "index, follow, max-image-preview:large" },
      { name: "googlebot", content: "index, follow" },
      { name: "theme-color", content: "#0b3b8c" },
      { name: "application-name", content: "Gatavase Bulky SMS" },
      { name: "geo.region", content: "UG" },
      { name: "geo.placename", content: "Kampala" },
      { property: "og:site_name", content: "Gatavase Bulky SMS" },
      { property: "og:title", content: "Gatavase Bulky SMS — Bulk SMS Platform for Uganda & Africa" },
      { property: "og:description", content: "Send bulk SMS across Uganda and Africa. MTN, Airtel, Africell delivery. UGX 125,000 / 5,000 SMS. Powered by Gatavase Corporation." },
      { property: "og:type", content: "website" },
      { property: "og:locale", content: "en_UG" },
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: "Gatavase Bulky SMS — Bulk SMS for Uganda & Africa" },
      { name: "twitter:description", content: "Reach every customer in Uganda with reliable bulk SMS. UGX 125,000 / 5,000 SMS. Powered by Gatavase Corporation." },
    ],
    links: [
      { rel: "icon", type: "image/png", href: faviconAsset.url },
      { rel: "shortcut icon", type: "image/png", href: faviconAsset.url },
      { rel: "apple-touch-icon", href: faviconAsset.url },
      { rel: "stylesheet", href: appCss },
      { rel: "preconnect", href: "https://fonts.googleapis.com" },
      { rel: "preconnect", href: "https://fonts.gstatic.com", crossOrigin: "" },
      { rel: "stylesheet", href: "https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" },
    ],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Organization",
          name: "Gatavase Bulky SMS",
          url: "https://sms.gatavaseug.com",
          logo: faviconAsset.url,
          parentOrganization: { "@type": "Organization", name: "Gatavase Corporation" },
          areaServed: ["UG", "KE", "TZ", "RW", "Africa"],
          description: "Bulk SMS platform for Uganda and Africa — promotional, transactional and OTP messaging.",
          sameAs: ["https://sms.gatavaseug.com"],
          contactPoint: {
            "@type": "ContactPoint",
            contactType: "customer support",
            areaServed: "UG",
            availableLanguage: ["en"],
          },
        }),
      },
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "WebSite",
          name: "Gatavase Bulky SMS",
          url: "https://sms.gatavaseug.com",
          inLanguage: "en-UG",
          publisher: { "@type": "Organization", name: "Gatavase Corporation" },
        }),
      },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

function RootShell({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head><HeadContent /></head>
      <body>{children}<Scripts /></body>
    </html>
  );
}

function RootComponent() {
  const { queryClient } = Route.useRouteContext();
  const router = useRouter();

  useEffect(() => {
    const { data: sub } = supabase.auth.onAuthStateChange((event) => {
      if (event !== "SIGNED_IN" && event !== "SIGNED_OUT" && event !== "USER_UPDATED") return;
      router.invalidate();
      if (event !== "SIGNED_OUT") queryClient.invalidateQueries();
    });
    return () => sub.subscription.unsubscribe();
  }, [router, queryClient]);

  return (
    <QueryClientProvider client={queryClient}>
      <Outlet />
      <Toaster richColors position="top-right" />
    </QueryClientProvider>
  );
}
