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

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

// ✅ Opcional: email legal/soporte
const LEGAL_EMAIL = process.env.NEXT_PUBLIC_LEGAL_EMAIL || "legal@newsoras.com";

// ✅ Fecha visible (actualizala cuando cambies algo)
const LAST_UPDATED_ISO = process.env.NEXT_PUBLIC_TERMS_LAST_UPDATED || "2026-01-04";

type Copy = {
  title: string;
  subtitle: string;

  metaTitle: string;
  metaDescription: string;

  lastUpdatedLabel: string;

  tocTitle: string;
  toc: { id: string; label: string }[];

  sections: {
    id: string;
    h: string;
    p: string[];
    bullets?: string[];
    note?: string;
  }[];

  contactTitle: string;
  contactP: string;
  contactCta: string;

  footerNote: string;
};

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)}`;
}

function getCopy(locale: Locale): Copy {
  if (locale === "es") {
    return {
      title: "Términos y Condiciones",
      subtitle:
        "Reglas claras para usar Newsoras. Lectura rápida, enfoque en transparencia y responsabilidad.",

      metaTitle: "Términos — Newsoras",
      metaDescription:
        "Términos y condiciones de Newsoras: uso del sitio, contenido editorial, propiedad intelectual, enlaces, limitación de responsabilidad, y contacto legal.",

      lastUpdatedLabel: "Última actualización",

      tocTitle: "Índice",
      toc: [
        { id: "aceptacion", label: "Aceptación" },
        { id: "uso", label: "Uso del sitio" },
        { id: "contenido", label: "Contenido y editorial" },
        { id: "ia", label: "IA y transparencia" },
        { id: "propiedad", label: "Propiedad intelectual" },
        { id: "citas", label: "Citas y uso permitido" },
        { id: "enlaces", label: "Enlaces a terceros" },
        { id: "responsabilidad", label: "Limitación de responsabilidad" },
        { id: "conducta", label: "Conducta prohibida" },
        { id: "cambios", label: "Cambios" },
        { id: "contacto", label: "Contacto" },
      ],

      sections: [
        {
          id: "aceptacion",
          h: "Aceptación",
          p: [
            "Al acceder o usar Newsoras, aceptás estos Términos y nuestra Política de Privacidad.",
            "Si no estás de acuerdo, por favor no uses el sitio.",
          ],
          note:
            "Nota: Esto no es asesoría legal. Ajustá estos términos a tu jurisdicción y al stack real con asesoría profesional si hace falta.",
        },
        {
          id: "uso",
          h: "Uso del sitio",
          p: [
            "Podés navegar y leer el contenido para uso personal y no comercial, salvo acuerdo escrito.",
            "Podemos suspender o limitar acceso si detectamos abuso, automatización maliciosa o ataques a la infraestructura.",
          ],
          bullets: [
            "Uso personal / lectura.",
            "Respeto de medidas de seguridad (anti-bot, rate limits).",
            "No interferir con el funcionamiento del sitio.",
          ],
        },
        {
          id: "contenido",
          h: "Contenido y editorial",
          p: [
            "Newsoras publica noticias, análisis y opinión. Nos esforzamos por la veracidad, pero el contenido puede cambiar (actualizaciones/correcciones) a medida que aparezcan nuevas fuentes.",
            "Cuando un texto es opinión, tratamos de distinguirlo de hechos verificables. Aun así, interpretaciones pueden variar.",
          ],
          bullets: [
            "Hechos: buscamos fuentes confiables y consistencia.",
            "Análisis: escenarios y contexto (puede haber incertidumbre).",
            "Opinión: argumentos editoriales (no equivale a hecho).",
          ],
        },
        {
          id: "ia",
          h: "IA y transparencia",
          p: [
            "Podemos usar herramientas de IA como asistencia editorial (borradores, claridad, consistencia), pero la responsabilidad editorial final es humana.",
            "La IA puede equivocarse. No tratamos a la IA como “fuente”: las fuentes son documentos, datos y reportes citados.",
          ],
          bullets: [
            "La IA no reemplaza verificación.",
            "Si se usan imágenes generadas por IA, deben indicarse como tales.",
            "Las correcciones se priorizan cuando hay evidencia verificable.",
          ],
        },
        {
          id: "propiedad",
          h: "Propiedad intelectual",
          p: [
            "El contenido de Newsoras (texto, diseño, marca, logo) está protegido por derechos de autor y/o marcas.",
            "No podés copiar, republicar o distribuir contenido completo sin permiso, salvo excepciones de cita breve o uso permitido por ley.",
          ],
        },
        {
          id: "citas",
          h: "Citas y uso permitido",
          p: [
            "Podés citar extractos cortos con atribución clara y enlace al artículo original.",
            "Si querés republicar un artículo completo, usarlo comercialmente o entrenar modelos con el contenido, contactanos para permiso.",
          ],
          bullets: [
            "Cita corta + atribución + link.",
            "No “scraping” agresivo ni republicación masiva.",
            "Para licencias o acuerdos: contacto legal.",
          ],
        },
        {
          id: "enlaces",
          h: "Enlaces a terceros",
          p: [
            "Podemos enlazar a sitios externos (fuentes, documentos, redes). No controlamos su contenido ni sus políticas.",
            "No somos responsables por daños derivados del uso de terceros.",
          ],
        },
        {
          id: "responsabilidad",
          h: "Limitación de responsabilidad",
          p: [
            "El contenido se ofrece “tal cual” para información general. No es asesoría financiera, legal o médica.",
            "No garantizamos disponibilidad continua del sitio ni ausencia total de errores.",
          ],
          bullets: [
            "Sin garantías implícitas de exactitud total o disponibilidad 24/7.",
            "No responsabilidad por decisiones tomadas solo en base al contenido.",
            "En algunos países estas limitaciones pueden no aplicar en su totalidad.",
          ],
        },
        {
          id: "conducta",
          h: "Conducta prohibida",
          p: ["No está permitido:"],
          bullets: [
            "Intentar vulnerar seguridad, escanear, explotar o acceder sin autorización.",
            "Automatizar solicitudes de manera que degrade el servicio (bots agresivos, scraping masivo).",
            "Publicar o enviar contenido ilegal, difamatorio o malicioso a través de canales de contacto.",
            "Suplantación de identidad o fraude.",
          ],
        },
        {
          id: "cambios",
          h: "Cambios en estos términos",
          p: [
            "Podemos actualizar estos términos para reflejar cambios del sitio o requisitos legales.",
            "La fecha de “Última actualización” indica el último ajuste.",
          ],
        },
      ],

      contactTitle: "Contacto",
      contactP:
        "Para solicitudes legales, licencias, reportes de abuso o reclamos formales, escribinos.",
      contactCta: "Escribir a legal",

      footerNote:
        "Newsoras — Independencia editorial + herramientas modernas. IA como asistente, no como fuente.",
    };
  }

  if (locale === "zh") {
    return {
      title: "服务条款",
      subtitle: "使用 Newsoras 的规则：清晰、透明、强调责任与安全。",

      metaTitle: "条款 — Newsoras",
      metaDescription:
        "Newsoras 服务条款：网站使用、内容与编辑原则、知识产权、引用规范、第三方链接、责任限制与联系方式。",

      lastUpdatedLabel: "最后更新",

      tocTitle: "目录",
      toc: [
        { id: "aceptacion", label: "接受条款" },
        { id: "uso", label: "网站使用" },
        { id: "contenido", label: "内容与编辑" },
        { id: "ia", label: "AI 使用与透明" },
        { id: "propiedad", label: "知识产权" },
        { id: "citas", label: "引用与允许使用" },
        { id: "enlaces", label: "第三方链接" },
        { id: "responsabilidad", label: "责任限制" },
        { id: "conducta", label: "禁止行为" },
        { id: "cambios", label: "条款变更" },
        { id: "contacto", label: "联系" },
      ],

      sections: [
        {
          id: "aceptacion",
          h: "接受条款",
          p: ["访问或使用 Newsoras 即表示你同意本条款与隐私政策。不同意请停止使用。"],
          note: "说明：本文不构成法律意见。请根据实际司法辖区与部署情况调整。",
        },
        {
          id: "uso",
          h: "网站使用",
          p: ["内容用于个人非商业阅读。若检测到滥用或攻击，可限制访问。"],
        },
        {
          id: "contenido",
          h: "内容与编辑",
          p: ["我们发布新闻、分析与观点。会在新来源出现时更新/更正。观点与事实尽量区分，但解释可能不同。"],
        },
        {
          id: "ia",
          h: "AI 使用与透明",
          p: ["AI 可作为编辑助手，但最终责任由人类承担。AI 不是“来源”，来源是可引用文件与数据。"],
        },
        {
          id: "propiedad",
          h: "知识产权",
          p: ["Newsoras 内容与品牌受版权/商标保护。未经许可不得全文转载或商业使用。"],
        },
        {
          id: "citas",
          h: "引用与允许使用",
          p: ["可短引用并注明出处与链接。全文转载/商业使用/模型训练请联系我们。"],
        },
        {
          id: "enlaces",
          h: "第三方链接",
          p: ["我们可能链接外部网站，但不控制其内容与政策。使用第三方产生的风险由你自行承担。"],
        },
        {
          id: "responsabilidad",
          h: "责任限制",
          p: ["内容仅供一般信息，不构成金融/法律/医疗建议。站点按“现状”提供，不保证永不中断或无错误。"],
        },
        {
          id: "conducta",
          h: "禁止行为",
          p: ["禁止攻击安全、未授权访问、恶意自动化请求、大规模抓取、欺诈与冒充等。"],
        },
        {
          id: "cambios",
          h: "条款变更",
          p: ["我们可能更新条款。页面“最后更新”显示最近修订日期。"],
        },
      ],

      contactTitle: "联系",
      contactP: "法律、许可、滥用报告等，请邮件联系。",
      contactCta: "发送邮件",

      footerNote: "Newsoras — 独立编辑判断 + 现代工具。AI 仅作助手，不作为来源。",
    };
  }

  return {
    title: "Terms",
    subtitle:
      "Clear rules for using Newsoras. Short read, focused on transparency and responsibility.",

    metaTitle: "Terms — Newsoras",
    metaDescription:
      "Newsoras Terms: site usage, editorial content, intellectual property, permitted quoting, third-party links, limitation of liability, and legal contact.",

    lastUpdatedLabel: "Last updated",

    tocTitle: "Contents",
    toc: [
      { id: "aceptacion", label: "Acceptance" },
      { id: "uso", label: "Use of the site" },
      { id: "contenido", label: "Content & editorial" },
      { id: "ia", label: "AI & transparency" },
      { id: "propiedad", label: "Intellectual property" },
      { id: "citas", label: "Quoting & permitted use" },
      { id: "enlaces", label: "Third-party links" },
      { id: "responsabilidad", label: "Limitation of liability" },
      { id: "conducta", label: "Prohibited conduct" },
      { id: "cambios", label: "Changes" },
      { id: "contacto", label: "Contact" },
    ],

    sections: [
      {
        id: "aceptacion",
        h: "Acceptance",
        p: [
          "By accessing or using Newsoras, you agree to these Terms and our Privacy Policy.",
          "If you do not agree, please do not use the site.",
        ],
        note:
          "Note: This is not legal advice. Align terms with your jurisdiction and real stack configuration if you need strict compliance.",
      },
      {
        id: "uso",
        h: "Use of the site",
        p: [
          "You may browse and read content for personal, non-commercial use unless agreed otherwise in writing.",
          "We may limit access if we detect abuse, malicious automation, or attacks on infrastructure.",
        ],
      },
      {
        id: "contenido",
        h: "Content & editorial",
        p: [
          "Newsoras publishes news, analysis, and opinion. We strive for accuracy, but content may be updated or corrected as new sources emerge.",
          "We aim to distinguish opinion from verifiable facts, but interpretations can vary.",
        ],
      },
      {
        id: "ia",
        h: "AI & transparency",
        p: [
          "We may use AI tools as editorial assistance (drafting, clarity, consistency checks), but final responsibility is always human.",
          "AI is not a source. Sources are documents, datasets, and cited reports.",
        ],
      },
      {
        id: "propiedad",
        h: "Intellectual property",
        p: [
          "Newsoras content (text, design, brand, logo) is protected by copyright and/or trademarks.",
          "You may not copy, republish, or distribute full content without permission, except where law allows short quotation.",
        ],
      },
      {
        id: "citas",
        h: "Quoting & permitted use",
        p: [
          "You may quote short excerpts with clear attribution and a link to the original article.",
          "For full republication, commercial use, or model training on our content, contact us for permission.",
        ],
      },
      {
        id: "enlaces",
        h: "Third-party links",
        p: [
          "We may link to third-party sites (sources, documents, social platforms). We do not control their content or policies.",
          "We are not responsible for harm arising from third-party usage.",
        ],
      },
      {
        id: "responsabilidad",
        h: "Limitation of liability",
        p: [
          "Content is provided “as is” for general information and is not financial, legal, or medical advice.",
          "We do not guarantee uninterrupted availability or complete absence of errors.",
        ],
      },
      {
        id: "conducta",
        h: "Prohibited conduct",
        p: ["You must not:"],
        bullets: [
          "Attempt to breach security, scan, exploit, or access without authorization.",
          "Automate requests in a way that degrades service (aggressive bots, bulk scraping).",
          "Submit illegal, defamatory, or malicious content via contact channels.",
          "Impersonate others or commit fraud.",
        ],
      },
      {
        id: "cambios",
        h: "Changes to these terms",
        p: [
          "We may update these terms to reflect changes to the site or legal requirements.",
          "The “Last updated” date indicates the latest revision.",
        ],
      },
    ],

    contactTitle: "Contact",
    contactP: "For legal requests, licensing, abuse reports, or formal claims, contact us.",
    contactCta: "Email legal",

    footerNote:
      "Newsoras — Independent editorial judgment + modern tooling. AI is an assistant, not a source.",
  };
}

// --- 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}/terms`, SITE_URL).toString();

  return {
    title: t.metaTitle,
    description: t.metaDescription,
    alternates: {
      canonical,
      languages: {
        en: new URL(`/en/terms`, SITE_URL).toString(),
        es: new URL(`/es/terms`, SITE_URL).toString(),
        zh: new URL(`/zh/terms`, 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: [
        {
          // ✅ crear: /public/og/terms.png (1200x630)
          url: new URL(`/og/terms.png`, SITE_URL).toString(),
          width: 1200,
          height: 630,
          alt: `${SITE_NAME} — Terms`,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: t.metaTitle,
      description: t.metaDescription,
      images: [new URL(`/og/terms.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: LEGAL_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 jsonLdTermsPage(locale: Locale) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";
  const url = `${SITE_URL}/${locale}/terms`;

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

function jsonLdBreadcrumbs(locale: Locale) {
  const url = `${SITE_URL}/${locale}/terms`;
  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: "Terms", item: url },
    ],
  };
}

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

  const mailtoHref = `mailto:${encodeURIComponent(LEGAL_EMAIL)}?subject=${encodeURIComponent(
    locale === "es" ? "Legal — Newsoras" : locale === "zh" ? "法律 — Newsoras" : "Legal — Newsoras"
  )}`;

  const orgLd = jsonLdOrganization(locale);
  const siteLd = jsonLdWebsite(locale);
  const pageLd = jsonLdTermsPage(locale);
  const crumbsLd = jsonLdBreadcrumbs(locale);

  return (
    <main className="container" style={{ paddingTop: 22, paddingBottom: 30 }}>
      {/* ✅ JSON-LD: Organization + WebSite + WebPage + Breadcrumbs */}
      <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">Usage</span>
            <span className="badge">IP</span>
            <span className="badge">Security</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}/privacy-policy`} className="badge" style={{ padding: "10px 14px" }}>
              {locale === "es" ? "Ver Privacidad" : locale === "zh" ? "查看隐私" : "Privacy Policy"}
            </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>
  );
}

// --- Notes (files + env) ----------------------------------------------------
// 1) /public/og/terms.png (1200x630)
// 2) /public/logo.png     (512x512)
// 3) .env.local:
//    NEXT_PUBLIC_SITE_URL=https://newsoras.com
//    NEXT_PUBLIC_LEGAL_EMAIL=legal@newsoras.com
//    NEXT_PUBLIC_TERMS_LAST_UPDATED=2026-01-04
