import "server-only";
import type { ReactNode } from "react";
import { getLang, t } from "./lang";
import { STATIC_ROUTES, resolveStatic } from "./routes";
import { JsonLd, breadcrumbLd } from "./jsonld";
import { langUrl } from "./metadata";
import { SITE_URL } from "./site";

/** يلفّ صفحة ثابتة: يطبع WebPage + BreadcrumbList بصيغة JSON-LD */
export async function StaticSeo({ path, children }: { path: string; children: ReactNode }) {
    const route = STATIC_ROUTES[path];
    if (!route || route.noindex) return <>{children}</>;

    const lang = await getLang();
    const { title, description } = resolveStatic(path, lang);
    const ld: Record<string, unknown>[] = [
        {
            "@context": "https://schema.org",
            "@type": path.startsWith("/services") ? "Service" : "WebPage",
            name: title,
            url: langUrl(path, lang),
            ...(description ? { description } : {}),
            inLanguage: lang === "ar" ? "ar-SA" : "en-US",
            ...(path.startsWith("/services")
                ? { provider: { "@id": `${SITE_URL}/#organization` }, areaServed: "SA" }
                : { isPartOf: { "@id": `${SITE_URL}/#website` } }),
        },
    ];

    if (path !== "/") {
        // crumbs في السجل مفاتيح ترجمة؛ وإن غابت يُستخدم الجزء الأول من العنوان كما هو
        const items = route.crumbs
            ? route.crumbs.map(([key, p]) => ({ name: t(lang, key), path: p === "" ? undefined : p }))
            : [{ name: title.split(" | ")[0] }];
        ld.push(breadcrumbLd(lang, [{ name: t(lang, "routes.home"), path: "/" }, ...items]));
    }

    return (
        <>
            <JsonLd data={ld} />
            {children}
        </>
    );
}
