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

import { AppNav } from "./components/AppNav";
import type { Route } from "./+types/root";
import { getShopifyApiKey, getShopifyApiSecret } from "./lib/env.server";
import "./app.css";

export async function loader({}: Route.LoaderArgs) {
  // Ensure both credentials are configured. Only the public API key is returned.
  getShopifyApiSecret();
  return {
    apiKey: getShopifyApiKey(),
  };
}

export function meta({ loaderData }: Route.MetaArgs) {
  return [
    { title: "B2B Customer Portal" },
    { name: "shopify-api-key", content: loaderData?.apiKey ?? "" },
  ];
}

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" />
        <Meta />
        <Links />
        {/* App Bridge must load with the API key meta for embedded Admin auth + UI. */}
        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js" />
        <script src="https://cdn.shopify.com/shopifycloud/polaris.js" />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App({ loaderData }: Route.ComponentProps) {
  return (
    <>
      {/* Keep the key in the document even when child routes replace root meta */}
      <meta name="shopify-api-key" content={loaderData.apiKey} />
      <AppNav />
      <Outlet />
    </>
  );
}

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 style={{ padding: "2rem", fontFamily: "system-ui, sans-serif" }}>
      <h1>{message}</h1>
      <p>{details}</p>
      {stack && (
        <pre style={{ width: "100%", padding: "1rem", overflowX: "auto" }}>
          <code>{stack}</code>
        </pre>
      )}
    </main>
  );
}
