import type { LoaderFunctionArgs } from "react-router";
import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
  useLoaderData,
  useRouteError,
} from "react-router";
import polarisStyles from "@shopify/polaris/build/esm/styles.css?url";
import dashboardStyles from "./dashboard.css?url";

export const links = () => [
  { rel: "preconnect", href: "https://cdn.shopify.com" },
  { rel: "preconnect", href: "https://fonts.googleapis.com" },
  { rel: "preconnect", href: "https://fonts.gstatic.com", crossOrigin: "anonymous" },
  { rel: "stylesheet", href: polarisStyles },
  { rel: "stylesheet", href: dashboardStyles },
  {
    rel: "preload",
    as: "style",
    href: "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css",
  },
  {
    rel: "stylesheet",
    href: "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css",
  },
  {
    rel: "stylesheet",
    href: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",
  },
];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const pathname = url.pathname.toLowerCase();
  const shop = url.searchParams.get("shop") || "";
  const host = url.searchParams.get("host") || "";
  const idToken = url.searchParams.get("id_token") || "";

  // Load App Bridge v4 on every merchant app page (excluding standalone public/SaaS admin pages)
  const isShopifyEmbedded =
    !pathname.startsWith("/saas-admin") &&
    !pathname.startsWith("/privacy") &&
    !pathname.startsWith("/help") &&
    !pathname.startsWith("/support") &&
    !pathname.startsWith("/docs") &&
    !pathname.startsWith("/documentation") &&
    !pathname.startsWith("/api") &&
    (pathname.startsWith("/app") ||
      pathname === "/" ||
      pathname.startsWith("/billing") ||
      pathname.startsWith("/settings") ||
      pathname.startsWith("/knowledge") ||
      pathname.startsWith("/notifications") ||
      pathname.startsWith("/dashboard") ||
      Boolean(shop || host || idToken));

  return {
    apiKey: process.env.SHOPIFY_API_KEY || "ff484160a48beda29e79144ee4e9a819",
    isShopifyEmbedded,
    shop,
  };
};

export default function App() {
  const { apiKey, isShopifyEmbedded, shop } = useLoaderData<typeof loader>();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        {isShopifyEmbedded && apiKey ? (
          <>
            <meta name="shopify-api-key" content={apiKey} />
            {shop ? <meta name="shopify-shop" content={shop} /> : null}
            <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
          </>
        ) : null}
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export function ErrorBoundary() {
  const error: any = useRouteError();
  console.error("[Root ErrorBoundary]:", error);
  const errorMessage = error?.message || error?.data?.message || (typeof error === "string" ? error : "An unexpected application error occurred.");
  const fallbackApiKey = "ff484160a48beda29e79144ee4e9a819";

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="shopify-api-key" content={fallbackApiKey} />
        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
        <title>ShopPilot AI — Error</title>
        <Meta />
        <Links />
      </head>
      <body style={{ margin: 0, padding: "40px 20px", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif", backgroundColor: "#f8fafc" }}>
        <div style={{ maxWidth: "520px", margin: "40px auto", backgroundColor: "#ffffff", padding: "32px", borderRadius: "14px", border: "1px solid #e2e8f0", boxShadow: "0 10px 25px -5px rgba(0,0,0,0.08)", textAlign: "center" }}>
          <div style={{ width: "48px", height: "48px", borderRadius: "50%", backgroundColor: "#fee2e2", color: "#dc2626", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: "22px", marginBottom: "16px" }}>
            ⚠
          </div>
          <h2 style={{ fontSize: "20px", fontWeight: 700, margin: "0 0 8px 0", color: "#0f172a" }}>ShopPilot AI Assistant</h2>
          <p style={{ fontSize: "14px", color: "#64748b", margin: "0 0 16px 0", lineHeight: 1.5 }}>
            {errorMessage}
          </p>
          <div style={{ marginTop: "24px", display: "flex", gap: "12px", justifyContent: "center" }}>
            <button
              type="button"
              onClick={() => {
                if (typeof window !== "undefined") {
                  window.location.reload();
                }
              }}
              style={{
                display: "inline-block",
                padding: "10px 20px",
                backgroundColor: "#4f46e5",
                color: "#ffffff",
                border: "none",
                borderRadius: "8px",
                cursor: "pointer",
                fontWeight: 600,
                fontSize: "14px"
              }}
            >
              Reload Application
            </button>
          </div>
        </div>
        <Scripts />
      </body>
    </html>
  );
}
