// Trepic cookie consent banner — vanilla JS, no React, no deps.
// Loaded as <script type="text/javascript"> on every page.
//
// Persists choice in localStorage under `trepic_cookie_consent_v1`:
//   { accepted: boolean, ts: ISO, categories: { necessary, functional, analytics, marketing } }
//
// Trepic does not currently set any non-necessary cookies. The banner is
// presented because (a) some jurisdictions require an opt-out signal even
// for low-cookie sites, and (b) third-party tooling we may add later
// (analytics, marketing) should respect the same recorded preference.
(function () {
  "use strict";

  var STORAGE_KEY = "trepic_cookie_consent_v1";

  function readConsent() {
    try {
      var raw = window.localStorage.getItem(STORAGE_KEY);
      if (!raw) return null;
      return JSON.parse(raw);
    } catch (e) {
      return null;
    }
  }

  function writeConsent(payload) {
    try {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
    } catch (e) {
      /* ignore quota / privacy-mode errors */
    }
    // Fire a custom event so other site code can react to the choice.
    try {
      window.dispatchEvent(new CustomEvent("trepic:consent", { detail: payload }));
    } catch (e) { /* IE — not supported */ }
  }

  function makeChoice(opts) {
    return {
      accepted: !!opts.accepted,
      ts: new Date().toISOString(),
      categories: {
        necessary: true,
        functional: !!opts.functional,
        analytics: !!opts.analytics,
        marketing: !!opts.marketing,
      },
    };
  }

  // Hide the banner once a choice is recorded.
  if (readConsent()) return;

  // Inject styles once.
  function injectStyles() {
    if (document.getElementById("trepic-cookie-banner-styles")) return;
    var s = document.createElement("style");
    s.id = "trepic-cookie-banner-styles";
    s.textContent = [
      ".tcb-root { position: fixed; left: 16px; right: 16px; bottom: 16px; z-index: 9999;",
      "  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif;",
      "  color: #292420; }",
      ".tcb-card { max-width: 720px; margin: 0 auto; background: #FAF9F4;",
      "  border: 1px solid #E2DDD2; border-radius: 12px; box-shadow: 0 12px 40px rgba(40,30,15,0.18);",
      "  padding: 22px 24px; display: flex; flex-direction: column; gap: 14px; }",
      ".tcb-h { font-family: 'Cormorant Infant', 'Cormorant Garamond', Georgia, serif;",
      "  font-weight: 500; font-size: 22px; line-height: 1.2; margin: 0; color: #292420; }",
      ".tcb-h em { font-style: italic; color: #b28b43; }",
      ".tcb-p { font-size: 14px; line-height: 1.55; margin: 0; color: #756E66; }",
      ".tcb-p a { color: #b28b43; text-decoration: underline; text-underline-offset: 2px; }",
      ".tcb-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; }",
      ".tcb-btn { font-family: inherit; font-size: 13px; font-weight: 500; letter-spacing: 0.02em;",
      "  padding: 10px 18px; border-radius: 999px; border: 1px solid #C9C2B5; background: transparent;",
      "  color: #292420; cursor: pointer; transition: all 160ms ease; }",
      ".tcb-btn:hover { border-color: #292420; }",
      ".tcb-btn-primary { background: #292420; color: #FAF9F4; border-color: #292420; }",
      ".tcb-btn-primary:hover { background: #b28b43; border-color: #b28b43; }",
      ".tcb-btn-link { background: transparent; border: none; color: #756E66; text-decoration: underline;",
      "  text-underline-offset: 3px; padding: 6px 8px; }",
      ".tcb-btn-link:hover { color: #292420; }",
      ".tcb-prefs { display: none; flex-direction: column; gap: 10px; padding: 12px 0 4px;",
      "  border-top: 1px solid #E2DDD2; margin-top: 4px; }",
      ".tcb-prefs.open { display: flex; }",
      ".tcb-pref { display: flex; align-items: flex-start; gap: 12px; padding: 8px 0; }",
      ".tcb-pref label { font-size: 13px; color: #292420; font-weight: 500; }",
      ".tcb-pref small { display: block; color: #756E66; font-weight: 400; margin-top: 2px; line-height: 1.5; }",
      ".tcb-pref input { margin-top: 3px; accent-color: #b28b43; }",
      ".tcb-pref input:disabled + label { color: #756E66; }",
      "@media (max-width: 540px) { .tcb-row { justify-content: stretch; } .tcb-btn { flex: 1 1 auto; text-align: center; } }",
    ].join("\n");
    document.head.appendChild(s);
  }

  function render() {
    injectStyles();
    var root = document.createElement("div");
    root.className = "tcb-root";
    root.setAttribute("role", "dialog");
    root.setAttribute("aria-live", "polite");
    root.setAttribute("aria-label", "Cookie preferences");
    root.innerHTML = [
      '<div class="tcb-card">',
      '  <h2 class="tcb-h">A note on <em>cookies</em></h2>',
      '  <p class="tcb-p">Trepic uses only the cookies and storage strictly necessary to make this site work — we don\'t run analytics, advertising, or third-party tracking on the public site. You can review the details or opt out of any non-essential category we may add in the future. See our <a href="/cookies/">Cookie Policy</a> and <a href="/privacy/">Privacy Policy</a>.</p>',
      '  <div class="tcb-prefs" id="tcb-prefs">',
      '    <div class="tcb-pref">',
      '      <input type="checkbox" id="tcb-c-necessary" checked disabled />',
      '      <div><label for="tcb-c-necessary">Strictly necessary</label><small>Required for the site and its admin tools to function. Always on.</small></div>',
      '    </div>',
      '    <div class="tcb-pref">',
      '      <input type="checkbox" id="tcb-c-functional" />',
      '      <div><label for="tcb-c-functional">Functional</label><small>Remembers preferences (language, banner choice). Currently none used beyond the strictly-necessary banner-choice itself.</small></div>',
      '    </div>',
      '    <div class="tcb-pref">',
      '      <input type="checkbox" id="tcb-c-analytics" />',
      '      <div><label for="tcb-c-analytics">Analytics</label><small>Helps us understand how the site is used (privacy-respecting, aggregate). Currently off — we don\'t run analytics on the public site.</small></div>',
      '    </div>',
      '    <div class="tcb-pref">',
      '      <input type="checkbox" id="tcb-c-marketing" />',
      '      <div><label for="tcb-c-marketing">Marketing</label><small>Cross-context behavioural advertising. Currently off — we don\'t do this.</small></div>',
      '    </div>',
      '  </div>',
      '  <div class="tcb-row">',
      '    <button type="button" class="tcb-btn-link" id="tcb-customize">Customize</button>',
      '    <button type="button" class="tcb-btn" id="tcb-reject">Reject all</button>',
      '    <button type="button" class="tcb-btn tcb-btn-primary" id="tcb-accept">Accept all</button>',
      '  </div>',
      '</div>',
    ].join("");

    document.body.appendChild(root);

    function dismiss(payload) {
      writeConsent(payload);
      if (root && root.parentNode) root.parentNode.removeChild(root);
    }

    var prefs = root.querySelector("#tcb-prefs");
    var btnCustomize = root.querySelector("#tcb-customize");
    var btnReject = root.querySelector("#tcb-reject");
    var btnAccept = root.querySelector("#tcb-accept");
    var saveBtn = null;

    btnCustomize.addEventListener("click", function () {
      var open = prefs.classList.toggle("open");
      btnCustomize.textContent = open ? "Hide details" : "Customize";
      // Replace "Accept all" with "Save preferences" while customizing
      if (open && !saveBtn) {
        btnAccept.textContent = "Save preferences";
        btnAccept.dataset.mode = "save";
      } else if (!open) {
        btnAccept.textContent = "Accept all";
        delete btnAccept.dataset.mode;
      }
    });

    btnReject.addEventListener("click", function () {
      dismiss(makeChoice({ accepted: false, functional: false, analytics: false, marketing: false }));
    });

    btnAccept.addEventListener("click", function () {
      if (btnAccept.dataset.mode === "save") {
        dismiss(makeChoice({
          accepted: true,
          functional: !!root.querySelector("#tcb-c-functional").checked,
          analytics: !!root.querySelector("#tcb-c-analytics").checked,
          marketing: !!root.querySelector("#tcb-c-marketing").checked,
        }));
      } else {
        dismiss(makeChoice({ accepted: true, functional: true, analytics: true, marketing: true }));
      }
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", render);
  } else {
    render();
  }

  // Public API for site code that wants to read the choice or open prefs again.
  window.TrepicConsent = {
    get: readConsent,
    reset: function () {
      try { window.localStorage.removeItem(STORAGE_KEY); } catch (e) {}
      render();
    },
  };
})();
