import "server-only";
import type { Metadata } from "next";
import type { Lang } from "@/config/constants";
import { buildMetadata } from "./metadata";
import { getLang, t as translate } from "./lang";

type T = (key: string) => string;
type Bi = { ar: string; en: string };

export type StaticRouteSeo = {
    /** العنوان — منقول حرفياً من مكوّن PageTitles في App.tsx الأصلي */
    title: (t: T) => string;
    description?: Bi | ((t: T) => string);
    keywords?: { ar: string[]; en: string[] };
    noindex?: boolean;
    /** يُضمَّن في sitemap.xml */
    sitemap?: { priority: number; changeFrequency: "daily" | "weekly" | "monthly" | "yearly" };
    /** مسار التنقل (Breadcrumb) لـ JSON-LD: [مفتاح الترجمة، المسار] */
    crumbs?: Array<[string, string]>;
};

const ivory = (t: T) => t("ivory");
const svc = (key: string, navKey: string, priority = 0.8): StaticRouteSeo => ({
    title: (t) => `${t(`routes.${key}`)} | ${t("routes.services")}`,
    description: (t) => t(`nav.${navKey}`),
    sitemap: { priority, changeFrequency: "monthly" },
    crumbs: [["routes.services", "/services/training"], [`routes.${key}`, ""]],
});
const diploma = (key: string): StaticRouteSeo => ({
    title: (t) => `${t(`routes.${key}`)} | ${t("routes.diploma")}`,
    description: {
        ar: "دبلوم مهني من ايفوري للتدريب والاستشارات بمحتوى تطبيقي معتمد يؤهلك لسوق العمل — تعرّف على المحاور والمدة وآلية التسجيل.",
        en: "A professional diploma by IVORY Training & Consulting with accredited, practical content that prepares you for the job market — modules, duration and enrollment.",
    },
    sitemap: { priority: 0.8, changeFrequency: "monthly" },
    crumbs: [["routes.diploma", "/ivory-diploma"], [`routes.${key}`, ""]],
});
const level = (titleKey: string): StaticRouteSeo => ({
    title: (t) => `${t(titleKey)} | ${t("routes.leadership-solutions")} | ${t("routes.products")}`,
    description: (t) => t("nav.leadership-solutions"),
    sitemap: { priority: 0.7, changeFrequency: "monthly" },
    crumbs: [["routes.leadership-solutions", "/services/leadership-solutions"], [titleKey, ""]],
});
const priv: StaticRouteSeo["noindex"] = true;

/**
 * سجل SEO للصفحات الثابتة. المفتاح هو مسار Next.js.
 * الأوصاف الجديدة (حيث لا يوجد نص معتمد في ملفات الترجمة) قابلة للمراجعة والتعديل هنا.
 */
export const STATIC_ROUTES: Record<string, StaticRouteSeo> = {
    "/": {
        title: (t) => `${t("routes.home")} | ${ivory(t)}`,
        sitemap: { priority: 1, changeFrequency: "daily" },
    },
    "/about": {
        title: (t) => `${t("routes.about")} | ${ivory(t)}`,
        description: {
            ar: "تعرّف على ايفوري للتدريب والاستشارات منذ 2012: رؤيتنا وقيمنا ولماذا تختارنا المنظمات الحكومية والخاصة شريكاً في تطوير الكفاءات.",
            en: "Meet IVORY Training & Consulting, since 2012: our vision, values and why public and private organizations choose us to develop their talent.",
        },
        sitemap: { priority: 0.8, changeFrequency: "monthly" },
    },
    "/contact-us": {
        title: (t) => `${t("routes.contact-us")} | ${ivory(t)}`,
        description: {
            ar: "تواصل مع ايفوري للتدريب والاستشارات في الرياض: الهاتف والبريد ونموذج المراسلة لطلب برنامج تدريبي أو استشارة.",
            en: "Contact IVORY Training & Consulting in Riyadh: phone, email and inquiry form to request a training program or consultation.",
        },
        sitemap: { priority: 0.7, changeFrequency: "yearly" },
    },
    "/privacy-policy": {
        title: (t) => `${t("routes.privacy-policy")} | ${ivory(t)}`,
        sitemap: { priority: 0.3, changeFrequency: "yearly" },
    },
    "/training-courses": {
        title: (t) => `${t("routes.training-courses")} | ${ivory(t)}`,
        description: {
            ar: "تصفّح البرامج التدريبية من ايفوري حسب المدينة والمجال والتاريخ — حضورياً وعن بُعد، مع التسجيل والدفع الإلكتروني.",
            en: "Browse IVORY training programs by city, field and date — in-person and online, with online registration and payment.",
        },
        keywords: { ar: ["دورات تدريبية في الرياض", "دورات معتمدة"], en: ["training courses Riyadh", "accredited courses"] },
        sitemap: { priority: 0.9, changeFrequency: "daily" },
    },
    "/training-plans": {
        title: (t) => `${t("routes.training-plan")} | ${ivory(t)}`,
        description: {
            ar: "الخطط التدريبية من ايفوري مصنّفة حسب المجالات والموضوعات لتخطيط تطوير فرق العمل على مدار العام.",
            en: "IVORY training plans organized by field and subject to plan your team development throughout the year.",
        },
        sitemap: { priority: 0.8, changeFrequency: "weekly" },
    },
    "/blogs": {
        title: (t) => `${t("routes.blogs")} | ${ivory(t)}`,
        description: {
            ar: "مدونة ايفوري: مقالات في القيادة والموارد البشرية والتدريب والتطوير المؤسسي.",
            en: "IVORY blog: articles on leadership, HR, training and organizational development.",
        },
        sitemap: { priority: 0.7, changeFrequency: "weekly" },
    },
    "/news": {
        title: (t) => `${t("routes.news")} | ${ivory(t)}`,
        description: { ar: "آخر أخبار ايفوري للتدريب والاستشارات وشراكاتها وفعالياتها.", en: "The latest news, partnerships and events from IVORY Training & Consulting." },
        sitemap: { priority: 0.7, changeFrequency: "daily" },
    },
    "/podcasts": {
        title: (t) => `${t("routes.podcasts")} | ${ivory(t)}`,
        description: { ar: "بودكاست ايفوري: حلقات مسموعة ومرئية في الإدارة والقيادة وتطوير الذات.", en: "IVORY podcast: audio and video episodes on management, leadership and self-development." },
        sitemap: { priority: 0.6, changeFrequency: "weekly" },
    },
    "/seminars": {
        title: (t) => `${t("routes.seminars")} | ${ivory(t)}`,
        description: { ar: "الفعاليات والندوات العامة من ايفوري — مواعيدها وتفاصيلها والتسجيل فيها.", en: "IVORY public events and seminars — dates, details and registration." },
        sitemap: { priority: 0.7, changeFrequency: "weekly" },
    },
    "/offers": {
        title: (t) => `${t("routes.offers")} | ${ivory(t)}`,
        description: { ar: "عروض ايفوري على البرامج التدريبية والباقات لفترة محدودة.", en: "Limited-time IVORY offers on training programs and bundles." },
        sitemap: { priority: 0.7, changeFrequency: "weekly" },
    },
    "/accreditations": {
        title: (t) => `${t("routes.accreditations")} | ${ivory(t)}`,
        description: { ar: "الاعتمادات والشراكات الدولية والمحلية لبرامج ايفوري التدريبية.", en: "International and local accreditations and partnerships behind IVORY training programs." },
        sitemap: { priority: 0.7, changeFrequency: "monthly" },
    },
    "/achievements": {
        title: (t) => `${t("routes.achievements")} | ${ivory(t)}`,
        description: { ar: "إنجازات ايفوري ومشاريعها مع الجهات الحكومية والخاصة.", en: "IVORY achievements and projects with public and private organizations." },
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/certificate-verification": {
        title: (t) => `${t("routes.certificate-verification")} | ${ivory(t)}`,
        description: { ar: "تحقّق من صحة شهادات ايفوري التدريبية برقم الشهادة.", en: "Verify the authenticity of IVORY training certificates by certificate number." },
        sitemap: { priority: 0.5, changeFrequency: "yearly" },
    },
    "/contractural": {
        title: (t) => `${t("routes.contractural")} | ${ivory(t)}`,
        description: { ar: "اطلب دورة تعاقدية مصممة لمنظمتك — حدّد الموضوع والعدد والموقع وسنعود إليك بعرض.", en: "Request a contractual course tailored to your organization — topic, headcount and location." },
        sitemap: { priority: 0.7, changeFrequency: "yearly" },
    },
    "/ivory-pro": {
        title: (t) => `Ivory PRO | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/ivory-diploma": {
        title: (t) => `${t("routes.diploma")} | ${ivory(t)}`,
        description: diploma("diploma").description,
        sitemap: { priority: 0.9, changeFrequency: "monthly" },
    },
    "/ivory-diploma/cyber-security": diploma("cyber"),
    "/ivory-diploma/ai": diploma("ai"),
    "/ivory-diploma/executive-management": diploma("executive-management"),
    "/ivory-diploma/hr": diploma("hr"),
    "/ivory-diploma/logistics-management": diploma("logistics-management"),

    "/services/training": svc("training", "training"),
    "/services/evaluations": svc("evaluations", "evaluations"),
    "/services/coaching": svc("coaching", "coaching"),
    "/services/training-platforms": svc("platforms", "platforms"),
    "/services/training-kits": svc("training-kits", "training-kits"),
    "/services/consulting": svc("consulting", "consulting"),
    "/services/learning-solutions": svc("learning-solutions", "learning-solutions"),
    "/services/third-sector": svc("third-sector", "third-sector"),
    "/services/leadership-solutions": svc("leadership-solutions", "leadership-solutions", 0.9),
    "/services/leadership-solutions/level-1": level("level_1.level_1"),
    "/services/leadership-solutions/level-2": level("secondLevel"),
    "/services/leadership-solutions/level-3": level("levelThree"),
    "/services/leadership-solutions/level-4": level("levelFour"),

    "/products/cmi": {
        title: (t) => `${t("routes.cmi")} | ${t("routes.products")}`,
        sitemap: { priority: 0.8, changeFrequency: "monthly" },
    },
    "/excelcx": {
        title: (t) => `${t("routes.excelcx")} | ${t("routes.products")}`,
        sitemap: { priority: 0.7, changeFrequency: "monthly" },
    },
    "/ivory-event-profile": {
        title: (t) => `${t("routes.ivory-event-profile")} | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/supply-chain": {
        title: (t) => `${t("routes.supply-chain")} | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/team-building-activities": {
        title: (t) => `${t("routes.TeamBuildingActivities")} | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/diploma-registration": {
        title: (t) => `${t("diploma_form.title")} | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/form": { title: (t) => `${t("routes.form")} | ${ivory(t)}`, sitemap: { priority: 0.4, changeFrequency: "yearly" } },
    "/compliance_training": {
        title: (t) => `${t("routes.compliance")} | ${ivory(t)}`,
        sitemap: { priority: 0.6, changeFrequency: "monthly" },
    },
    "/atd25": { title: (t) => `${t("routes.atd25")} | ${ivory(t)}`, sitemap: { priority: 0.5, changeFrequency: "monthly" } },

    // صفحات خاصة — لا تُفهرس ولا تدخل sitemap
    "/login": { title: (t) => `${t("routes.login")} | ${ivory(t)}`, noindex: priv },
    "/forget-password": { title: () => "ايفوري | Ivory", noindex: priv },
    "/otp-code": { title: (t) => `${t("routes.otp")} | ${ivory(t)}`, noindex: priv },
    "/reset-password": { title: (t) => `${t("routes.reset-password")} | ${ivory(t)}`, noindex: priv },
    "/profile": { title: (t) => `${t("routes.profile")} | ${ivory(t)}`, noindex: priv },
    "/bot": { title: (t) => `${t("routes.home")} | ${ivory(t)}`, noindex: priv },
    "/courses/payment/success": { title: (t) => `${t("routes.payment-success")} | ${ivory(t)}`, noindex: priv },
    "/courses/payment/failed": { title: (t) => `${t("routes.payment-failed")} | ${ivory(t)}`, noindex: priv },
};

export function resolveStatic(path: string, lang: Lang) {
    const route = STATIC_ROUTES[path];
    const t: T = (k) => translate(lang, k);
    if (!route) return { title: "ايفوري | Ivory", t };
    const description = typeof route.description === "function" ? route.description(t) : route.description?.[lang];
    return { route, t, title: route.title(t), description, keywords: route.keywords?.[lang] };
}

/** للاستخدام المباشر في page.tsx:  export const generateMetadata = staticMetadata("/about") */
export function staticMetadata(path: string) {
    return async function generateMetadata(): Promise<Metadata> {
        const lang = await getLang();
        const { route, title, description, keywords } = resolveStatic(path, lang);
        return buildMetadata({ lang, path, title, description, keywords, noindex: route?.noindex });
    };
}
