import "@/index.css";
import type { Metadata, Viewport } from "next";
import Script from "next/script";
import type { ReactNode } from "react";

import Providers from "./providers";
import AppShell from "./app-shell";
import { getLang } from "@/lib/seo/lang";
import { SITE, SITE_URL } from "@/lib/seo/site";
import { JsonLd, organizationLd, websiteLd } from "@/lib/seo/jsonld";

const GTM_ID = process.env.NEXT_PUBLIC_GTM_ID || "GTM-PXPNF44Z";

/** البيانات الوصفية العامة — تُكملها كل صفحة بـ metadata أو generateMetadata */
export async function generateMetadata(): Promise<Metadata> {
    const lang = await getLang();
    return {
        metadataBase: new URL(SITE_URL),
        title: { default: SITE.defaultTitle, template: "%s" },
        description: SITE.description[lang],
        applicationName: SITE.name[lang],
        authors: [{ name: SITE.name[lang], url: SITE_URL }],
        creator: SITE.name[lang],
        publisher: SITE.name[lang],
        icons: {
            icon: [{ url: "/IvoryLogo.svg", type: "image/svg+xml" }, { url: "/favicon.ico" }],
            apple: "/IvoryLogo.svg",
        },
        formatDetection: { telephone: false },
        verification: {
            google: process.env.GOOGLE_SITE_VERIFICATION || undefined,
            other: process.env.BING_SITE_VERIFICATION ? { "msvalidate.01": process.env.BING_SITE_VERIFICATION } : undefined,
        },
    };
}

export const viewport: Viewport = {
    width: "device-width",
    initialScale: 1,
    themeColor: "#6A2F38",
};

export default async function RootLayout({ children }: { children: ReactNode }) {
    const lang = await getLang();
    const dir = lang === "ar" ? "rtl" : "ltr";

    return (
        <html lang={lang} dir={dir} suppressHydrationWarning>
            <body dir={dir} lang={lang} className={dir} suppressHydrationWarning>
                {/* Google Tag Manager (noscript) — من index.html الأصلي */}
                <noscript>
                    <iframe
                        src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
                        height="0"
                        width="0"
                        style={{ display: "none", visibility: "hidden" }}
                    />
                </noscript>

                <JsonLd data={[organizationLd(lang), websiteLd(lang)]} />

                <Providers lang={lang}>
                    <AppShell>{children}</AppShell>
                </Providers>

                {/* Google Tag Manager — نفس المقتطف الأصلي */}
                <Script id="gtm" strategy="afterInteractive">
                    {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','${GTM_ID}');`}
                </Script>
            </body>
        </html>
    );
}
