import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { ContactForm } from "@/components/ContactForm";
import { CTASection } from "@/components/CTASection";
import { FounderGrid } from "@/components/FounderGrid";
import { GrowthSystem } from "@/components/GrowthSystem";
import { ProcessTimeline } from "@/components/ProcessTimeline";
import { SolutionsGrid } from "@/components/SolutionsGrid";
import { WorkGrid } from "@/components/WorkGrid";
import { sectionLabels } from "@/content/pageContent";
import { brand, isLocale, isPageSlug, locales, pageSlugs, pillars, solutions, type Locale, type PageSlug } from "@/content/site";
import { translations } from "@/content/translations";

export function generateStaticParams() {
  return locales.flatMap((locale) => pageSlugs.map((page) => ({ locale, page })));
}

const pageTitles: Record<PageSlug, Record<Locale, string>> = {
  "growth-system": { fr: "Le système de croissance Yashal", en: "The Yashal Growth System", ar: "نظام Yashal للنمو" },
  solutions: { fr: "Solutions de croissance", en: "Growth solutions", ar: "حلول النمو" },
  work: { fr: "Travaux sélectionnés", en: "Selected Work", ar: "أعمال مختارة" },
  about: { fr: "À propos", en: "About", ar: "من نحن" },
  contact: { fr: "Contact", en: "Contact", ar: "تواصل معنا" },
  privacy: { fr: "Politique de confidentialité", en: "Privacy policy", ar: "سياسة الخصوصية" },
  legal: { fr: "Mentions légales", en: "Legal notice", ar: "الإشعار القانوني" },
};

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; page: string }>;
}): Promise<Metadata> {
  const values = await params;
  if (!isLocale(values.locale) || !isPageSlug(values.page)) return {};
  const locale = values.locale;
  const page = values.page;
  const noIndex = page === "legal" || page === "privacy";
  return {
    title: pageTitles[page][locale],
    description: translations[locale].pages[page].intro,
    alternates: {
      canonical: `/${locale}/${page}/`,
      languages: {
        fr: `/fr/${page}/`,
        en: `/en/${page}/`,
        ar: `/ar/${page}/`,
        "x-default": `/fr/${page}/`,
      },
    },
    robots: noIndex ? { index: false, follow: true } : undefined,
    openGraph: {
      title: pageTitles[page][locale],
      description: translations[locale].pages[page].intro,
      url: `/${locale}/${page}/`,
      images: [{ url: "/social/yashal-og.png", width: 1200, height: 630 }],
    },
    twitter: {
      card: "summary_large_image",
      title: pageTitles[page][locale],
      description: translations[locale].pages[page].intro,
      images: ["/social/yashal-og.png"],
    },
  };
}

export default async function StandardPage({
  params,
}: {
  params: Promise<{ locale: string; page: string }>;
}) {
  const values = await params;
  if (!isLocale(values.locale) || !isPageSlug(values.page)) notFound();
  const locale = values.locale;
  const page = values.page;
  const t = translations[locale];
  const p = t.pages[page];
  const labels = sectionLabels[locale];
  const local = {
    fr: {
      measure: "Mesure et apprentissage",
      connectedSystem: "Un système connecté",
      aiNote:
        "L’intelligence artificielle peut améliorer l’analyse et l’exécution. Elle reste une capacité transversale, pas une huitième solution.",
      workNote:
        "Cinq projets vidéo réels révèlent l’étendue des contextes, des formats et des intentions créatives.",
      beliefs: "Nos convictions",
      founders: "Les fondateurs",
      positioning: "Notre position",
      positioningTitle: "Un partenaire de croissance, pas une agence traditionnelle.",
      positioningText:
        "Les capacités créatives, digitales et marketing sont des moyens. La finalité est de construire des systèmes et des actifs qui renforcent l’entreprise.",
      location: "Fès, Maroc",
    },
    en: {
      measure: "Measurement and learning",
      connectedSystem: "One connected system",
      aiNote:
        "Artificial intelligence can improve analysis and execution. It remains a cross-functional capability, not an eighth solution.",
      workNote:
        "Five real video projects reveal the range of contexts, formats and creative intentions.",
      beliefs: "Our beliefs",
      founders: "The founders",
      positioning: "Our position",
      positioningTitle: "A Growth Partner, not a traditional agency.",
      positioningText:
        "Creative, digital and marketing capabilities are means. The purpose is to build systems and assets that strengthen the business.",
      location: "Fès, Morocco",
    },
    ar: {
      measure: "القياس والتعلّم",
      connectedSystem: "نظام واحد مترابط",
      aiNote:
        "يمكن للذكاء الاصطناعي تحسين التحليل والتنفيذ، لكنه يظل قدرة مشتركة وليس حلاً ثامناً.",
      workNote:
        "تكشف خمسة مشاريع فيديو حقيقية تنوّع السياقات والصيغ والغايات الإبداعية.",
      beliefs: "قناعاتنا",
      founders: "المؤسسون",
      positioning: "موقعنا",
      positioningTitle: "شريك نمو، ولسنا وكالة تقليدية.",
      positioningText:
        "القدرات الإبداعية والرقمية والتسويقية وسائل. أما الغاية فهي بناء أنظمة وأصول تقوّي الشركة.",
      location: "فاس، المغرب",
    },
  }[locale];

  const content = (() => {
    switch (page) {
      case "growth-system":
        return (
          <>
            <section className="section shell">
              <div className="editorial-block">
                <span>01</span><div><h2>{p.isolatedTitle}</h2><p>{p.isolatedText}</p></div>
              </div>
              <GrowthSystem locale={locale} />
            </section>
            <section className="principle-section">
              <div className="shell two-column-copy">
                <div><p className="kicker">{labels.diagnosis}</p><h2>{p.constraintsTitle}</h2></div>
                <p>{p.constraintsText}</p>
              </div>
            </section>
            <ProcessTimeline locale={locale} title={t.home.methodTitle} />
            <section className="section shell">
              <div className="two-column-copy">
                <div><p className="kicker">{local.measure}</p><h2>{p.measureTitle}</h2></div>
                <p>{p.measureText}</p>
              </div>
              <div className="connection-list">
                {solutions.map((solution, index) => (
                  <div key={solution}><span>{String(index + 1).padStart(2, "0")}</span><strong>{t.solutions[solution].name}</strong><small>{t.pillars[pillars[index % pillars.length]].name}</small></div>
                ))}
              </div>
            </section>
          </>
        );
      case "solutions":
        return (
          <section className="section shell">
            <SolutionsGrid locale={locale} />
            <div className="section-note">
              <p className="kicker">{local.connectedSystem}</p>
              <p>{local.aiNote}</p>
            </div>
          </section>
        );
      case "work":
        return (
          <>
            <section className="section shell">
              <div className="work-readiness">
                <div className="readiness-visual" aria-hidden="true">
                  <span>Y</span><i /><b />
                </div>
                <div data-reveal><p className="kicker">{labels.publicationStandard}</p><h2>{p.readyTitle}</h2><p>{p.readyText}</p></div>
              </div>
              <div className="section-heading" data-reveal>
                <div><p className="kicker">{t.common.selectedWork}</p><h2>{p.categoriesTitle}</h2></div>
                <p>{local.workNote}</p>
              </div>
              <WorkGrid locale={locale} />
            </section>
          </>
        );
      case "about":
        return (
          <>
            <section className="section shell">
              <div className="two-column-copy">
                <div><p className="kicker">{local.positioning}</p><h2>{local.positioningTitle}</h2></div>
                <p>{local.positioningText}</p>
              </div>
            </section>
            <section className="principle-section">
              <div className="shell two-column-copy">
                <div><p className="kicker">{local.beliefs}</p><h2>{p.beliefsTitle}</h2></div>
                <p>{p.beliefsText}</p>
              </div>
            </section>
            <section className="founders-section">
              <div className="shell">
                <div className="section-heading"><div><p className="kicker">{local.founders}</p><h2>{p.foundersTitle}</h2></div></div>
                <FounderGrid locale={locale} />
              </div>
            </section>
            <section className="section shell"><blockquote>{p.moroccoTitle}</blockquote></section>
            <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({
              "@context": "https://schema.org",
              "@graph": [
                { "@type": "Person", name: "Yassine El Belloute", jobTitle: "Co-Founder & Growth Director", worksFor: { "@type": "Organization", name: brand.name } },
                { "@type": "Person", name: "Abderrahmane Haloui", jobTitle: "Co-Founder & Creative Production Director", worksFor: { "@type": "Organization", name: brand.name } },
                { "@type": "Person", name: "Dr Oussama Benchekroun", jobTitle: "Co-Founder & Strategic Advisor", worksFor: { "@type": "Organization", name: brand.name } },
              ],
            }) }} />
          </>
        );
      case "contact": {
        const message = locale === "fr" ? "Bonjour Yashal Studios, je souhaite commencer une conversation au sujet de mon activité." : locale === "ar" ? "مرحباً Yashal Studios، أود أن أبدأ محادثة حول نشاطي." : "Hello Yashal Studios, I would like to start a conversation about my business.";
        return (
          <>
            <section className="contact-choice shell">
              <div className="form-panel"><ContactForm locale={locale} /></div>
              <aside>
                <p className="kicker">WhatsApp</p>
                <h2>{t.common.whatsapp}</h2>
                <p>{locale === "fr" ? "Pour une conversation directe, utilisez le message préparé et complétez-le avec votre contexte." : locale === "ar" ? "للمحادثة المباشرة، استخدم الرسالة المعدة وأضف سياقك." : "For a direct conversation, use the prepared message and add your context."}</p>
                <a className="button button-light" href={`https://wa.me/${brand.phoneHref.replace("+", "")}?text=${encodeURIComponent(message)}`}>{t.common.whatsapp}</a>
                <div className="contact-details"><a href={`mailto:${brand.email}`}>{brand.email}</a><a href={`tel:${brand.phoneHref}`} dir="ltr">{brand.phone}</a><span>{local.location}</span></div>
              </aside>
            </section>
            <section className="section shell"><div className="two-column-copy"><h2>{p.processTitle}</h2><p>{p.processText}</p></div></section>
          </>
        );
      }
      case "privacy":
      case "legal":
        return (
          <section className="section shell legal-content">
            <div className="legal-alert"><strong>{t.common.legalReview}</strong><p>{t.common.legalReviewText}</p></div>
            <div><h2>{page === "privacy" ? p.dataTitle : p.knownTitle}</h2><p>{page === "privacy" ? p.dataText : p.knownText}</p></div>
            <div><h2>{page === "privacy" ? p.securityTitle : p.missingTitle}</h2><p>{page === "privacy" ? p.securityText : p.missingText}</p></div>
            {page === "privacy" && <div><h2>{p.rightsTitle}</h2><p>{p.rightsText}</p></div>}
          </section>
        );
    }
  })();

  const showCta = !["contact", "privacy", "legal"].includes(page);
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: t.nav.home,
        item: `https://${brand.domain}/${locale}/`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: pageTitles[page][locale],
        item: `https://${brand.domain}/${locale}/${page}/`,
      },
    ],
  };
  return (
    <main id="main">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />
      <header className="page-hero shell" data-reveal>
        <Breadcrumbs locale={locale} current={pageTitles[page][locale]} />
        <p className="kicker">{t.common.eyebrow}</p>
        <h1>{p.title}</h1>
        <p>{p.intro}</p>
        {page === "growth-system" && <Link className="text-link" href={`/${locale}/solutions/`}>{t.nav.solutions}</Link>}
      </header>
      {content}
      {showCta && <div className="shell"><CTASection locale={locale} /></div>}
    </main>
  );
}
