// frontend/app/[locale]/contact/page.tsx

// Agregar:
// /api/contact (POST)
// rate limit
// Turnstile
// validación estricta
// logging

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";

// ✅ Podés sobreescribir por env en prod si querés
const CONTACT_EMAIL = process.env.NEXT_PUBLIC_CONTACT_EMAIL || "contact@newsoras.com";
const CONTACT_TELEGRAM = process.env.NEXT_PUBLIC_CONTACT_TELEGRAM || ""; // ej: "https://t.me/newsoras"
const CONTACT_X = process.env.NEXT_PUBLIC_CONTACT_X || ""; // ej: "https://x.com/newsoras"

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

  metaTitle: string;
  metaDescription: string;

  quickTitle: string;
  quickEmailLabel: string;
  quickEmailHint: string;
  quickTelegramLabel: string;
  quickTelegramHint: string;
  quickXLabel: string;
  quickXHint: string;

  formTitle: string;
  formIntro: string;
  formName: string;
  formEmail: string;
  formTopic: string;
  formTopicTip: string;
  formMessage: string;
  formSend: string;
  formPrivacy: string;

  topics: { value: string; label: string }[];

  correctionsTitle: string;
  correctionsP: string;
  correctionsBullets: string[];

  collabTitle: string;
  collabP: string;
  collabBullets: string[];

  footerNote: string;
};

function getCopy(locale: Locale): Copy {
  if (locale === "es") {
    return {
      title: "Contacto",
      subtitle:
        "Sugerencias, correcciones, colaboraciones y feedback. Respondemos con criterio y respeto.",

      metaTitle: "Contacto — Newsoras",
      metaDescription:
        "Contactá a Newsoras para sugerir temas, reportar errores, solicitar correcciones o proponer colaboraciones. Periodismo independiente con asistencia de IA.",

      quickTitle: "Vías rápidas",
      quickEmailLabel: "Email",
      quickEmailHint: "La vía más confiable para correcciones y solicitudes formales.",
      quickTelegramLabel: "Telegram",
      quickTelegramHint: "Ideal para tips rápidos o seguimiento.",
      quickXLabel: "X",
      quickXHint: "Para avisos públicos y discusiones abiertas.",

      formTitle: "Escribinos",
      formIntro:
        "Usá este formulario para enviarnos un mensaje. Si preferís, también podés escribir directo por email.",
      formName: "Nombre (opcional)",
      formEmail: "Email (opcional)",
      formTopic: "Motivo",
      formTopicTip:
        "Elegí el motivo para que tu mensaje llegue más rápido al lugar correcto.",
      formMessage: "Mensaje",
      formSend: "Enviar",
      formPrivacy:
        "Privacidad: no publicamos tu email. Usamos la información solo para responder y mejorar el contenido.",

      topics: [
        { value: "correccion", label: "Corrección / Error factual" },
        { value: "sugerencia", label: "Sugerencia de tema" },
        { value: "colaboracion", label: "Colaboración / Prensa" },
        { value: "legal", label: "Derechos de autor / Reclamo" },
        { value: "otro", label: "Otro" },
      ],

      correctionsTitle: "Correcciones (lo tomamos en serio)",
      correctionsP:
        "Si detectás un error factual, ayudanos con contexto verificable. En Newsoras priorizamos la veracidad: corregimos rápido y dejamos registro cuando corresponde.",
      correctionsBullets: [
        "Incluí el link del artículo y el párrafo específico.",
        "Compartí la fuente primaria (documento, comunicado, dataset, etc.).",
        "Si es una fecha/número/nombre, indicá el dato correcto y por qué.",
      ],

      collabTitle: "Colaboraciones",
      collabP:
        "Nos interesan colaboraciones que sumen valor real: análisis, datos, verificación, entrevistas y cobertura especializada.",
      collabBullets: [
        "Pitch breve: tema, enfoque y por qué ahora.",
        "Tu experiencia (sin exagerar) y links a trabajos previos.",
        "Qué aportás: datos, acceso a fuentes, investigación o perspectiva.",
      ],

      footerNote:
        "Newsoras — S.O.R.A.S.: Source-Oriented, Real-time Analysis System. Hechos verificables + análisis con criterio.",
    };
  }

  if (locale === "zh") {
    return {
      title: "联系",
      subtitle: "线索、勘误、合作与反馈。我们重视基于证据的沟通。",

      metaTitle: "联系 — Newsoras",
      metaDescription:
        "联系 Newsoras：提供选题建议、反馈错误、提交更正或提出合作。独立新闻与 AI 辅助分析。",

      quickTitle: "快速联系",
      quickEmailLabel: "邮箱",
      quickEmailHint: "更正与正式请求的最佳渠道。",
      quickTelegramLabel: "Telegram",
      quickTelegramHint: "适合快速线索与跟进。",
      quickXLabel: "X",
      quickXHint: "公开讨论与通知。",

      formTitle: "给我们留言",
      formIntro:
        "可使用此表单发送消息；也可以直接发邮件联系我们。",
      formName: "姓名（可选）",
      formEmail: "邮箱（可选）",
      formTopic: "主题",
      formTopicTip: "选择主题以便更快处理。",
      formMessage: "内容",
      formSend: "发送",
      formPrivacy: "隐私：我们不会公开你的邮箱，仅用于回复与改进内容。",

      topics: [
        { value: "correccion", label: "更正 / 事实错误" },
        { value: "sugerencia", label: "选题建议" },
        { value: "colaboracion", label: "合作 / 媒体" },
        { value: "legal", label: "版权 / 投诉" },
        { value: "otro", label: "其他" },
      ],

      correctionsTitle: "更正（我们非常重视）",
      correctionsP:
        "若发现事实错误，请提供可核查的背景与来源。我们优先追求真实性：会及时更正，并在必要时留存更正记录。",
      correctionsBullets: [
        "提供文章链接与具体段落位置。",
        "附上一手来源（文件、公告、数据等）。",
        "若涉及日期/数字/姓名，请说明正确内容与依据。",
      ],

      collabTitle: "合作",
      collabP:
        "我们欢迎能带来真实增量价值的合作：数据、核查、访谈、研究与专业报道。",
      collabBullets: [
        "简短提案：主题、角度、为何现在。",
        "你的经验与过往作品链接。",
        "你能提供的资源：数据、渠道、研究或视角。",
      ],

      footerNote:
        "Newsoras — S.O.R.A.S.: Source-Oriented, Real-time Analysis System（基于来源的实时分析体系）。",
    };
  }

  return {
    title: "Contact",
    subtitle:
      "Suggestions, corrections, collaborations, and feedback. Evidence-first conversations.",

    metaTitle: "Contact — Newsoras",
    metaDescription:
      "Contact Newsoras to suggest topics, report factual errors, request corrections, or propose collaborations. Independent journalism with AI assistance.",

    quickTitle: "Quick channels",
    quickEmailLabel: "Email",
    quickEmailHint: "Best for corrections and formal requests.",
    quickTelegramLabel: "Telegram",
    quickTelegramHint: "Great for quick tips and follow-ups.",
    quickXLabel: "X",
    quickXHint: "Public updates and open discussions.",

    formTitle: "Write to us",
    formIntro:
      "Use this form to send a message. Prefer email? You can also write directly.",
    formName: "Name (optional)",
    formEmail: "Email (optional)",
    formTopic: "Topic",
    formTopicTip: "Pick a topic so your message gets routed faster.",
    formMessage: "Message",
    formSend: "Send",
    formPrivacy:
      "Privacy: we don’t publish your email. We use it only to reply and improve content.",

    topics: [
      { value: "correccion", label: "Correction / Factual issue" },
      { value: "sugerencia", label: "Story suggestion" },
      { value: "colaboracion", label: "Collaboration / Press" },
      { value: "legal", label: "Copyright / Claim" },
      { value: "otro", label: "Other" },
    ],

    correctionsTitle: "Corrections (we take them seriously)",
    correctionsP:
      "If you spot a factual error, help us with verifiable context. Truth matters here: we correct fast and keep a record when appropriate.",
    correctionsBullets: [
      "Include the article link and the specific paragraph.",
      "Share the primary source (document, statement, dataset, etc.).",
      "If it’s a date/number/name, specify the correct value and why.",
    ],

    collabTitle: "Collaborations",
    collabP:
      "We welcome collaborations that add real value: analysis, data, verification, interviews, and specialized coverage.",
    collabBullets: [
      "Short pitch: topic, angle, and why now.",
      "Your background (without exaggeration) + links to previous work.",
      "What you bring: data, access, research, or perspective.",
    ],

    footerNote:
      "Newsoras — S.O.R.A.S.: Source-Oriented, Real-time Analysis System. Verifiable facts + thoughtful analysis.",
  };
}

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

  return {
    title: t.metaTitle,
    description: t.metaDescription,
    alternates: {
      canonical,
      languages: {
        en: new URL(`/en/contact`, SITE_URL).toString(),
        es: new URL(`/es/contact`, SITE_URL).toString(),
        zh: new URL(`/zh/contact`, SITE_URL).toString(),
      },
    },
    openGraph: {
      type: "website",
      url: canonical,
      siteName: SITE_NAME,
      title: t.metaTitle,
      description: t.metaDescription,
      locale: locale === "es" ? "es_ES" : locale === "zh" ? "zh_CN" : "en_US",
      images: [
        {
          // ✅ Poné este archivo en /public/og/contact.png (1200x630)
          url: new URL(`/og/contact.png`, SITE_URL).toString(),
          width: 1200,
          height: 630,
          alt: `${SITE_NAME} — Contact`,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: t.metaTitle,
      description: t.metaDescription,
      images: [new URL(`/og/contact.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 helpers ---------------------------------------------------------
function jsonLdOrganization(locale: Locale) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";

  const contactPoints: any[] = [
    {
      "@type": "ContactPoint",
      contactType: "customer support",
      email: CONTACT_EMAIL,
      availableLanguage: ["en", "es", "zh"],
    },
  ];

  if (CONTACT_TELEGRAM) {
    contactPoints.push({
      "@type": "ContactPoint",
      contactType: "support",
      url: CONTACT_TELEGRAM,
      availableLanguage: ["en", "es", "zh"],
    });
  }

  return {
    "@context": "https://schema.org",
    "@type": "Organization",
    "@id": `${SITE_URL}#organization`,
    name: SITE_NAME,
    url: SITE_URL,
    // ✅ Poné un logo real en /public/logo.png (ideal 512x512)
    logo: `${SITE_URL}/logo.png`,
    contactPoint: contactPoints,
    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 jsonLdContactPage(locale: Locale) {
  const inLanguage = locale === "es" ? "es" : locale === "zh" ? "zh" : "en";
  const url = `${SITE_URL}/${locale}/contact`;

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

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

  const orgLd = jsonLdOrganization(locale);
  const siteLd = jsonLdWebsite(locale);
  const contactLd = jsonLdContactPage(locale);

  // Para el mailto con asunto “bonito”
  const subject =
    locale === "es"
      ? "Contacto — Newsoras"
      : locale === "zh"
      ? "联系 — Newsoras"
      : "Contact — Newsoras";

  const mailtoHref = `mailto:${encodeURIComponent(CONTACT_EMAIL)}?subject=${encodeURIComponent(
    subject
  )}`;

  return (
    <main className="container" style={{ paddingTop: 22, paddingBottom: 30 }}>
      {/* ✅ JSON-LD (Organization + WebSite + ContactPage) */}
      <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(contactLd) }}
      />

      {/* 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: 12 }}>
            <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: 8, marginTop: 14 }}>
            <span className="badge">Corrections</span>
            <span className="badge">Tips</span>
            <span className="badge">Collabs</span>
            <span className="badge">Copyright</span>
          </div>
        </div>
      </section>

      {/* Content Grid (mobile-first) */}
      <section
        style={{
          display: "grid",
          gridTemplateColumns: "1fr",
          gap: 18,
          marginTop: 18,
        }}
      >
        {/* Quick channels */}
        <div className="card" style={{ padding: 20 }}>
          <h2 className="h2" style={{ marginBottom: 12 }}>
            {t.quickTitle}
          </h2>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
              gap: 12,
            }}
          >
            {/* Email */}
            <div
              style={{
                border: "1px solid var(--line)",
                borderRadius: 16,
                padding: 14,
                background: "rgba(255,255,255,0.02)",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <div
                  style={{
                    width: 10,
                    height: 10,
                    borderRadius: 999,
                    background: "var(--accent)",
                    boxShadow: "0 0 10px var(--accent-glow)",
                  }}
                />
                <h3 style={{ margin: 0, fontSize: "1rem", fontWeight: 800 }}>
                  {t.quickEmailLabel}
                </h3>
              </div>

              <p className="p" style={{ margin: "0 0 12px 0", color: "var(--text-secondary)" }}>
                {t.quickEmailHint}
              </p>

              <a
                href={mailtoHref}
                className="badge"
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 8,
                  padding: "10px 14px",
                  borderColor: "var(--text-muted)",
                }}
              >
                {CONTACT_EMAIL}
              </a>
            </div>

            {/* Telegram (optional) */}
            {CONTACT_TELEGRAM ? (
              <div
                style={{
                  border: "1px solid var(--line)",
                  borderRadius: 16,
                  padding: 14,
                  background: "rgba(255,255,255,0.02)",
                }}
              >
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                  <div
                    style={{
                      width: 10,
                      height: 10,
                      borderRadius: 999,
                      background: "var(--accent)",
                      boxShadow: "0 0 10px var(--accent-glow)",
                    }}
                  />
                  <h3 style={{ margin: 0, fontSize: "1rem", fontWeight: 800 }}>
                    {t.quickTelegramLabel}
                  </h3>
                </div>

                <p className="p" style={{ margin: "0 0 12px 0", color: "var(--text-secondary)" }}>
                  {t.quickTelegramHint}
                </p>

                <a
                  href={CONTACT_TELEGRAM}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="badge"
                  style={{ display: "inline-flex", padding: "10px 14px", borderColor: "var(--text-muted)" }}
                >
                  Open Telegram
                </a>
              </div>
            ) : null}

            {/* X (optional) */}
            {CONTACT_X ? (
              <div
                style={{
                  border: "1px solid var(--line)",
                  borderRadius: 16,
                  padding: 14,
                  background: "rgba(255,255,255,0.02)",
                }}
              >
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                  <div
                    style={{
                      width: 10,
                      height: 10,
                      borderRadius: 999,
                      background: "var(--accent)",
                      boxShadow: "0 0 10px var(--accent-glow)",
                    }}
                  />
                  <h3 style={{ margin: 0, fontSize: "1rem", fontWeight: 800 }}>
                    {t.quickXLabel}
                  </h3>
                </div>

                <p className="p" style={{ margin: "0 0 12px 0", color: "var(--text-secondary)" }}>
                  {t.quickXHint}
                </p>

                <a
                  href={CONTACT_X}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="badge"
                  style={{ display: "inline-flex", padding: "10px 14px", borderColor: "var(--text-muted)" }}
                >
                  Open X
                </a>
              </div>
            ) : null}
          </div>

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

        {/* Form (visual, safe; no backend required) */}
        <div className="card" style={{ padding: 20 }}>
          <h2 className="h2" style={{ marginBottom: 8 }}>
            {t.formTitle}
          </h2>
          <p className="p" style={{ marginTop: 8, color: "var(--text-secondary)" }}>
            {t.formIntro}
          </p>

          {/* 
            ✅ Seguridad: este form NO envía a un endpoint (para evitar spam / sin backend).
            La acción es mailto (abre el cliente de correo del usuario).
            Cuando tengas un backend, lo cambiás por /api/contact con rate-limit + Turnstile.
          */}
          <form
            action={mailtoHref}
            method="post"
            encType="text/plain"
            style={{ display: "grid", gap: 12, marginTop: 14 }}
          >
            <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 12 }}>
              <label style={{ display: "grid", gap: 6 }}>
                <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{t.formName}</span>
                <input
                  name="name"
                  type="text"
                  placeholder={t.formName}
                  autoComplete="name"
                  style={inputStyle}
                />
              </label>

              <label style={{ display: "grid", gap: 6 }}>
                <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{t.formEmail}</span>
                <input
                  name="email"
                  type="email"
                  placeholder="you@email.com"
                  autoComplete="email"
                  style={inputStyle}
                />
              </label>
            </div>

            <label style={{ display: "grid", gap: 6 }}>
              <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{t.formTopic}</span>
              <select name="topic" defaultValue={t.topics[0]?.value ?? "otro"} style={inputStyle}>
                {t.topics.map((x) => (
                  <option key={x.value} value={x.value}>
                    {x.label}
                  </option>
                ))}
              </select>
              <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{t.formTopicTip}</span>
            </label>

            <label style={{ display: "grid", gap: 6 }}>
              <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{t.formMessage}</span>
              <textarea
                name="message"
                placeholder={t.formMessage}
                rows={6}
                style={{ ...inputStyle, resize: "vertical" }}
              />
            </label>

            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
              <button type="submit" className="badge" style={buttonStyle}>
                {t.formSend}
              </button>

              <Link href={`/${locale}`} className="badge" style={{ padding: "10px 14px" }}>
                Home
              </Link>
            </div>

            <div style={{ color: "var(--text-muted)", fontSize: 12 }}>
              {t.formPrivacy}
            </div>
          </form>

          <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)" }}>Nota técnica (anti-spam):</strong>{" "}
            cuando quieras un formulario real (sin “mailto”), lo hacemos con{" "}
            <strong style={{ color: "var(--text-primary)" }}>API route</strong> +{" "}
            <strong style={{ color: "var(--text-primary)" }}>rate-limit</strong> +{" "}
            <strong style={{ color: "var(--text-primary)" }}>Cloudflare Turnstile</strong>.
          </div>
        </div>

        {/* Corrections */}
        <div className="card" style={{ padding: 20 }}>
          <h2 className="h2" style={{ marginBottom: 8 }}>
            {t.correctionsTitle}
          </h2>
          <p className="p" style={{ marginTop: 8 }}>
            {t.correctionsP}
          </p>
          <ul style={{ marginTop: 12, paddingLeft: 18, color: "var(--text-secondary)", lineHeight: 1.75 }}>
            {t.correctionsBullets.map((x) => (
              <li key={x}>{x}</li>
            ))}
          </ul>
        </div>

        {/* Collabs */}
        <div className="card" style={{ padding: 20 }}>
          <h2 className="h2" style={{ marginBottom: 8 }}>
            {t.collabTitle}
          </h2>
          <p className="p" style={{ marginTop: 8 }}>
            {t.collabP}
          </p>
          <ul style={{ marginTop: 12, paddingLeft: 18, color: "var(--text-secondary)", lineHeight: 1.75 }}>
            {t.collabBullets.map((x) => (
              <li key={x}>{x}</li>
            ))}
          </ul>
        </div>
      </section>
    </main>
  );
}

// --- Styles (inline, consistent + mobile-friendly) ---------------------------
const inputStyle: React.CSSProperties = {
  width: "100%",
  padding: "12px 12px",
  borderRadius: 14,
  border: "1px solid var(--line)",
  background: "rgba(255,255,255,0.02)",
  color: "var(--text-primary)",
  outline: "none",
};

const buttonStyle: React.CSSProperties = {
  borderColor: "var(--text-muted)",
  padding: "10px 14px",
  cursor: "pointer",
  background: "rgba(255,255,255,0.02)",
};
