/* ============ GDPR cookie consent ============ */

const COOKIE_CONSENT_KEY = "yml_cookie_consent";
const CONSENT_VERSION = 2;
const CONSENT_MAX_AGE_DAYS = 365;

// Config-driven categories — add/edit a category here, nothing else needs
// to change structurally. "analytics" and "marketing" aren't wired to any
// actual script yet (this site doesn't run analytics or ad tags today),
// but the categories and the hasConsent(key) API are ready for when it does.
const COOKIE_CATEGORIES = [
  {
    key: "necessary",
    label: "Välttämättömät",
    required: true,
    description: "Sivuston perustoimintojen kannalta pakollisia evästeitä. Ei voi poistaa käytöstä.",
  },
  {
    key: "analytics",
    label: "Suorituskyky ja analytiikka",
    required: false,
    description: "Auttavat ymmärtämään, miten sivustoa käytetään, jotta sitä voi kehittää.",
  },
  {
    key: "marketing",
    label: "Markkinointi ja mainonta",
    required: false,
    description: "Käytetään mainonnan kohdentamiseen ja mittaamiseen.",
  },
  {
    key: "embeds",
    label: "Upotukset (Spotify)",
    required: false,
    description: "Sallii Spotify-soittimien näyttämisen. Spotify voi asettaa evästeitä selaimeesi upotuksen latautuessa.",
  },
];
window.COOKIE_CATEGORIES = COOKIE_CATEGORIES;

function defaultConsentValues() {
  const values = {};
  for (const cat of COOKIE_CATEGORIES) values[cat.key] = Boolean(cat.required);
  return values;
}

function readCookieConsent() {
  try {
    const raw = localStorage.getItem(COOKIE_CONSENT_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || parsed.version !== CONSENT_VERSION || !parsed.updatedAt) return null;
    const ageDays = (Date.now() - new Date(parsed.updatedAt).getTime()) / (1000 * 60 * 60 * 24);
    if (!(ageDays >= 0) || ageDays > CONSENT_MAX_AGE_DAYS) return null;
    return parsed;
  } catch (err) {
    return null;
  }
}

function writeCookieConsent(consent) {
  try {
    localStorage.setItem(COOKIE_CONSENT_KEY, JSON.stringify(consent));
  } catch (err) {
    // localStorage unavailable (private mode etc.) — consent just won't persist
  }
  window.dispatchEvent(new CustomEvent("cookie-consent-changed", { detail: consent }));
}

// partial: object of {categoryKey: boolean} — only overrides the given keys
function setCookieConsent(partial) {
  const current = readCookieConsent() || defaultConsentValues();
  const next = { ...defaultConsentValues(), ...current, ...partial };
  for (const cat of COOKIE_CATEGORIES) {
    if (cat.required) next[cat.key] = true;
  }
  next.version = CONSENT_VERSION;
  next.updatedAt = new Date().toISOString();
  writeCookieConsent(next);
}

function acceptAllConsent() {
  const all = {};
  for (const cat of COOKIE_CATEGORIES) all[cat.key] = true;
  setCookieConsent(all);
}

// Simple API other code can use to gate scripts/embeds on a category, e.g.
// window.hasConsent('analytics') before loading an analytics script.
window.getCookieConsent = readCookieConsent;
window.hasConsent = function (key) {
  const c = readCookieConsent();
  return Boolean(c && c[key]);
};
window.hasEmbedConsent = function () {
  return window.hasConsent("embeds");
};
window.setCookieConsent = setCookieConsent;
window.acceptAllCookieConsent = acceptAllConsent;
window.openCookiePreferences = function () {
  window.dispatchEvent(new CustomEvent("open-cookie-preferences"));
};

function useCookieConsent() {
  const [consent, setConsent] = React.useState(readCookieConsent);
  React.useEffect(() => {
    const onChange = (e) => setConsent(e.detail);
    window.addEventListener("cookie-consent-changed", onChange);
    return () => window.removeEventListener("cookie-consent-changed", onChange);
  }, []);
  return consent;
}
window.useCookieConsent = useCookieConsent;

// Google AdSense (Auto ads) — only loads once "marketing" consent is given,
// and only ever loads once. Checked on startup, and again on every consent
// change so accepting later (not just on first visit) also triggers it.
const ADSENSE_CLIENT_ID = "ca-pub-9530802940952979";
let adsenseLoaded = false;
function loadAdsenseIfConsented() {
  if (adsenseLoaded || !window.hasConsent("marketing")) return;
  adsenseLoaded = true;
  const script = document.createElement("script");
  script.async = true;
  script.crossOrigin = "anonymous";
  script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${ADSENSE_CLIENT_ID}`;
  document.head.appendChild(script);
}
loadAdsenseIfConsented();
window.addEventListener("cookie-consent-changed", loadAdsenseIfConsented);

// Vercel Web Analytics — cookieless, but still gated behind "analytics"
// consent for consistency with how the site presents its categories.
let vercelAnalyticsLoaded = false;
function loadVercelAnalyticsIfConsented() {
  if (vercelAnalyticsLoaded || !window.hasConsent("analytics")) return;
  vercelAnalyticsLoaded = true;
  const script = document.createElement("script");
  script.defer = true;
  script.src = "/_vercel/insights/script.js";
  document.head.appendChild(script);
}
loadVercelAnalyticsIfConsented();
window.addEventListener("cookie-consent-changed", loadVercelAnalyticsIfConsented);

function CookiePreferencesModal({ onClose }) {
  const stored = readCookieConsent() || defaultConsentValues();
  const [values, setValues] = React.useState(() => {
    const v = {};
    for (const cat of COOKIE_CATEGORIES) v[cat.key] = cat.required ? true : Boolean(stored[cat.key]);
    return v;
  });

  const panelRef = React.useRef(null);
  const previousFocusRef = React.useRef(null);

  // Focus trap: focus the panel on open, cycle Tab within it, Escape closes
  // without saving, and focus returns to whatever triggered the modal.
  React.useEffect(() => {
    previousFocusRef.current = document.activeElement;
    const panel = panelRef.current;
    const getFocusable = () =>
    panel ? Array.from(panel.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')) : [];

    const focusables = getFocusable();
    if (focusables.length) focusables[0].focus();

    function onKeyDown(e) {
      if (e.key === "Escape") {
        e.preventDefault();
        onClose();
        return;
      }
      if (e.key === "Tab") {
        const items = getFocusable();
        if (!items.length) return;
        const first = items[0];
        const last = items[items.length - 1];
        if (e.shiftKey && document.activeElement === first) {
          e.preventDefault();
          last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
      }
    }
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      if (previousFocusRef.current && previousFocusRef.current.focus) {
        previousFocusRef.current.focus();
      }
    };
  }, [onClose]);

  function save() {
    setCookieConsent(values);
    onClose();
  }

  return (
    <div className="cookie-modal__overlay" onClick={onClose}>
      <div
        className="cookie-modal"
        ref={panelRef}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="cookie-modal-title">

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16 }}>
          <h3 id="cookie-modal-title" className="h3" style={{ marginBottom: 8 }}>Evästeasetukset</h3>
          <button className="cookie-modal__close" onClick={onClose} aria-label="Sulje tallentamatta muutoksia">
            ✕
          </button>
        </div>
        <p style={{ marginBottom: 8, color: "var(--charcoal)" }}>
          Voit valita, mitä evästeitä sallit tällä sivustolla. Voit muuttaa valintaasi täältä milloin tahansa.
          Lisätietoa evästeistä ja tietojenkäsittelystä löydät{" "}
          <a href="#/tietosuojaseloste" style={{ textDecoration: "underline" }}>tietosuojaselosteestamme</a>.
        </p>

        {COOKIE_CATEGORIES.map((cat) =>
        <div className="cookie-modal__row" key={cat.key}>
            <div>
              <div style={{ fontWeight: 600 }} id={`cookie-cat-${cat.key}-label`}>{cat.label}</div>
              <div style={{ fontSize: "0.9rem", color: "var(--charcoal)" }} id={`cookie-cat-${cat.key}-desc`}>
                {cat.description}
              </div>
            </div>
            <input
            type="checkbox"
            checked={values[cat.key]}
            disabled={cat.required}
            aria-labelledby={`cookie-cat-${cat.key}-label`}
            aria-describedby={`cookie-cat-${cat.key}-desc`}
            onChange={(e) => setValues((v) => ({ ...v, [cat.key]: e.target.checked }))} />

          </div>
        )}

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 24, flexWrap: "wrap" }}>
          <button className="btn btn--primary" onClick={save}>Tallenna asetukset</button>
        </div>
      </div>
    </div>);

}

function CookieBanner() {
  const consent = useCookieConsent();
  const [modalOpen, setModalOpen] = React.useState(false);

  React.useEffect(() => {
    const onOpen = () => setModalOpen(true);
    window.addEventListener("open-cookie-preferences", onOpen);
    return () => window.removeEventListener("open-cookie-preferences", onOpen);
  }, []);

  if (modalOpen) {
    return <CookiePreferencesModal onClose={() => setModalOpen(false)} />;
  }

  if (consent !== null) return null;

  return (
    <div className="cookie-banner" role="dialog" aria-label="Evästeilmoitus">
      <div className="cookie-banner__text">
        <strong>Käytämme evästeitä.</strong>{" "}
        Käytämme evästeitä sivuston perustoimintoihin sekä valinnaisesti analytiikkaan, markkinointiin ja
        Spotify-soittimien näyttämiseen. Voit muuttaa valintaasi milloin tahansa sivun alalaidan Evästeasetuksista.
        Lue lisää <a href="#/tietosuojaseloste" style={{ textDecoration: "underline" }}>tietosuojaselosteestamme</a>.
      </div>
      <div className="cookie-banner__actions">
        <button className="btn btn--tertiary" onClick={() => setModalOpen(true)}>Hallinnoi evästeitä</button>
        <button className="btn btn--primary" onClick={() => acceptAllConsent()}>Hyväksy kaikki</button>
      </div>
    </div>);

}

window.CookieBanner = CookieBanner;
