(() => {
  "use strict";
  const CONSENT_COOKIE = "apu_cookie_consent";
  const MAX_AGE = 60 * 60 * 24 * 180;

  function getCookie(name) {
    const prefix = `${encodeURIComponent(name)}=`;
    return document.cookie.split(";").map(v => v.trim()).find(v => v.startsWith(prefix))?.slice(prefix.length) || "";
  }
  function setConsent(value) {
    document.cookie = `${CONSENT_COOKIE}=${encodeURIComponent(value)}; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax; Secure`;
  }
  function clearConsent() {
    document.cookie = `${CONSENT_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Secure`;
  }
  function panelMarkup() {
    return `<section class="apu-cookie-panel" data-apu-contrast-lock="ink" id="apuCookiePanel" role="dialog" aria-labelledby="apuCookieTitle" aria-describedby="apuCookieCopy">
      <div>
        <p class="apu-cookie-panel__label">Privacy choice</p>
        <h2 id="apuCookieTitle">Allow cookies to continue</h2>
        <p id="apuCookieCopy">Website tetap dapat dilihat. Pilih cookie analitik untuk membantu menghitung pengunjung unik, atau lanjutkan hanya dengan cookie esensial. Baca <a href="/privacy.html">Kebijakan Privasi</a> dan <a href="/terms.html">Persyaratan Layanan</a>.</p>
      </div>
      <div class="apu-cookie-panel__actions">
        <button class="apu-cookie-allow" id="apuCookieAllow" type="button">Allow cookies & continue</button>
        <button class="apu-cookie-essential" id="apuCookieEssential" type="button">Essential only</button>
      </div>
    </section>`;
  }
  async function safeFetch(url, options = {}, timeoutMs = 3500) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try { return await fetch(url, {...options, signal: controller.signal}); }
    finally { clearTimeout(timer); }
  }
  function renderVisitorCount(nodes, data, state = "ready") {
    const hasTotal = Boolean(data?.configured) && Number.isFinite(Number(data?.total));
    const formatted = hasTotal ? new Intl.NumberFormat("id-ID").format(Number(data.total)) : null;
    nodes.forEach(node => {
      const compact = node.hasAttribute("data-visitor-count-compact");
      node.dataset.counterState = state;
      node.textContent = formatted ?? (compact ? "D1" : "aktif setelah D1 dikonfigurasi");
      node.title = formatted
        ? `${formatted} pengunjung unik tercatat`
        : "Hubungkan database Cloudflare D1 dengan binding VISITOR_DB untuk mengaktifkan penghitung global.";
    });
  }
  async function loadVisitorCount() {
    const nodes = [...document.querySelectorAll("[data-visitor-count]")];
    if (!nodes.length) return;
    nodes.forEach(node => { node.dataset.counterState = "loading"; });
    try {
      const response = await safeFetch("/api/visit", {headers:{Accept:"application/json"}, cache:"no-store"});
      if (!response.ok) throw new Error("counter unavailable");
      renderVisitorCount(nodes, await response.json());
    } catch (_) {
      nodes.forEach(node => {
        const compact = node.hasAttribute("data-visitor-count-compact");
        node.dataset.counterState = "unconfigured";
        node.textContent = compact ? "D1" : (node.dataset.visitorFallback || "aktif setelah D1 dikonfigurasi");
        node.title = "Hubungkan Cloudflare D1 dengan binding VISITOR_DB untuk mengaktifkan penghitung pengunjung unik.";
      });
    }
  }
  async function registerVisit() {
    try {
      await safeFetch("/api/visit", {method:"POST", headers:{"Content-Type":"application/json", Accept:"application/json"}, body:"{}", cache:"no-store"});
    } catch (_) {}
    loadVisitorCount();
  }
  function showPanel() {
    let panel = document.getElementById("apuCookiePanel");
    if (!panel) {
      document.body.insertAdjacentHTML("beforeend", panelMarkup());
      panel = document.getElementById("apuCookiePanel");
    }
    panel.hidden = false;
    document.getElementById("apuCookieAllow")?.focus({preventScroll:true});
  }
  function hidePanel() {
    const panel = document.getElementById("apuCookiePanel");
    if (panel) panel.hidden = true;
  }
  function bind() {
    if (!document.getElementById("apuCookiePanel")) document.body.insertAdjacentHTML("beforeend", panelMarkup());
    const consent = decodeURIComponent(getCookie(CONSENT_COOKIE));
    if (consent) hidePanel(); else showPanel();
    document.getElementById("apuCookieAllow")?.addEventListener("click", () => {
      setConsent("analytics"); hidePanel(); registerVisit();
    });
    document.getElementById("apuCookieEssential")?.addEventListener("click", () => {
      setConsent("essential"); hidePanel(); loadVisitorCount();
    });
    document.addEventListener("click", event => {
      const trigger = event.target.closest("[data-cookie-settings]");
      if (!trigger) return;
      event.preventDefault(); clearConsent(); showPanel();
    });
    if (consent === "analytics") registerVisit(); else loadVisitorCount();
  }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", bind, {once:true}); else bind();
})();
