/* global React, useLang, TypedHeadline */
const { useMemo } = React;
// ============ Política de Cookies ============
// Espeja privacy-page.jsx: la estructura de cada cláusula se declara acá, el texto sale de
// t() (claves cookies.*, ver legal_messages.py). Agrega dos bloques que privacy no tiene:
//   { table: {rows, cols} }  tabla cookie / quién / para qué / cuánto dura
//   { button: true }         el botón que reabre el panel de preferencias
//
// TRAMPA heredada del patrón: las cláusulas son 1-based en las claves (cookies.s1.*) pero
// el índice del TOC es 0-based (cookies.toc.0). SECTIONS[0] ↔ s1 ↔ toc.0.
const SECTIONS = [
  { id: "que-es",        blocks: [{ p: 0 }, { p: 1 }] },
  { id: "esenciales",    blocks: [{ p: 0 }, { table: { rows: 2, cols: 4 } }, { p: 1 }] },
  { id: "analitica",     blocks: [{ p: 0 }, { table: { rows: 2, cols: 4 } }, { p: 1 }] },
  { id: "publicidad",    blocks: [{ p: 0 }, { table: { rows: 2, cols: 4 } }, { p: 1 }, { p: 2 }] },
  { id: "cambiar",       blocks: [{ p: 0 }, { button: true }, { p: 1 }] },
  { id: "terceros",      blocks: [{ p: 0 }, { p: 1 }] },
  { id: "sin-cookies",   blocks: [{ p: 0 }, { ul: 2 }, { p: 1 }] },
  { id: "derechos",      blocks: [{ p: 0 }, { p: 1 }] },
  { id: "cambios",       blocks: [{ p: 0 }, { email: true }] },
];

const P_STYLE = {
  color: "var(--neutral-2)",
  fontSize: 16,
  lineHeight: 1.75,
  maxWidth: "72ch",
  marginTop: 14,
};

function CookiesEmail() {
  const { t } = useLang();
  const email = t("cookies.email.value");
  return (
    <p style={P_STYLE}>
      {t("cookies.email.label")}{" "}
      <a href={`mailto:${email}`} style={{ color: "var(--ink)", fontWeight: 600 }}>
        {email}
      </a>
    </p>
  );
}

// Reabre el panel de preferencias desde el cuerpo de la política. Es el mismo mecanismo que
// el enlace del pie: retirar el consentimiento tiene que ser tan fácil como haberlo dado.
function CookiesPrefsButton() {
  const { t } = useLang();
  return (
    <button
      type="button"
      className="legal-prefs-btn"
      onClick={() => window.ForsvarConsent && window.ForsvarConsent.open()}
    >
      {t("cookies.s5.button")}
    </button>
  );
}

function CookiesTable({ n, spec }) {
  const { t } = useLang();
  const cols = Array.from({ length: spec.cols }, (_, c) => c);
  return (
    <div className="legal-tbl-wrap">
      <table className="legal-tbl">
        <thead>
          <tr>{cols.map((c) => <th key={c}>{t(`cookies.s${n}.th${c}`)}</th>)}</tr>
        </thead>
        <tbody>
          {Array.from({ length: spec.rows }, (_, r) => (
            <tr key={r}>
              {cols.map((c) => (
                <td key={c}>
                  {c === 0
                    ? <code className="legal-tbl-name">{t(`cookies.s${n}.r${r}.c${c}`)}</code>
                    : t(`cookies.s${n}.r${r}.c${c}`)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function CookiesClause({ section, index }) {
  const { t } = useLang();
  const n = index + 1;                 // número visible + prefijo de clave (cookies.s{n})

  return (
    <article
      id={section.id}
      style={{ scrollMarginTop: 96, marginTop: index === 0 ? 0 : 56 }}
    >
      <h2
        style={{
          fontSize: "clamp(22px, 2.4vw, 30px)",
          lineHeight: 1.15,
          letterSpacing: "-0.02em",
          color: "var(--ink)",
          margin: 0,
        }}
      >
        <span style={{ color: "var(--accent)", fontFamily: "var(--font-mono)", fontSize: "0.7em", marginRight: 10 }}>
          {String(n).padStart(2, "0")}
        </span>
        {t(`cookies.s${n}.title`)}
      </h2>

      {section.blocks.map((b, bi) => {
        if (b.email) return <CookiesEmail key={bi} />;
        if (b.button) return <CookiesPrefsButton key={bi} />;
        if (b.table) return <CookiesTable key={bi} n={n} spec={b.table} />;
        if (b.ul !== undefined) {
          return (
            <ul key={bi} style={{ margin: "14px 0 0", paddingLeft: 22, maxWidth: "72ch" }}>
              {Array.from({ length: b.ul }, (_, li) => (
                <li key={li} style={{ color: "var(--neutral-2)", fontSize: 16, lineHeight: 1.6, marginTop: 8 }}>
                  {t(`cookies.s${n}.li${li}`)}
                </li>
              ))}
            </ul>
          );
        }
        return <p key={bi} style={P_STYLE}>{t(`cookies.s${n}.p${b.p}`)}</p>;
      })}
    </article>
  );
}

function CookiesContent() {
  const { t, lang } = useLang();
  const segments = useMemo(() => [
    { type: "text", value: t("cookies.hero.h1a") },
    { type: "underline", value: t("cookies.hero.h1u") },
    { type: "text", value: t("cookies.hero.h1b") }
  ], [lang, t]);
  return (
    <>
      <section className="hero" id="top">
        <div className="container">
          <div className="hero-lower-left" style={{ maxWidth: 1100 }}>
            <span className="kicker"><span className="dot" />{t("cookies.hero.kicker")}</span>
            <h1 className="hero-headline hero-headline-narrow" style={{ marginTop: 22 }}>
              <TypedHeadline key={lang} segments={segments} />
            </h1>
            <p style={{ fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.04em", color: "var(--neutral-3)", marginTop: 28 }}>
              {t("cookies.hero.updated")}
            </p>
            <p className="hero-sub" style={{ maxWidth: "68ch", marginTop: 18 }}>
              {t("cookies.hero.intro")}
            </p>
            <nav className="fp-toc" aria-label="Índice de secciones">
              {SECTIONS.map((s, i) => (
                <a key={s.id} href={`#${s.id}`}>{t(`cookies.toc.${i}`)}</a>
              ))}
            </nav>
          </div>
        </div>
      </section>

      <section className="on-paper">
        <div className="container">
          <div style={{ maxWidth: 860 }}>
            <p style={{ ...P_STYLE, marginTop: 0 }}>{t("cookies.intro.body")}</p>
            <CookiesEmail />
            <div style={{ marginTop: 40 }}>
              {SECTIONS.map((s, i) => (
                <CookiesClause key={s.id} section={s} index={i} />
              ))}
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

window.CookiesEmail = CookiesEmail;
window.CookiesTable = CookiesTable;
window.CookiesClause = CookiesClause;
window.CookiesContent = CookiesContent;
