(function () {
  const STORAGE_KEY = "sikompro-theme";
  const BG_STORAGE_KEY = "sikompro-bg";
  const root = document.documentElement;

  const palettes = {
    light: {
      ocean: {
        label: "Ocean",
        dot: "#38bdf8",
        pageTop: "#f8fcff",
        pageBottom: "#edf5ff",
        pageAccent: "rgba(56,189,248,.14)",
        surface: "#f8fbff",
        surfaceAlt: "#eef4fb",
        sidebar: "#0f2742",
        sidebarSoft: "#152d4d",
        ink: "#10233d",
        muted: "#64748b",
        line: "#dbe7f5",
      },
      mint: {
        label: "Mint",
        dot: "#34d399",
        pageTop: "#f7fffb",
        pageBottom: "#ebf8f2",
        pageAccent: "rgba(52,211,153,.16)",
        surface: "#f8fffc",
        surfaceAlt: "#edf8f2",
        sidebar: "#12353a",
        sidebarSoft: "#184b50",
        ink: "#12322f",
        muted: "#5f766f",
        line: "#d5e9e1",
      },
      amber: {
        label: "Amber",
        dot: "#f59e0b",
        pageTop: "#fffaf1",
        pageBottom: "#fdf3df",
        pageAccent: "rgba(245,158,11,.16)",
        surface: "#fffdf8",
        surfaceAlt: "#f7efdf",
        sidebar: "#3a2a0f",
        sidebarSoft: "#584011",
        ink: "#3b2b10",
        muted: "#76684d",
        line: "#eadac0",
      },
      rose: {
        label: "Rose",
        dot: "#fb7185",
        pageTop: "#fff7f9",
        pageBottom: "#fdeff3",
        pageAccent: "rgba(251,113,133,.15)",
        surface: "#fff9fb",
        surfaceAlt: "#f8ecf0",
        sidebar: "#3a1523",
        sidebarSoft: "#562036",
        ink: "#3c1726",
        muted: "#7b5a66",
        line: "#edd6df",
      },
      graphite: {
        label: "Graphite",
        dot: "#94a3b8",
        pageTop: "#f7f9fc",
        pageBottom: "#edf2f7",
        pageAccent: "rgba(148,163,184,.15)",
        surface: "#fbfdff",
        surfaceAlt: "#eef3f9",
        sidebar: "#263244",
        sidebarSoft: "#344255",
        ink: "#1f2d3d",
        muted: "#64748b",
        line: "#dbe4ee",
      },
      violet: {
        label: "Violet",
        dot: "#8b5cf6",
        pageTop: "#fbf9ff",
        pageBottom: "#f0ebff",
        pageAccent: "rgba(139,92,246,.16)",
        surface: "#fcfbff",
        surfaceAlt: "#f0ebff",
        sidebar: "#2c204c",
        sidebarSoft: "#3b2f61",
        ink: "#24183f",
        muted: "#685f86",
        line: "#ded6f8",
      },
    },
    dark: {
      ocean: {
        label: "Ocean",
        dot: "#38bdf8",
        pageTop: "#06111f",
        pageBottom: "#0b1730",
        pageAccent: "rgba(56,189,248,.18)",
        surface: "rgba(8,15,28,.92)",
        surfaceAlt: "rgba(15,23,42,.88)",
        sidebar: "#040e26",
        sidebarSoft: "#0a1730",
        ink: "#eef5ff",
        muted: "#c9d8ee",
        line: "rgba(148,163,184,.16)",
      },
      mint: {
        label: "Mint",
        dot: "#34d399",
        pageTop: "#041713",
        pageBottom: "#081e1a",
        pageAccent: "rgba(52,211,153,.16)",
        surface: "rgba(8,20,17,.92)",
        surfaceAlt: "rgba(13,30,24,.88)",
        sidebar: "#041411",
        sidebarSoft: "#0b211b",
        ink: "#ecfff7",
        muted: "#c8e6db",
        line: "rgba(120,200,170,.16)",
      },
      amber: {
        label: "Amber",
        dot: "#f59e0b",
        pageTop: "#140d04",
        pageBottom: "#221507",
        pageAccent: "rgba(245,158,11,.14)",
        surface: "rgba(25,16,6,.92)",
        surfaceAlt: "rgba(38,25,10,.88)",
        sidebar: "#150d03",
        sidebarSoft: "#271707",
        ink: "#fff7ea",
        muted: "#f1dcb1",
        line: "rgba(245,158,11,.16)",
      },
      rose: {
        label: "Rose",
        dot: "#fb7185",
        pageTop: "#16070d",
        pageBottom: "#220b14",
        pageAccent: "rgba(251,113,133,.14)",
        surface: "rgba(25,8,15,.92)",
        surfaceAlt: "rgba(38,13,24,.88)",
        sidebar: "#17040a",
        sidebarSoft: "#2a0a17",
        ink: "#fff1f5",
        muted: "#efc6d0",
        line: "rgba(251,113,133,.16)",
      },
      graphite: {
        label: "Graphite",
        dot: "#94a3b8",
        pageTop: "#07111d",
        pageBottom: "#0f172a",
        pageAccent: "rgba(148,163,184,.16)",
        surface: "rgba(8,15,28,.92)",
        surfaceAlt: "rgba(15,23,42,.88)",
        sidebar: "#040b17",
        sidebarSoft: "#0b1424",
        ink: "#eef5ff",
        muted: "#c9d8ee",
        line: "rgba(148,163,184,.16)",
      },
      violet: {
        label: "Violet",
        dot: "#8b5cf6",
        pageTop: "#0d081c",
        pageBottom: "#18112d",
        pageAccent: "rgba(139,92,246,.16)",
        surface: "rgba(16,11,33,.92)",
        surfaceAlt: "rgba(28,18,52,.88)",
        sidebar: "#0b0820",
        sidebarSoft: "#1a1236",
        ink: "#f7f3ff",
        muted: "#d9ccff",
        line: "rgba(139,92,246,.16)",
      },
    },
  };

  const defaultPalette = {
    light: "ocean",
    dark: "ocean",
  };

  let paletteDockNode = null;
  let paletteDropupBound = false;

  function getPreferredTheme() {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved === "light" || saved === "dark") {
      return saved;
    }
    return window.matchMedia &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
  }

  function getPreferredPalette(theme) {
    const saved = localStorage.getItem(BG_STORAGE_KEY);
    if (saved && palettes[theme] && palettes[theme][saved]) {
      return saved;
    }
    return defaultPalette[theme] || "ocean";
  }

  function syncThemeColor(theme) {
    const meta = document.querySelector('meta[name="theme-color"]');
    if (!meta) return;
    meta.setAttribute("content", theme === "dark" ? "#0b1220" : "#0f2742");
  }

  function syncColorScheme(theme) {
    document.documentElement.style.colorScheme = theme;
    if (document.body) {
      document.body.style.colorScheme = theme;
    }
  }

  function applyAppearance(theme, paletteKey) {
    const palette =
      palettes[theme]?.[paletteKey] ||
      palettes[theme]?.[defaultPalette[theme]] ||
      palettes.light.ocean;
    const variables = {
      "--sikompro-page-bg-top": palette.pageTop,
      "--sikompro-page-bg-bottom": palette.pageBottom,
      "--sikompro-page-bg-accent": palette.pageAccent,
      "--sikompro-surface": palette.surface,
      "--sikompro-surface-alt": palette.surfaceAlt,
      "--sikompro-sidebar-bg": palette.sidebar,
      "--sikompro-sidebar-soft": palette.sidebarSoft,
      "--sikompro-ink": palette.ink,
      "--sikompro-muted": palette.muted,
      "--sikompro-line": palette.line,
      "--sikompro-accent-dot": palette.dot,
    };

    Object.entries(variables).forEach(([key, value]) => {
      root.style.setProperty(key, value);
    });

    if (document.body) {
      document.body.dataset.bg = paletteKey;
    }
    root.dataset.bg = paletteKey;
  }

  function emitAppearanceChange(theme, paletteKey) {
    document.dispatchEvent(
      new CustomEvent("sikompro:appearancechange", {
        detail: { theme, palette: paletteKey },
      }),
    );
  }

  function setPalette(theme, paletteKey, persist = true) {
    const next =
      palettes[theme] && palettes[theme][paletteKey]
        ? paletteKey
        : defaultPalette[theme] || "ocean";
    if (persist) {
      localStorage.setItem(BG_STORAGE_KEY, next);
    }
    applyAppearance(theme, next);
    updatePaletteButtons(theme, next);
    emitAppearanceChange(theme, next);
  }

  function updatePaletteButtons(theme, activePalette) {
    document.querySelectorAll("[data-bg-choice]").forEach((button) => {
      const isActive = button.getAttribute("data-bg-choice") === activePalette;
      button.classList.toggle("is-active", isActive);
      button.setAttribute("aria-pressed", isActive ? "true" : "false");
      button.title = `${palettes[theme]?.[button.getAttribute("data-bg-choice")]?.label || button.getAttribute("data-bg-choice")} background`;
    });
  }

  function setTheme(theme) {
    root.setAttribute("data-theme", theme);
    document.body?.setAttribute("data-theme", theme);
    localStorage.setItem(STORAGE_KEY, theme);
    syncThemeColor(theme);
    syncColorScheme(theme);
    setPalette(theme, getPreferredPalette(theme), false);
    const iconClass = document.body?.classList.contains("auth-page")
      ? "fa-solid fa-circle-half-stroke"
      : "fa fa-adjust";

    document.querySelectorAll("[data-theme-toggle]").forEach((button) => {
      const icon = button.querySelector("[data-theme-toggle-icon]");
      const label = button.querySelector("[data-theme-toggle-label]");
      const activeLabel = theme === "dark" ? "Mode Malam" : "Mode Siang";
      const next = theme === "dark" ? "Siang" : "Malam";
      if (icon) {
        icon.className = iconClass;
      }
      if (label) label.textContent = activeLabel;
      button.setAttribute("aria-label", `Ganti ke mode ${next.toLowerCase()}`);
      button.setAttribute("title", `Ganti ke mode ${next.toLowerCase()}`);
      button.setAttribute("aria-pressed", theme === "dark" ? "true" : "false");
    });
  }

  function injectPaletteDock() {
    if (!document.body || !document.body.classList.contains("dashboard-shell"))
      return;
    const theme = root.getAttribute("data-theme") === "dark" ? "dark" : "light";
    const activePalette = getPreferredPalette(theme);
    const container =
      document.querySelector(".main-sidebar .nav-sidebar") ||
      document.querySelector(".main-sidebar .sidebar") ||
      document.querySelector(
        ".navbar-nav.ml-auto, .navbar-nav.ms-auto, .navbar-nav",
      );
    if (!container) return;

    if (!paletteDockNode) {
      const paletteList = Object.entries(palettes[theme])
        .map(
          ([key, palette]) =>
            `<button type="button" class="theme-palette-chip${key === activePalette ? " is-active" : ""}" data-bg-choice="${key}" aria-pressed="${key === activePalette ? "true" : "false"}" title="${palette.label}">
                  <span class="theme-palette-dot" style="background:${palette.dot}"></span>
                  <span class="theme-palette-label">${palette.label}</span>
              </button>`,
        )
        .join("");

      const wrap = document.createElement("div");
      wrap.className = "theme-palette-dock theme-palette-dropup";
      wrap.setAttribute("data-bg-picker", "");
      wrap.innerHTML = `
              <button type="button" class="theme-palette-toggle" data-theme-palette-toggle aria-expanded="false">
                  <span class="theme-palette-caption">Background</span>
                  <i class="fa fa-caret-down" aria-hidden="true"></i>
              </button>
              <div class="theme-palette-content dropdown-content">
                  <div class="theme-palette-list">${paletteList}</div>
              </div>
          `;

      const li = document.createElement("li");
      li.className = "nav-item theme-palette-nav";
      li.appendChild(wrap);
      paletteDockNode = li;
    }

    if (!paletteDropupBound) {
      document.addEventListener(
        "click",
        function (event) {
          const toggle = event.target.closest("[data-theme-palette-toggle]");
          if (toggle) {
            event.preventDefault();
            event.stopPropagation();

            const dock = toggle.closest(".theme-palette-dropup");
            const isOpen = dock.classList.contains("is-open");
            document
              .querySelectorAll(".theme-palette-dropup.is-open")
              .forEach((node) => {
                if (node !== dock) {
                  node.classList.remove("is-open");
                  const otherToggle = node.querySelector(
                    "[data-theme-palette-toggle]",
                  );
                  if (otherToggle) {
                    otherToggle.setAttribute("aria-expanded", "false");
                  }
                }
              });

            dock.classList.toggle("is-open", !isOpen);
            toggle.setAttribute("aria-expanded", (!isOpen).toString());
            return;
          }

          if (!event.target.closest(".theme-palette-dropup")) {
            document
              .querySelectorAll(".theme-palette-dropup.is-open")
              .forEach((node) => {
                node.classList.remove("is-open");
                const otherToggle = node.querySelector(
                  "[data-theme-palette-toggle]",
                );
                if (otherToggle) {
                  otherToggle.setAttribute("aria-expanded", "false");
                }
              });
          }
        },
        true,
      );
      paletteDropupBound = true;
    }

    if (paletteDockNode.parentElement !== container) {
      paletteDockNode.remove();
      const inputItem = container.querySelector(
        'a[href*="input_komplain"], a[href="input_komplain_admin.php"]',
      );
      const inputNavItem = inputItem ? inputItem.closest(".nav-item") : null;
      if (inputNavItem && inputNavItem.parentElement === container) {
        inputNavItem.insertAdjacentElement("afterend", paletteDockNode);
      } else {
        container.insertBefore(paletteDockNode, container.firstChild);
      }
    }
  }

  function injectPersistentMenuButton() {
    if (!document.body || !document.body.classList.contains("dashboard-shell"))
      return;
    if (document.querySelector('[data-widget="pushmenu"]')) return;
    if (document.querySelector(".dashboard-menu-fab")) return;
    if (window.matchMedia && window.matchMedia("(min-width: 992px)").matches)
      return;

    const button = document.createElement("button");
    button.type = "button";
    button.className = "dashboard-menu-fab";
    button.setAttribute("aria-label", "Buka menu");
    button.setAttribute("title", "Buka menu");
    button.innerHTML = '<i class="fa fa-bars" aria-hidden="true"></i>';

    button.addEventListener("click", function () {
      const pushmenu = document.querySelector('[data-widget="pushmenu"]');
      if (pushmenu) {
        pushmenu.click();
        return;
      }

      document.body.classList.toggle("sidebar-open");
      document.body.classList.toggle("sidebar-collapse");
    });

    document.body.appendChild(button);
  }

  function injectDesktopSidebarToggle() {
    if (!document.body || !document.body.classList.contains("dashboard-shell"))
      return;
    if (window.matchMedia && window.matchMedia("(max-width: 991.98px)").matches)
      return;
    if (document.querySelector(".dashboard-sidebar-toggle-inline")) return;

    const nav =
      document.querySelector(".main-header .navbar-nav:first-child") ||
      document.querySelector(".main-header .navbar-nav");
    if (!nav) return;

    const li = document.createElement("li");
    li.className = "nav-item d-none d-lg-flex align-items-center me-2";
    li.innerHTML = `
      <button type="button" class="dashboard-sidebar-toggle-inline" aria-label="Collapse Sidebar" title="Collapse Sidebar">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </button>
    `;
    li.querySelector("button").addEventListener("click", function () {
      toggleSidebarMenu();
    });

    nav.insertBefore(li, nav.firstChild);
  }

  function injectBackButton() {
    if (!document.body || !document.body.classList.contains("dashboard-shell"))
      return;
    if (
      window.location.pathname.endsWith("/dashboard.php") ||
      window.location.pathname.endsWith("/teknisi.php")
    ) {
      return;
    }
    if (window.location.pathname.includes("/cetak_")) return;
    if (document.querySelector(".dashboard-back-button")) return;
    if (document.querySelector('a[href*="dashboard.php"].btn, a[href*="dashboard.php"].btn-outline-secondary, a[href*="dashboard.php"].btn-light')) {
      return;
    }

    const target =
      document.querySelector(".content-wrapper .container-fluid") ||
      document.querySelector(".content-wrapper");
    if (!target) return;

    const back = document.createElement("a");
    back.href = "dashboard.php";
    back.className = "dashboard-back-button";
    back.innerHTML = '<i class="fa fa-arrow-left" aria-hidden="true"></i><span>Kembali</span>';
    target.insertAdjacentElement("afterbegin", back);
  }

  function toggleSidebarMenu() {
    if (!document.body) return;

    const isOpen = document.body.classList.contains("sidebar-open");
    document.body.classList.toggle("sidebar-open", !isOpen);
    document.body.classList.toggle("sidebar-collapse", isOpen);

    document.querySelectorAll('[data-widget="pushmenu"]').forEach((button) => {
      button.setAttribute("aria-expanded", (!isOpen).toString());
    });
  }

  function bindPushmenuToggle() {
    document.addEventListener(
      "click",
      function (event) {
        const button = event.target.closest('[data-widget="pushmenu"]');
        if (!button) return;

        event.preventDefault();
        event.stopPropagation();
        toggleSidebarMenu();
      },
      true,
    );
  }

  function syncDashboardSidebarState() {
    if (!document.body || !document.body.classList.contains("dashboard-shell"))
      return;
    const isMobile =
      window.matchMedia && window.matchMedia("(max-width: 767.98px)").matches;

    if (isMobile) {
      document.body.classList.add("sidebar-collapse");
      document.body.classList.remove("sidebar-open");
    } else {
      document.body.classList.remove("sidebar-collapse");
      document.body.classList.remove("sidebar-open");
    }
    injectPaletteDock();
  }

  const initialTheme = getPreferredTheme();
  setTheme(initialTheme);

  document.addEventListener("DOMContentLoaded", function () {
    setTheme(getPreferredTheme());
    syncDashboardSidebarState();
    bindPushmenuToggle();
    injectPersistentMenuButton();
    injectDesktopSidebarToggle();
    injectBackButton();
    injectPaletteDock();

    const buttons = document.querySelectorAll("[data-theme-toggle]");
    if (!buttons.length) {
      const floating = document.createElement("button");
      floating.type = "button";
      floating.className = "theme-fab";
      floating.setAttribute("data-theme-toggle", "");
      floating.innerHTML = document.body?.classList.contains("auth-page")
        ? '<i data-theme-toggle-icon class="fa-solid fa-circle-half-stroke"></i><span data-theme-toggle-label>Mode Malam</span>'
        : '<i data-theme-toggle-icon class="fa fa-adjust"></i><span data-theme-toggle-label>Mode Malam</span>';
      document.body.appendChild(floating);
    }

    document.body.addEventListener("click", function (event) {
      const button = event.target.closest("[data-theme-toggle]");
      if (!button) return;
      const current =
        root.getAttribute("data-theme") === "dark" ? "dark" : "light";
      setTheme(current === "dark" ? "light" : "dark");
    });

    document.body.addEventListener("click", function (event) {
      const button = event.target.closest("[data-bg-choice]");
      if (!button) return;
      const theme =
        root.getAttribute("data-theme") === "dark" ? "dark" : "light";
      const palette = button.getAttribute("data-bg-choice");
      setPalette(theme, palette, true);
      const dock = button.closest(".theme-palette-dropup");
      if (dock) {
        dock.classList.remove("is-open");
        const toggle = dock.querySelector("[data-theme-palette-toggle]");
        if (toggle) {
          toggle.setAttribute("aria-expanded", "false");
        }
      }
    });

    window.addEventListener(
      "resize",
      function () {
        syncDashboardSidebarState();
        injectPaletteDock();
      },
      { passive: true },
    );
  });
})();
