// Vildez — Cookie consent banner + policy modal
const { useState: useStateCC, useEffect: useEffectCC } = React;

const COOKIE_STORAGE_KEY = "vildez:cookie-consent";
// Bump this when the policy text or the set of cookies/SDKs materially changes.
// Decisions stored under an older version are treated as missing and the banner reappears.
const COOKIE_CONSENT_VERSION = 1;

const COOKIE_POLICY_LAST_UPDATED = "2026-05-03";

const COOKIE_I18N = {
  es: {
    title: "Cookies en vildez.com",
    body: "Esta Web solo utiliza cookies técnicas imprescindibles para su funcionamiento. No se emplean cookies analíticas ni de terceros. Puedes aceptar, rechazar o leer más detalles antes de decidir.",
    accept: "Aceptar",
    reject: "Rechazar",
    moreInfo: "Ver más información",
    policyTitle: "Política de cookies",
    policySub: `Última actualización: ${COOKIE_POLICY_LAST_UPDATED}.`,
    close: "Cerrar",
  },
  en: {
    title: "Cookies on vildez.com",
    body: "This site only uses strictly necessary cookies. No analytics or third-party cookies are used. You can accept, reject, or read more before deciding.",
    accept: "Accept",
    reject: "Reject",
    moreInfo: "More information",
    policyTitle: "Cookie policy",
    policySub: `Last updated: ${COOKIE_POLICY_LAST_UPDATED}.`,
    close: "Close",
  },
};

const COOKIE_POLICY_BODY = {
  es: [
    {
      kind: "p",
      text: "Esta política describe qué son las cookies, qué tipos utilizamos en https://vildez.com y cómo puedes gestionarlas, de acuerdo con el artículo 22.2 de la Ley 34/2002 de Servicios de la Sociedad de la Información (LSSI-CE) y la normativa europea aplicable.",
    },
    { kind: "h", text: "1. ¿Qué es una cookie?" },
    {
      kind: "p",
      text: "Una cookie es un pequeño fichero de texto que un sitio web almacena en tu navegador cuando la visitas. Permite recordar información sobre tu visita — como tu idioma preferido o el estado de sesión — y puede usarse también con fines analíticos o publicitarios.",
    },
    { kind: "h", text: "2. Tipos de cookies por finalidad" },
    {
      kind: "ul",
      items: [
        "Técnicas o necesarias: imprescindibles para el funcionamiento de la Web. No requieren consentimiento.",
        "Preferencia o personalización: recuerdan elecciones del usuario (idioma, región, etc.).",
        "Analíticas o de medición: permiten medir el uso de la Web para mejorarla. Requieren consentimiento.",
        "Publicidad y marketing: se usan para mostrar anuncios personalizados. Requieren consentimiento.",
      ],
    },
    { kind: "h", text: "3. Cookies que utiliza esta Web" },
    {
      kind: "p",
      text: "Esta Web solo utiliza cookies técnicas imprescindibles para su funcionamiento. No se emplean cookies analíticas, de personalización ni de terceros.",
    },
    {
      kind: "p",
      text: "En cumplimiento del artículo 22.2 LSSI-CE, también se informan las tecnologías similares (almacenamiento local del navegador) utilizadas con la misma finalidad estrictamente necesaria:",
    },
    {
      kind: "ul",
      items: [
        "companyBrain.auth — técnica, propia (localStorage). Mantiene la sesión iniciada del usuario. Duración: hasta cierre de sesión o borrado manual.",
        "companyBrain.currentUserId — técnica, propia (localStorage). Identifica al usuario activo para enviarlo en las cabeceras de la API. Duración: hasta cierre de sesión.",
        "companyBrain.sidebar.collapsed — técnica, propia (localStorage). Recuerda si tenías el menú lateral plegado para mantener tu elección al recargar. Duración: persistente hasta que la borres.",
        "vildez:cookie-consent — técnica, propia (localStorage). Guarda tu decisión sobre este aviso para no volver a mostrarlo. Duración: persistente hasta que la borres.",
      ],
    },
    {
      kind: "p",
      text: "Esta tabla se revisará y actualizará en cuanto se incorpore cualquier servicio adicional (analítica, chat, vídeo embebido, etc.).",
    },
    { kind: "h", text: "4. Consentimiento" },
    {
      kind: "p",
      text: "Al acceder por primera vez a la Plataforma, se mostrará un banner informativo que permite al usuario aceptar, rechazar o personalizar el uso de cookies no esenciales. El consentimiento puede modificarse en cualquier momento desde el botón \"Cookies\" disponible en el pie del menú lateral, que vuelve a abrir este aviso.",
    },
    {
      kind: "p",
      text: "La retirada del consentimiento no afectará a la licitud del tratamiento basado en el consentimiento previo a su retirada.",
    },
    { kind: "h", text: "5. Cómo gestionar o desactivar las cookies" },
    {
      kind: "p",
      text: "Puedes aceptar, rechazar o borrar las cookies directamente desde la configuración de tu navegador:",
    },
    {
      kind: "ul",
      items: [
        "Chrome: Ajustes → Privacidad y seguridad → Cookies.",
        "Firefox: Ajustes → Privacidad & Seguridad → Cookies.",
        "Safari: Preferencias → Privacidad → Gestionar datos del sitio web.",
        "Edge: Configuración → Cookies y permisos del sitio.",
      ],
    },
    {
      kind: "p",
      text: "Ten en cuenta que deshabilitar las cookies técnicas puede afectar al correcto funcionamiento de la Web.",
    },
    { kind: "h", text: "6. Transferencias internacionales" },
    {
      kind: "p",
      text: "Algunos de los proveedores que instalan cookies pueden tratar tus datos fuera del Espacio Económico Europeo. Consulta nuestra Política de Privacidad para más información sobre las garantías aplicadas.",
    },
    { kind: "h", text: "7. Cambios en esta política" },
    {
      kind: "p",
      text: "Esta política puede actualizarse para reflejar cambios en los servicios que utilizamos o en la legislación aplicable. Publicaremos cualquier cambio en esta página indicando la fecha de la última actualización.",
    },
    { kind: "h", text: "8. Contacto" },
    {
      kind: "p",
      text: "Para cualquier duda sobre esta política, puedes escribirnos a contact@vildez.com.",
    },
  ],
  en: [
    {
      kind: "p",
      text: "This policy describes what cookies are, which types we use on https://vildez.com and how you can manage them, in accordance with article 22.2 of Spanish Law 34/2002 (LSSI-CE) and the applicable European regulation.",
    },
    { kind: "h", text: "1. What is a cookie?" },
    {
      kind: "p",
      text: "A cookie is a small text file that a website stores on your browser when you visit it. It allows the site to remember information about your visit — such as your preferred language or session state — and may also be used for analytical or advertising purposes.",
    },
    { kind: "h", text: "2. Types of cookies by purpose" },
    {
      kind: "ul",
      items: [
        "Strictly necessary: essential for the website to work. No consent required.",
        "Preferences / personalization: remember user choices (language, region, etc.).",
        "Analytics / measurement: measure usage to improve the site. Require consent.",
        "Advertising and marketing: used to show personalized ads. Require consent.",
      ],
    },
    { kind: "h", text: "3. Cookies used on this site" },
    {
      kind: "p",
      text: "This site only uses strictly necessary cookies. No analytics, personalization or third-party cookies are used.",
    },
    {
      kind: "p",
      text: "Pursuant to article 22.2 LSSI-CE, similar technologies (browser local storage) used for the same strictly-necessary purpose are also disclosed:",
    },
    {
      kind: "ul",
      items: [
        "companyBrain.auth — strictly necessary, first-party (localStorage). Keeps the user signed in. Duration: until logout or manual deletion.",
        "companyBrain.currentUserId — strictly necessary, first-party (localStorage). Identifies the active user for API request headers. Duration: until logout.",
        "companyBrain.sidebar.collapsed — strictly necessary, first-party (localStorage). Remembers whether the side menu was collapsed so your choice is restored on reload. Duration: persistent until deleted.",
        "vildez:cookie-consent — strictly necessary, first-party (localStorage). Stores your decision on this notice so it is not shown again. Duration: persistent until deleted.",
      ],
    },
    {
      kind: "p",
      text: "This table will be reviewed and updated whenever any additional service is added (analytics, chat, embedded video, etc.).",
    },
    { kind: "h", text: "4. Consent" },
    {
      kind: "p",
      text: 'On your first visit, an informational banner is shown that lets you accept, reject or customize non-essential cookies. You can change your choice at any time from the "Cookies" button in the sidebar footer, which reopens this notice.',
    },
    {
      kind: "p",
      text: "Withdrawing consent does not affect the lawfulness of processing based on consent before its withdrawal.",
    },
    { kind: "h", text: "5. How to manage or disable cookies" },
    {
      kind: "p",
      text: "You can accept, reject or delete cookies directly from your browser settings:",
    },
    {
      kind: "ul",
      items: [
        "Chrome: Settings → Privacy and security → Cookies.",
        "Firefox: Settings → Privacy & Security → Cookies.",
        "Safari: Preferences → Privacy → Manage website data.",
        "Edge: Settings → Cookies and site permissions.",
      ],
    },
    {
      kind: "p",
      text: "Note that disabling strictly necessary cookies may break the site.",
    },
    { kind: "h", text: "6. International transfers" },
    {
      kind: "p",
      text: "Some providers that install cookies may process your data outside the European Economic Area. See our Privacy Policy for details on the safeguards in place.",
    },
    { kind: "h", text: "7. Changes to this policy" },
    {
      kind: "p",
      text: "This policy may be updated to reflect changes in the services we use or in applicable law. Any change will be published on this page along with the date of the last update.",
    },
    { kind: "h", text: "8. Contact" },
    {
      kind: "p",
      text: "If you have any questions about this policy, you can write to us at contact@vildez.com.",
    },
  ],
};

function readConsent() {
  try {
    const raw = localStorage.getItem(COOKIE_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || parsed.version !== COOKIE_CONSENT_VERSION) return null;
    return parsed;
  } catch (e) {
    return null;
  }
}

function writeConsent(decision) {
  try {
    localStorage.setItem(
      COOKIE_STORAGE_KEY,
      JSON.stringify({
        decision,
        version: COOKIE_CONSENT_VERSION,
        at: new Date().toISOString(),
      })
    );
  } catch (e) {}
  window.dispatchEvent(new CustomEvent("cookie-consent-changed", { detail: { decision } }));
}

window.cookieConsent = {
  get: readConsent,
  set: writeConsent,
  version: COOKIE_CONSENT_VERSION,
  reset: () => {
    try { localStorage.removeItem(COOKIE_STORAGE_KEY); } catch (e) {}
    window.dispatchEvent(new CustomEvent("cookie-consent-changed", { detail: { decision: null } }));
  },
};

window.CookieConsent = function CookieConsent({ lang }) {
  const t = COOKIE_I18N[lang] || COOKIE_I18N.es;
  const policyBody = COOKIE_POLICY_BODY[lang] || COOKIE_POLICY_BODY.es;
  const [visible, setVisible] = useStateCC(() => readConsent() === null);
  const [policyOpen, setPolicyOpen] = useStateCC(false);

  useEffectCC(() => {
    const onChanged = () => setVisible(readConsent() === null);
    window.addEventListener("cookie-consent-changed", onChanged);
    return () => window.removeEventListener("cookie-consent-changed", onChanged);
  }, []);

  const decide = (decision) => {
    writeConsent(decision);
    setPolicyOpen(false);
  };

  const Modal = window.Modal;

  return (
    <>
      {visible && (
        <div className="cookie-banner" role="dialog" aria-live="polite" aria-label={t.title}>
          <div className="cookie-banner-text">
            <h4 className="cookie-banner-title">{t.title}</h4>
            <p className="cookie-banner-body">{t.body}</p>
          </div>
          <div className="cookie-banner-actions">
            <button type="button" className="btn ghost" onClick={() => setPolicyOpen(true)}>
              {t.moreInfo}
            </button>
            <button type="button" className="btn" onClick={() => decide("rejected")}>
              {t.reject}
            </button>
            <button type="button" className="btn brand" onClick={() => decide("accepted")}>
              {t.accept}
            </button>
          </div>
        </div>
      )}

      {Modal && (
        <Modal
          open={policyOpen}
          onClose={() => setPolicyOpen(false)}
          title={t.policyTitle}
          subtitle={t.policySub}
          width={640}
          closeOnBackdrop={true}
          footer={
            <>
              <button type="button" className="btn" onClick={() => decide("rejected")}>{t.reject}</button>
              <button type="button" className="btn brand" onClick={() => decide("accepted")}>{t.accept}</button>
            </>
          }
        >
          <div className="cookie-policy">
            {policyBody.map((block, i) => {
              if (block.kind === "h") return <h4 key={i} className="cookie-policy-h">{block.text}</h4>;
              if (block.kind === "ul") {
                return (
                  <ul key={i} className="cookie-policy-ul">
                    {block.items.map((it, j) => <li key={j}>{it}</li>)}
                  </ul>
                );
              }
              return <p key={i} className="cookie-policy-p">{block.text}</p>;
            })}
          </div>
        </Modal>
      )}
    </>
  );
};
