(() => {
  "use strict";
  const configNode = document.getElementById("apuProjectFooterConfig");
  if (!configNode || document.getElementById("apuProjectFooter")) return;
  let config = {};
  try { config = JSON.parse(configNode.textContent || "{}"); } catch (_) {}

  const words = {
    en:{kicker:"Standalone Cloudflare project",copy:"One focused system presented as a responsive, installable, Cloudflare Pages-ready standalone website.",visitors:"Unique visitors:",fallback:"active after D1 is configured",privacy:"Privacy Policy",terms:"Terms of Service",cookies:"Cookie settings",nav:"Legal and privacy links"},
    id:{kicker:"Proyek Cloudflare mandiri",copy:"Satu sistem terfokus yang disajikan sebagai situs mandiri responsif, dapat diinstal, dan siap untuk Cloudflare Pages.",visitors:"Pengunjung unik:",fallback:"aktif setelah D1 dikonfigurasi",privacy:"Kebijakan Privasi",terms:"Persyaratan Layanan",cookies:"Pengaturan cookie",nav:"Tautan hukum dan privasi"},
    ms:{kicker:"Projek Cloudflare kendiri",copy:"Satu sistem terfokus yang dipersembahkan sebagai laman kendiri responsif, boleh dipasang dan sedia untuk Cloudflare Pages.",visitors:"Pelawat unik:",fallback:"aktif selepas D1 dikonfigurasi",privacy:"Dasar Privasi",terms:"Persyaratan Perkhidmatan",cookies:"Tetapan kuki",nav:"Pautan undang-undang dan privasi"},
    de:{kicker:"Eigenständiges Cloudflare-Projekt",copy:"Ein fokussiertes System als responsive, installierbare und für Cloudflare Pages vorbereitete eigenständige Website.",visitors:"Eindeutige Besucher:",fallback:"nach der D1-Konfiguration aktiv",privacy:"Datenschutz",terms:"Nutzungsbedingungen",cookies:"Cookie-Einstellungen",nav:"Rechtliche Hinweise und Datenschutz"},
    vi:{kicker:"Dự án Cloudflare độc lập",copy:"Một hệ thống tập trung được trình bày dưới dạng trang web độc lập, đáp ứng, có thể cài đặt và sẵn sàng cho Cloudflare Pages.",visitors:"Khách truy cập duy nhất:",fallback:"hoạt động sau khi cấu hình D1",privacy:"Chính sách quyền riêng tư",terms:"Điều khoản dịch vụ",cookies:"Cài đặt cookie",nav:"Liên kết pháp lý và quyền riêng tư"},
    zh:{kicker:"独立 Cloudflare 项目",copy:"一个专注的系统，以响应式、可安装并适用于 Cloudflare Pages 的独立网站形式呈现。",visitors:"独立访客：",fallback:"配置 D1 后启用",privacy:"隐私政策",terms:"服务条款",cookies:"Cookie 设置",nav:"法律与隐私链接"},
    ja:{kicker:"独立Cloudflareプロジェクト",copy:"一つのシステムを、レスポンシブでインストール可能なCloudflare Pages対応の独立サイトとして提供します。",visitors:"ユニーク訪問者：",fallback:"D1設定後に有効",privacy:"プライバシーポリシー",terms:"利用規約",cookies:"Cookie設定",nav:"法的情報とプライバシーリンク"}
  };

  function language(){
    const raw = document.documentElement.dataset.apuLanguage || document.documentElement.lang || localStorage.getItem("apu-ui-language") || "en";
    const code = String(raw).toLowerCase().split("-")[0];
    return words[code] ? code : "en";
  }
  function esc(value){return String(value ?? "").replace(/[&<>\"']/g, ch => ({"&":"&amp;","<":"&lt;",">":"&gt;",'\"':"&quot;","'":"&#039;"}[ch]));}

  function hideLegacyFooters(root=document){
    root.querySelectorAll?.("footer:not(#apuProjectFooter)").forEach(node => {
      node.dataset.apuFooterReplaced = "true";
      node.setAttribute("aria-hidden","true");
    });
  }

  function build(){
    hideLegacyFooters();
    const footer = document.createElement("footer");
    footer.id = "apuProjectFooter";
    footer.className = "apu-project-footer";
    footer.setAttribute("role","contentinfo");
    footer.style.setProperty("--apu-footer-accent", config.accent || "#ffd94d");
    const compact = ((config.line1 || "").length > 16 || (config.line2 || "").length > 18) ? "true" : "false";
    footer.innerHTML = `<span class="apu-project-footer__glow" aria-hidden="true"></span><div class="apu-project-footer__inner"><div class="apu-project-footer__brand" data-compact="${compact}"><p class="apu-project-footer__code"><span>${esc(config.code || "PROJECT")}</span> · <span data-apu-footer-text="kicker"></span></p><p class="apu-project-footer__logo" aria-label="${esc((config.line1 || "") + " " + (config.line2 || ""))}"><span>${esc(config.line1 || document.title)}</span><span class="apu-project-footer__logo-accent">${esc(config.line2 || "")}</span></p></div><div class="apu-project-footer__copy"><p class="apu-project-footer__description" data-apu-footer-text="copy"></p><p class="apu-project-footer__visitor"><span class="apu-project-footer__visitor-mark" aria-hidden="true"></span><span data-apu-footer-text="visitors"></span><strong data-visitor-count data-apu-footer-visitor data-visitor-fallback=""></strong></p><nav class="apu-project-footer__links" data-apu-footer-nav aria-label=""><a href="/privacy.html" data-apu-footer-text="privacy"></a><a href="/terms.html" data-apu-footer-text="terms"></a><button type="button" data-cookie-settings data-apu-footer-text="cookies"></button></nav></div><div class="apu-project-footer__symbols" aria-hidden="true"><span>★</span><span>∞</span><span>◉</span><span>✦</span></div></div></footer>`;
    document.body.appendChild(footer);
    const reserve = document.createElement("div");
    reserve.id = "apuProjectFooterReserve";
    reserve.className = "apu-project-footer__reserve";
    reserve.setAttribute("aria-hidden","true");
    document.body.appendChild(reserve);
    updateLanguage();
    syncCookieReserve();
  }

  function updateLanguage(){
    const dict = words[language()];
    document.querySelectorAll("[data-apu-footer-text]").forEach(node => {
      const key = node.dataset.apuFooterText;
      if (dict[key]) node.textContent = dict[key];
    });
    const counter = document.querySelector("[data-apu-footer-visitor]");
    if (counter && (!counter.textContent.trim() || counter.dataset.counterState === "unconfigured" || counter.dataset.counterState === "offline")) counter.textContent = dict.fallback;
    if (counter) counter.dataset.visitorFallback = dict.fallback;
    const nav = document.querySelector("[data-apu-footer-nav]");
    if (nav) nav.setAttribute("aria-label",dict.nav);
  }

  function syncCookieReserve(){
    const panel = document.getElementById("apuCookiePanel");
    const reserve = document.getElementById("apuProjectFooterReserve");
    if (!reserve) return;
    const visible = Boolean(panel && !panel.hidden && getComputedStyle(panel).display !== "none");
    reserve.style.height = visible ? `${Math.ceil(panel.getBoundingClientRect().height + 30)}px` : "0px";
  }

  if (document.body) build(); else document.addEventListener("DOMContentLoaded",build,{once:true});
  const observer = new MutationObserver(records => {
    records.forEach(record => record.addedNodes.forEach(node => {
      if (node.nodeType === 1) hideLegacyFooters(node.matches?.("footer") ? node.parentElement || document : node);
    }));
    if (!document.getElementById("apuProjectFooter") && document.body) build();
    syncCookieReserve();
  });
  observer.observe(document.documentElement,{subtree:true,childList:true,attributes:true,attributeFilter:["lang","data-apu-language","hidden"]});
  window.addEventListener("resize",syncCookieReserve,{passive:true});
  window.addEventListener("apu:viewer-language-change",updateLanguage);
  window.addEventListener("apu:front-language-change",updateLanguage);
  document.addEventListener("change",event => { if (event.target.matches?.("select")) setTimeout(updateLanguage,0); });
})();
