import type { Metadata } from "next";
import { headers } from "next/headers";
import "./globals.css";
import { PublicChrome } from "@/components/public-chrome";
import { BRAND_PRELOAD } from "@/lib/brand";

export const metadata: Metadata = {
  title: { default: "Trackopia — Affiliate & influencer marketing for Shopify", template: "%s — Trackopia" },
  description:
    "Run your entire affiliate program inside Shopify: recruit affiliates, issue real discount codes, track every sale, and pay commissions automatically.",
};

const SHOPIFY_API_KEY = process.env.NEXT_PUBLIC_SHOPIFY_API_KEY ?? "";

export default async function RootLayout({
  children,
}: Readonly<{ children: React.ReactNode }>) {
  // Embedded (Shopify admin) loads carry a host param; middleware flags them.
  const embedded = (await headers()).get("x-embedded") === "1";

  return (
    // suppressHydrationWarning: the brand-preload script sets a --brand style on
    // <html> before hydration, which would otherwise flag an attribute mismatch.
    <html lang="en" suppressHydrationWarning>
      <head>
        {/* Shopify App Bridge — required for embedded apps. Loaded from Shopify's
            CDN as a plain, non-async script so it initialises before app code.
            Only on embedded loads so the public marketing site stays clean. */}
        {embedded && SHOPIFY_API_KEY ? (
          <>
            <meta name="shopify-api-key" content={SHOPIFY_API_KEY} />
            {/* eslint-disable-next-line @next/next/no-sync-scripts */}
            <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js" />
          </>
        ) : null}
      </head>
      <body className="min-h-screen bg-gray-50 text-gray-900 antialiased">
        {/* Apply cached brand colours before first paint — kills the flash. */}
        <script dangerouslySetInnerHTML={{ __html: BRAND_PRELOAD }} />
        {embedded ? (
          // Embedded admin renders full-bleed (no public chrome).
          children
        ) : (
          <PublicChrome>{children}</PublicChrome>
        )}
      </body>
    </html>
  );
}
