// frontend/app/[locale]/privacy-policy/page.tsx
import type { Metadata } from "next";
import Link from "next/link";
import type { Locale } from "@/lib/i18n";
import { isLocale } from "@/lib/i18n";

import type { Copy } from "@/app/[locale]/privacy/copy-types";
import { es } from "@/content/privacy/es";
import { en } from "@/content/privacy/en";
import { zh } from "@/content/privacy/zh";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || "https://newsoras.com";
const SITE_NAME = "Newsoras";

// ✅ Opcional: poné un email real para privacy / legal
const PRIVACY_EMAIL = process.env.NEXT_PUBLIC_PRIVACY_EMAIL || "privacy@newsoras.com";

// ✅ Si querés mantener override por env, lo dejamos.
// Si no lo querés, borrá esta constante y usá t.lastUpdatedISO directo.
const LAST_UPDATED_ISO_ENV = process.env.NEXT_PUBLIC_PRIVACY_LAST_UPDATED || "";

const COPY = { es, en, zh } as const;

function getCopy(locale: Locale): Copy {
  return (COPY as Record<string, Copy>)[locale] ?? COPY.en;
}

function fmtDate(locale: Locale, iso: string) {
  const d = new Date(iso + "T00:00:00Z");
  const y = d.getUTCFullYear();
  const m = d.getUTCMonth() + 1;
  const day = d.getUTCDate();

  const pad = (n: number) => String(n).padStart(2, "0");

  if (locale === "es") return `${pad(day)}/${pad(m)}/${y}`;
  if (locale === "zh") return `${y}-${pad(m)}-${pad(day)}`;
  return `${y}-${pad(m)}-${pad(day)}`;
}

// --- SEO: generateMetadata ---------------------------------------------------
export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale: rawLocale } = await params;
  const locale: Locale = isLocale(rawLocale) ? rawLocale : "en";
  const t = getCopy(locale);

  const canonical = new URL(`/${locale}/privacy-policy`, SITE_URL).toString();

  return {
    title: t.metaTitle,
    description: t.metaDescription,
    alternates: {
      canonical,
      languages: {
        en: new URL(`/en/privacy-policy`, SITE_URL).toString(),
        es: new URL(`/es/privacy-policy`, SITE_URL).toString(),
        zh: new URL(`/zh/privacy-policy`, SITE_URL).toString(),
      },
    },
    openGraph: {
      type: "article",
      url: canonical,
      siteName: SITE_NAME,
      title: t.metaTitle,
      description: t.metaDescription,
      locale: locale === "es" ? "es_ES" : locale === "zh" ? "zh_CN" : "en_US",
      images: [
        {
          url: new URL(`/og/privacy.png`, SITE_URL).toString(),
          width: 1200,
          height: 630,
          alt: `${SITE_NAME} — ${t.title}`,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: t.metaTitle,
      description: t.metaDescription,
      images: [new URL(`/og/privacy.png`, SITE_URL).toString()],
    },
    robots: {
      index: true,
      follow: true,
      googleBot: {
        index: true,
        follow: true,
        "max-image-preview": "large",
        "max-snippet": -1,
        "max-video-preview": -1,
      },
    },
  };
}

// --- JSON-LD ---------------------------------------------------------------
function jsonLdOrganization(locale: Locale) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";

  return {
    "@context": "https://schema.org",
    "@type": "Organization",
    "@id": `${SITE_URL}#organization`,
    name: SITE_NAME,
    url: SITE_URL,
    logo: `${SITE_URL}/logo.png`,
    email: PRIVACY_EMAIL,
    inLanguage,
  };
}

function jsonLdWebsite(locale: Locale) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";
  return {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "@id": `${SITE_URL}#website`,
    url: SITE_URL,
    name: SITE_NAME,
    publisher: { "@id": `${SITE_URL}#organization` },
    inLanguage,
  };
}

function jsonLdPrivacyPage(locale: Locale, title: string) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";
  const url = `${SITE_URL}/${locale}/privacy-policy`;

  return {
    "@context": "https://schema.org",
    "@type": "WebPage",
    "@id": `${url}#webpage`,
    url,
    name: `${SITE_NAME} — ${title}`,
    isPartOf: { "@id": `${SITE_URL}#website` },
    about: { "@id": `${SITE_URL}#organization` },
    inLanguage,
  };
}

function jsonLdBreadcrumbs(locale: Locale, title: string) {
  const url = `${SITE_URL}/${locale}/privacy-policy`;
  const home = `${SITE_URL}/${locale}`;

  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: home },
      { "@type": "ListItem", position: 2, name: title, item: url },
    ],
  };
}

// --- Page -------------------------------------------------------------------
export default async function PrivacyPolicyPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: rawLocale } = await params;
  const locale: Locale = isLocale(rawLocale) ? rawLocale : "en";
  const t = getCopy(locale);

  // Prioridad: env override (si existe) > t.lastUpdatedISO
  const lastUpdatedISO = (LAST_UPDATED_ISO_ENV || t.lastUpdatedISO || "2026-01-04").trim();
  const lastUpdated = fmtDate(locale, lastUpdatedISO);

  // ✅ Anti-injection en mailto (bien hecho)
  const mailtoHref = `mailto:${encodeURIComponent(PRIVACY_EMAIL)}?subject=${encodeURIComponent(
    locale === "es" ? "Privacidad — Newsoras" : locale === "zh" ? "隐私 — Newsoras" : "Privacy — Newsoras"
  )}`;

  const orgLd = jsonLdOrganization(locale);
  const siteLd = jsonLdWebsite(locale);
  const pageLd = jsonLdPrivacyPage(locale, t.title);
  const crumbsLd = jsonLdBreadcrumbs(locale, t.title);

  return (
    <main className="container" style={{ paddingTop: 22, paddingBottom: 30 }}>
      {/* ✅ JSON-LD */}
      <script
        type="application/ld+json"
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: JSON.stringify(orgLd) }}
      />
      <script
        type="application/ld+json"
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: JSON.stringify(siteLd) }}
      />
      <script
        type="application/ld+json"
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: JSON.stringify(pageLd) }}
      />
      <script
        type="application/ld+json"
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: JSON.stringify(crumbsLd) }}
      />

      {/* Hero */}
      <section className="card" style={{ position: "relative", overflow: "hidden", padding: 22 }}>
        <div
          aria-hidden
          style={{
            position: "absolute",
            inset: -60,
            background:
              "radial-gradient(600px 220px at 20% 0%, var(--accent-glow), transparent 70%), radial-gradient(500px 220px at 80% 20%, rgba(37, 99, 235, 0.25), transparent 70%)",
            filter: "blur(8px)",
            opacity: 0.9,
          }}
        />

        <div style={{ position: "relative" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
            <div
              style={{
                width: 44,
                height: 44,
                borderRadius: 12,
                background: "linear-gradient(135deg, var(--accent), #2563eb)",
                boxShadow: "0 0 18px var(--accent-glow)",
              }}
            />
            <div>
              <h1 className="h1" style={{ margin: 0 }}>
                {t.title}
              </h1>
              <p className="p" style={{ margin: "6px 0 0 0", color: "var(--text-secondary)" }}>
                {t.subtitle}
              </p>
            </div>
          </div>

          <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginTop: 10 }}>
            <span className="badge" style={{ borderColor: "var(--text-muted)" }}>
              {t.lastUpdatedLabel}: {lastUpdated}
            </span>
            <span className="badge">Data</span>
            <span className="badge">Security</span>
            <span className="badge">Transparency</span>
          </div>
        </div>
      </section>

      {/* TOC */}
      <section className="card" style={{ padding: 20, marginTop: 18 }}>
        <h2 className="h2" style={{ marginBottom: 12 }}>
          {t.tocTitle}
        </h2>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          {t.toc.map((x) => (
            <a key={x.id} href={`#${x.id}`} className="badge" style={{ borderColor: "var(--text-muted)" }}>
              {x.label}
            </a>
          ))}
        </div>
      </section>

      {/* Content */}
      <section style={{ display: "grid", gridTemplateColumns: "1fr", gap: 18, marginTop: 18 }}>
        {t.sections.map((s) => (
          <article key={s.id} id={s.id} className="card" style={{ padding: 20 }}>
            <h2 className="h2" style={{ marginBottom: 10 }}>
              {s.h}
            </h2>

            {s.p.map((p) => (
              <p key={p} className="p" style={{ color: "var(--text-secondary)", marginTop: 10 }}>
                {p}
              </p>
            ))}

            {s.bullets?.length ? (
              <ul style={{ marginTop: 12, paddingLeft: 18, color: "var(--text-secondary)", lineHeight: 1.75 }}>
                {s.bullets.map((b) => (
                  <li key={b}>{b}</li>
                ))}
              </ul>
            ) : null}

            {s.note ? (
              <div
                style={{
                  marginTop: 14,
                  padding: 14,
                  borderRadius: 16,
                  border: "1px dashed var(--line)",
                  background: "rgba(255,255,255,0.02)",
                  color: "var(--text-secondary)",
                  fontSize: 13,
                  lineHeight: 1.6,
                }}
              >
                <strong style={{ color: "var(--text-primary)" }}>
                  {locale === "es" ? "Nota:" : locale === "zh" ? "说明：" : "Note:"}
                </strong>{" "}
                {s.note}
              </div>
            ) : null}
          </article>
        ))}

        {/* Contact */}
        <div className="card" style={{ padding: 20 }} id="contacto">
          <h2 className="h2" style={{ marginBottom: 8 }}>
            {t.contactTitle}
          </h2>
          <p className="p" style={{ marginTop: 8, color: "var(--text-secondary)" }}>
            {t.contactP}
          </p>

          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 12 }}>
            <a href={mailtoHref} className="badge" style={{ padding: "10px 14px", borderColor: "var(--text-muted)" }}>
              {t.contactCta}
            </a>
            <Link href={`/${locale}/contact`} className="badge" style={{ padding: "10px 14px" }}>
              {locale === "es" ? "Ir a Contacto" : locale === "zh" ? "前往联系页" : "Go to Contact"}
            </Link>
            <Link href={`/${locale}`} className="badge" style={{ padding: "10px 14px" }}>
              Home
            </Link>
          </div>

          <div style={{ marginTop: 14, color: "var(--text-muted)", fontSize: 12 }}>
            {t.footerNote}
          </div>
        </div>
      </section>
    </main>
  );
}
