function CookiesNublo() {
  const { useState, useEffect } = React;

  const [open, setOpen] = useState(false);
  const [analytics, setAnalytics] = useState(false);
  const [marketing, setMarketing] = useState(false);

  useEffect(() => {
    const saved = localStorage.getItem("nl-consent");
    if (!saved) {
      setOpen(true);
    } else {
      const prefs = JSON.parse(saved);

      if (typeof prefs.analytics === "boolean") {
        setAnalytics(prefs.analytics);
      }
      if (typeof prefs.marketing === "boolean") {
        setMarketing(prefs.marketing);
      }

      if (prefs.analytics) {
        loadScript("https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX");
      }

      if (prefs.marketing) {
        loadScript("https://connect.facebook.net/en_US/fbevents.js");
      }
    }
  }, []);

  // Marcar en el DOM cuando el panel está abierto (para usarlo desde CSS)
  useEffect(() => {
    if (typeof document === "undefined") return;
    const root = document.documentElement;
    if (open) {
      root.setAttribute("data-cookies-open", "1");
    } else {
      root.removeAttribute("data-cookies-open");
    }
  }, [open]);

  function loadScript(url) {
    const s = document.createElement("script");
    s.src = url;
    s.async = true;
    document.head.appendChild(s);
  }

  function applyConsent(prefs) {
    try {
      localStorage.setItem("nl-consent", JSON.stringify(prefs));
    } catch (e) {
      // ignore storage errors
    }

    try {
      const root = document.documentElement;
      // marcar que se han aceptado cookies para animar el icono de WhatsApp
      root.setAttribute("data-cookies-accepted", "1");
      root.removeAttribute("data-cookies-open");
    } catch (e) {
      // ignore DOM errors
    }

    // Cerrar panel sin recargar la página
    setOpen(false);

    // Aplicar inmediatamente las preferencias opcionales
    if (prefs.analytics) {
      loadScript("https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX");
    }
    if (prefs.marketing) {
      loadScript("https://connect.facebook.net/en_US/fbevents.js");
    }

    // Abrir el popup de lead si está disponible
    try {
      if (window.NubloLeadPopup && typeof window.NubloLeadPopup.open === "function") {
        window.NubloLeadPopup.open();
      }
    } catch (e) {
      // ignore popup errors
    }
  }

  function acceptAll() {
    const prefs = { analytics: true, marketing: true };
    applyConsent(prefs);
  }

  function rejectAll() {
    const prefs = { analytics: false, marketing: false };
    applyConsent(prefs);
  }

  function acceptSelected() {
    const prefs = { analytics, marketing };
    applyConsent(prefs);
  }

  return (
    <>
      {/* Botón para reabrir */}
      {!open && (
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="cookies-reopen"
        >
          <span>Preferencias de cookies</span>
          <img
            src="https://uxwing.com/wp-content/themes/uxwing/download/food-and-drinks/cookies-icon.png"
            alt="Preferencias de cookies"
          />
        </button>
      )}

      {/* Banner principal */}
      {open && (
        <div
          style={{
            position: "fixed",
            bottom: 0,
            left: 0,
            right: 0,
            background: "rgba(3, 20, 35, 0.96)",
            borderTop: "1px solid rgba(148, 197, 255, 0.25)",
            padding: 8,
            boxShadow: "0 -14px 30px rgba(3, 10, 32, 0.75)",
            zIndex: 9999,
            animation: "slideUp 0.5s ease",
            fontFamily: "Montserrat, sans-serif",
          }}
          >
          <div
            style={{
              maxWidth: 1040,
              margin: "0 auto",
              display: "flex",
              flexDirection: "column",
              gap: 12,
              textAlign: "left",
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 6,
              }}
            >
              <h3
                style={{
                  fontSize: "1.5rem",
                  margin: 0,
                  color: "#eaf6ff",
                  fontWeight: 700,
                  textAlign: "center",
                }}
              >
                Preferencias de Cookies
              </h3>

              <p
                style={{
                  margin: 0,
                  color: "rgba(214, 234, 255, 0.9)",
                  lineHeight: 1.4,
                  fontSize: "0.9rem",
                  textAlign: "justify",
                  textJustify: "inter-word",
                  width: "100%",
                }}
              >
                Usamos cookies esenciales para que el sitio funcione y opcionales para{" "}
                <strong>analítica</strong> y <strong>marketing</strong>. Las cookies esenciales no pueden
                desactivarse, ya que permiten funciones básicas como seguridad, acceso al sitio o recordar
                tus preferencias técnicas. Puedes leer más en nuestra{" "}
                <a
                  href="https://nublolanguages.com/cookies"
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{ color: "#f7d24a", textDecoration: "underline" }}
                >
                  política de cookies
                </a>
                .
              </p>
            </div>

            {/* Preferencias: Esenciales / Analíticas / Marketing */}
            <div
              className="cookies-cards"
              style={{
                display: "grid",
                gap: 10,
                marginTop: 2,
                alignItems: "stretch",
              }}
            >
              {/* Esenciales (siempre activas) */}
              <div
                style={{
                  flex: "1 1 260px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 10,
                  padding: "8px 12px",
                  borderRadius: 12,
                  border: "1px solid rgba(199, 210, 254, 0.9)",
                  background: "rgba(1, 39, 63, 0.94)",
                  cursor: "default",
                }}
              >
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span
                    style={{
                      fontSize: "0.85rem",
                      fontWeight: 600,
                      color: "#eaf6ff",
                    }}
                  >
                    Esenciales
                  </span>
                  <span
                    style={{
                      fontSize: "0.78rem",
                      color: "rgba(187, 213, 242, 0.9)",
                    }}
                  >
                    Necesarias para funciones básicas como seguridad, acceso al sitio y recordar tus
                    preferencias técnicas. Siempre activas.
                  </span>
                </div>

                {/* Switch visual bloqueado */}
                <div
                  style={{
                    width: 46,
                    minWidth: 46,
                    height: 24,
                    borderRadius: 999,
                    background: "#f7d24a",
                    padding: 3,
                    position: "relative",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "flex-end",
                    opacity: 0.85,
                    boxSizing: "border-box",
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: "50%",
                      background: "#ffffff",
                      boxShadow: "0 2px 6px rgba(15,23,42,0.25)",
                    }}
                  />
                </div>
              </div>

              {/* Analíticas */}
              <label
                style={{
                  flex: "1 1 260px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 10,
                  padding: "8px 12px",
                  borderRadius: 12,
                  border: analytics
                    ? "1px solid rgba(148, 197, 255, 0.9)"
                    : "1px solid rgba(99, 161, 214, 0.5)",
                  background: analytics
                    ? "linear-gradient(135deg, rgba(148, 197, 255, 0.35), rgba(0, 73, 109, 0.4))"
                    : "rgba(1, 39, 63, 0.94)",
                  cursor: "pointer",
                  boxShadow: analytics ? "0 10px 26px rgba(2, 20, 40, 0.65)" : "none",
                }}
              >
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span
                    style={{
                      fontSize: "0.85rem",
                      fontWeight: 600,
                      color: "#eaf6ff",
                    }}
                  >
                    Analíticas
                  </span>
                  <span
                    style={{
                      fontSize: "0.78rem",
                      color: "rgba(187, 213, 242, 0.9)",
                    }}
                  >
                    Nos ayudan a entender cómo usas Nublo Languages para mejorar tu experiencia.
                  </span>
                </div>

                {/* Switch visual */}
                <div
                  style={{
                    width: 46,
                    minWidth: 46,
                    height: 24,
                    borderRadius: 999,
                    background: analytics ? "#f7d24a" : "rgba(148, 197, 255, 0.35)",
                    padding: 3,
                    position: "relative",
                    transition: "background 0.2s ease",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: analytics ? "flex-end" : "flex-start",
                    boxSizing: "border-box",
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: "50%",
                      background: "#ffffff",
                      boxShadow: "0 2px 6px rgba(15,23,42,0.25)",
                      transition: "transform 0.2s ease",
                    }}
                  />
                </div>

                {/* Checkbox real (oculto visualmente) */}
                <input
                  type="checkbox"
                  checked={analytics}
                  onChange={(e) => setAnalytics(e.target.checked)}
                  style={{ display: "none" }}
                />
              </label>

              {/* Marketing */}
              <label
                style={{
                  flex: "1 1 260px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 10,
                  padding: "8px 12px",
                  borderRadius: 12,
                  border: marketing
                    ? "1px solid rgba(199, 148, 0, 0.9)"
                    : "1px solid rgba(99, 161, 214, 0.5)",
                  background: marketing
                    ? "linear-gradient(135deg, rgba(247, 210, 74, 0.35), rgba(218, 172, 0, 0.4))"
                    : "rgba(1, 39, 63, 0.94)",
                  cursor: "pointer",
                  boxShadow: marketing ? "0 10px 26px rgba(2, 20, 40, 0.65)" : "none",
                }}
              >
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span
                    style={{
                      fontSize: "0.85rem",
                      fontWeight: 600,
                      color: "#eaf6ff",
                    }}
                  >
                    Marketing
                  </span>
                  <span
                    style={{
                      fontSize: "0.78rem",
                      color: "rgba(187, 213, 242, 0.9)",
                    }}
                  >
                    Ayudan a medir el rendimiento de campañas de publicidad y a mejorar la segmentación.
                  </span>
                </div>

                {/* Switch visual */}
                <div
                  style={{
                    width: 46,
                    minWidth: 46,
                    height: 24,
                    borderRadius: 999,
                    background: marketing ? "#f7d24a" : "rgba(148, 197, 255, 0.35)",
                    padding: 3,
                    position: "relative",
                    transition: "background 0.2s ease",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: marketing ? "flex-end" : "flex-start",
                    boxSizing: "border-box",
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: "50%",
                      background: "#ffffff",
                      boxShadow: "0 2px 6px rgba(15,23,42,0.25)",
                      transition: "transform 0.2s ease",
                    }}
                  />
                </div>

                {/* Checkbox real (oculto visualmente) */}
                <input
                  type="checkbox"
                  checked={marketing}
                  onChange={(e) => setMarketing(e.target.checked)}
                  style={{ display: "none" }}
                />
              </label>
            </div>

            {/* Botones de acción */}
            <div
              className="cookies-buttons"
              style={{
                display: "inline-flex",
                flexDirection: "column",
                alignItems: "stretch",
                alignSelf: "center",
                width: "auto",
                gap: 8,
                marginTop: 8,
              }}
            >
              <div
                className="cookies-buttons-row"
                style={{
                  display: "flex",
                  justifyContent: "center",
                  gap: 10,
                }}
              >
                <button
                  onClick={rejectAll}
                  style={{
                    padding: "8px 14px",
                    borderRadius: 999,
                    border: "1px solid rgba(148, 197, 255, 0.7)",
                    background: "transparent",
                    color: "rgba(214, 234, 255, 0.95)",
                    cursor: "pointer",
                    fontSize: "0.9rem",
                  }}
                >
                  Solo esenciales
                </button>

                <button
                  onClick={acceptSelected}
                  style={{
                    padding: "8px 16px",
                    borderRadius: 999,
                    border: "none",
                    background: "rgba(0, 73, 109, 0.96)",
                    color: "#eaf6ff",
                    cursor: "pointer",
                    fontSize: "0.9rem",
                  }}
                >
                  Guardar selección
                </button>
              </div>

              <button
                onClick={acceptAll}
                className="cookies-cta-all"
                style={{
                  padding: "8px 20px",
                  borderRadius: 999,
                  border: "none",
                  background:
                    "linear-gradient(135deg, #f7d24a 0%, #daac00 45%, #c89400 100%)",
                  color: "#031423",
                  cursor: "pointer",
                  fontSize: "0.9rem",
                  fontWeight: 700,
                  boxShadow: "0 10px 24px rgba(218,172,0,0.35)",
                }}
              >
                Aceptar todas
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Animación CSS */}
      <style>
        {`
        @keyframes slideUp {
          from { transform: translateY(100%); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }

        /* Layout responsive para los tres "heros" de cookies */
        .cookies-cards {
          grid-template-columns: minmax(0, 1fr);
        }

        @media (min-width: 720px) {
          .cookies-cards {
            grid-template-columns: repeat(2, minmax(0, 1fr));
          }
        }

        @media (min-width: 1100px) {
          .cookies-cards {
            grid-template-columns: repeat(3, minmax(0, 1fr));
          }
        }

        @media (max-width: 720px) {
          .cookies-buttons {
            display: inline-flex;
            flex-direction: column;
            align-items: stretch;
            align-self: center;
            width: auto;
          }

          .cookies-buttons-row {
            display: inline-flex;
          }

          .cookies-cta-all {
            width: 100%;
          }
        }
      `}
      </style>
    </>
  );
}

// Exponer globalmente cuando se carga en el navegador (igual patrón previsu.html)
if (typeof window !== "undefined") {
  window.CookiesNublo = CookiesNublo;
}
