(function () {
  const STORAGE_KEYS = {
    theme: "ka-nexus-theme",
    sidebar: "ka-nexus-sidebar-collapsed",
  };

  const chartInstances = [];

  function safeStorage(action, key, value) {
    try {
      if (action === "get") {
        return window.localStorage.getItem(key);
      }
      window.localStorage.setItem(key, value);
    } catch (error) {
      return null;
    }
    return null;
  }

  function getCssVar(name) {
    return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  }

  function escapeHtml(value) {
    return String(value)
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;");
  }

  function showToast(message, tone) {
    const stack =
      document.querySelector("[data-toast-stack]") ||
      createToastStack();
    const item = document.createElement("div");
    item.className = "toast-item reveal";

    const toneClass = tone || "primary";
    item.innerHTML = `
      <div class="flex items-start gap-3">
        <span class="metric-badge ${escapeHtml(toneClass)} !rounded-2xl !px-2.5 !py-1">${escapeHtml(
      toneClass.toUpperCase()
    )}</span>
        <div class="min-w-0">
          <p class="text-sm font-semibold text-[color:var(--text)]">Action completed</p>
          <p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(
            message
          )}</p>
        </div>
      </div>
    `;
    stack.appendChild(item);
    window.setTimeout(() => {
      item.remove();
    }, 3600);
  }

  function createToastStack() {
    const stack = document.createElement("div");
    stack.className = "toast-stack";
    stack.setAttribute("data-toast-stack", "true");
    document.body.appendChild(stack);
    return stack;
  }

  function applyTheme(theme) {
    const nextTheme = theme === "dark" ? "dark" : "light";
    document.documentElement.classList.toggle("dark", nextTheme === "dark");
    document.documentElement.setAttribute("data-theme", nextTheme);
    safeStorage("set", STORAGE_KEYS.theme, nextTheme);

    document.querySelectorAll("[data-theme-toggle]").forEach((button) => {
      const label = button.querySelector("[data-theme-label]");
      if (label) {
        label.textContent = nextTheme === "dark" ? "Light Mode" : "Dark Mode";
      }
    });

    document.dispatchEvent(
      new CustomEvent("ka:theme-changed", { detail: { theme: nextTheme } })
    );
  }

  function initTheme() {
    const storedTheme = safeStorage("get", STORAGE_KEYS.theme);
    const systemTheme = window.matchMedia &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
    applyTheme(storedTheme || systemTheme);

    document.querySelectorAll("[data-theme-toggle]").forEach((button) => {
      button.addEventListener("click", () => {
        const nextTheme = document.documentElement.classList.contains("dark")
          ? "light"
          : "dark";
        applyTheme(nextTheme);
      });
    });
  }

  function setSidebarCollapsed(collapsed) {
    document.body.classList.toggle("sidebar-collapsed", collapsed);
    safeStorage("set", STORAGE_KEYS.sidebar, collapsed ? "true" : "false");
  }

  function setMobileSidebarOpen(open) {
    document.body.classList.toggle("mobile-sidebar-open", open);
  }

  function initSidebar() {
    if (window.innerWidth >= 1024) {
      setSidebarCollapsed(safeStorage("get", STORAGE_KEYS.sidebar) === "true");
    }

    document
      .querySelectorAll("[data-sidebar-toggle]")
      .forEach((button) =>
        button.addEventListener("click", () => {
          setSidebarCollapsed(
            !document.body.classList.contains("sidebar-collapsed")
          );
        })
      );

    document
      .querySelectorAll("[data-mobile-sidebar-open]")
      .forEach((button) =>
        button.addEventListener("click", () => {
          setMobileSidebarOpen(true);
        })
      );

    document
      .querySelectorAll("[data-mobile-sidebar-close], [data-mobile-overlay]")
      .forEach((button) =>
        button.addEventListener("click", () => {
          setMobileSidebarOpen(false);
        })
      );

    document.querySelectorAll(".sidebar-shell a").forEach((link) => {
      link.addEventListener("click", () => {
        if (window.innerWidth < 1024) {
          setMobileSidebarOpen(false);
        }
      });
    });

    window.addEventListener("resize", () => {
      if (window.innerWidth < 1024) {
        document.body.classList.remove("sidebar-collapsed");
      } else {
        setMobileSidebarOpen(false);
        setSidebarCollapsed(safeStorage("get", STORAGE_KEYS.sidebar) === "true");
      }
    });

    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape") {
        setMobileSidebarOpen(false);
      }
    });
  }

  function initModals() {
    document.querySelectorAll("[data-modal-open]").forEach((button) => {
      button.addEventListener("click", () => {
        const id = button.getAttribute("data-modal-open");
        const modal = document.querySelector(`[data-modal="${id}"]`);
        if (modal) {
          modal.classList.remove("hidden");
        }
      });
    });

    document.querySelectorAll("[data-modal-close]").forEach((button) => {
      button.addEventListener("click", () => {
        const modal = button.closest("[data-modal]");
        if (modal) {
          modal.classList.add("hidden");
        }
      });
    });

    document.querySelectorAll("[data-modal]").forEach((modal) => {
      modal.addEventListener("click", (event) => {
        if (event.target === modal) {
          modal.classList.add("hidden");
        }
      });
    });
  }

  function initDrawers() {
    document.querySelectorAll("[data-drawer-open]").forEach((button) => {
      button.addEventListener("click", () => {
        const id = button.getAttribute("data-drawer-open");
        const drawer = document.querySelector(`[data-drawer="${id}"]`);
        if (drawer) {
          drawer.classList.remove("hidden");
        }
      });
    });

    document.querySelectorAll("[data-drawer-close]").forEach((button) => {
      button.addEventListener("click", () => {
        const drawer = button.closest("[data-drawer]");
        if (drawer) {
          drawer.classList.add("hidden");
        }
      });
    });

    document.querySelectorAll("[data-drawer]").forEach((drawer) => {
      drawer.addEventListener("click", (event) => {
        if (event.target === drawer) {
          drawer.classList.add("hidden");
        }
      });
    });
  }

  function parseSortValue(rawValue, type) {
    if (type === "number") {
      const cleaned = String(rawValue).replace(/[^0-9.-]/g, "");
      return Number.parseFloat(cleaned || "0");
    }

    if (type === "date") {
      return Date.parse(String(rawValue)) || 0;
    }

    return String(rawValue || "").toLowerCase();
  }

  function updateSelectionSummary(root) {
    const selected = root.querySelectorAll("[data-row-select]:checked");
    const bulkBar = root.querySelector("[data-bulk-bar]");
    const bulkCount = root.querySelector("[data-bulk-count]");

    if (bulkBar) {
      bulkBar.classList.toggle("hidden", selected.length === 0);
    }

    if (bulkCount) {
      bulkCount.textContent = String(selected.length);
    }
  }

  function buildPageButton(page, currentPage) {
    const active = page === currentPage;
    return `
      <button
        type="button"
        data-page-button="${page}"
        class="inline-flex h-10 min-w-10 items-center justify-center rounded-2xl border px-3 text-sm font-semibold transition ${
          active
            ? "border-transparent bg-blue-600 text-white shadow-lg shadow-blue-600/20"
            : "border-slate-200 bg-white/80 text-slate-600 hover:border-slate-300 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-300 dark:hover:border-slate-600 dark:hover:text-white"
        }"
      >
        ${page}
      </button>
    `;
  }

  function initDataTables() {
    document.querySelectorAll("[data-table-root]").forEach((root) => {
      const rows = Array.from(root.querySelectorAll("tbody tr[data-row]"));
      const searchInput = root.querySelector("[data-table-search]");
      const filters = Array.from(root.querySelectorAll("[data-table-filter]"));
      const selectAll = root.querySelector("[data-table-select-all]");
      const pagination = root.querySelector("[data-pagination]");
      const count = root.querySelector("[data-table-count]");
      const pageSize = Number.parseInt(root.dataset.pageSize || "6", 10);

      const state = {
        query: "",
        sortKey: root.dataset.sortKey || "",
        sortDir: root.dataset.sortDir || "asc",
        page: 1,
        filters: {},
      };

      function collectFilteredRows() {
        let filtered = rows.filter((row) => {
          const rowSearch = (row.dataset.search || "").toLowerCase();
          const matchesQuery = !state.query || rowSearch.includes(state.query);
          const matchesFilters = filters.every((filter) => {
            const key = filter.dataset.tableFilter;
            const value = state.filters[key];
            if (!value) {
              return true;
            }
            return String(row.dataset[key] || "")
              .toLowerCase()
              .includes(String(value).toLowerCase());
          });
          return matchesQuery && matchesFilters;
        });

        if (state.sortKey) {
          const button = root.querySelector(
            `[data-sort-key="${state.sortKey}"]`
          );
          const type = button ? button.dataset.sortType || "string" : "string";
          filtered = filtered.sort((left, right) => {
            const leftValue = parseSortValue(
              left.getAttribute(`data-sort-${state.sortKey}`),
              type
            );
            const rightValue = parseSortValue(
              right.getAttribute(`data-sort-${state.sortKey}`),
              type
            );
            if (leftValue < rightValue) {
              return state.sortDir === "asc" ? -1 : 1;
            }
            if (leftValue > rightValue) {
              return state.sortDir === "asc" ? 1 : -1;
            }
            return 0;
          });
        }

        return filtered;
      }

      function renderPagination(totalRows) {
        if (!pagination) {
          return;
        }

        const totalPages = Math.max(1, Math.ceil(totalRows / pageSize));
        state.page = Math.min(state.page, totalPages);
        const start = Math.max(1, state.page - 1);
        const end = Math.min(totalPages, start + 2);
        let buttons = "";

        for (let page = start; page <= end; page += 1) {
          buttons += buildPageButton(page, state.page);
        }

        pagination.innerHTML = `
          <button
            type="button"
            data-page-button="${Math.max(1, state.page - 1)}"
            class="inline-flex h-10 items-center justify-center rounded-2xl border border-slate-200 bg-white/80 px-4 text-sm font-semibold text-slate-600 transition hover:border-slate-300 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-300 dark:hover:border-slate-600 dark:hover:text-white"
          >
            Prev
          </button>
          ${buttons}
          <button
            type="button"
            data-page-button="${Math.min(totalPages, state.page + 1)}"
            class="inline-flex h-10 items-center justify-center rounded-2xl border border-slate-200 bg-white/80 px-4 text-sm font-semibold text-slate-600 transition hover:border-slate-300 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-300 dark:hover:border-slate-600 dark:hover:text-white"
          >
            Next
          </button>
        `;
      }

      function syncRows() {
        const filtered = collectFilteredRows();
        const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
        state.page = Math.min(state.page, totalPages);

        rows.forEach((row) => row.classList.add("is-hidden"));
        const startIndex = (state.page - 1) * pageSize;
        filtered
          .slice(startIndex, startIndex + pageSize)
          .forEach((row) => row.classList.remove("is-hidden"));

        if (count) {
          count.textContent = `${filtered.length} records`;
        }

        if (selectAll) {
          selectAll.checked = false;
        }

        renderPagination(filtered.length);
        updateSelectionSummary(root);

        root.querySelectorAll("[data-sort-key]").forEach((button) => {
          const icon = button.querySelector("[data-sort-indicator]");
          const isActive = button.dataset.sortKey === state.sortKey;
          if (icon) {
            icon.textContent = isActive
              ? state.sortDir === "asc"
                ? "â†‘"
                : "â†“"
              : "â†•";
          }
        });
      }

      if (searchInput) {
        searchInput.addEventListener("input", (event) => {
          state.query = event.target.value.trim().toLowerCase();
          state.page = 1;
          syncRows();
        });
      }

      filters.forEach((filter) => {
        filter.addEventListener("change", () => {
          state.filters[filter.dataset.tableFilter] = filter.value;
          state.page = 1;
          syncRows();
        });
      });

      root.querySelectorAll("[data-sort-key]").forEach((button) => {
        button.addEventListener("click", () => {
          const key = button.dataset.sortKey;
          if (state.sortKey === key) {
            state.sortDir = state.sortDir === "asc" ? "desc" : "asc";
          } else {
            state.sortKey = key;
            state.sortDir = "asc";
          }
          syncRows();
        });
      });

      if (pagination) {
        pagination.addEventListener("click", (event) => {
          const target = event.target.closest("[data-page-button]");
          if (!target) {
            return;
          }
          state.page = Number.parseInt(target.dataset.pageButton, 10) || 1;
          syncRows();
        });
      }

      if (selectAll) {
        selectAll.addEventListener("change", () => {
          rows
            .filter((row) => !row.classList.contains("is-hidden"))
            .forEach((row) => {
              const checkbox = row.querySelector("[data-row-select]");
              if (checkbox) {
                checkbox.checked = selectAll.checked;
              }
            });
          updateSelectionSummary(root);
        });
      }

      root.addEventListener("change", (event) => {
        if (event.target.matches("[data-row-select]")) {
          updateSelectionSummary(root);
        }
      });

      root.addEventListener("click", (event) => {
        const action = event.target.closest("[data-bulk-action]");
        if (!action) {
          return;
        }
        showToast(
          action.getAttribute("data-bulk-action") || "Bulk action completed",
          "primary"
        );
      });

      syncRows();
    });
  }

  function deepClone(value) {
    return JSON.parse(JSON.stringify(value));
  }

  function resolveThemeToken(token) {
    const tokens = {
      primary: getCssVar("--primary"),
      primarySoft: getCssVar("--primary-soft"),
      success: getCssVar("--success"),
      successSoft: getCssVar("--success-soft"),
      warning: getCssVar("--warning"),
      warningSoft: getCssVar("--warning-soft"),
      danger: getCssVar("--danger"),
      dangerSoft: getCssVar("--danger-soft"),
      info: getCssVar("--info"),
      infoSoft: getCssVar("--info-soft"),
      text: getCssVar("--text"),
      textSoft: getCssVar("--text-soft"),
      textFaint: getCssVar("--text-faint"),
      border: getCssVar("--border"),
      bgElevated: getCssVar("--bg-elevated"),
      bgMuted: getCssVar("--bg-muted"),
    };

    return tokens[token] || token;
  }

  function resolveThemeTokens(value) {
    if (Array.isArray(value)) {
      return value.map(resolveThemeTokens);
    }

    if (value && typeof value === "object") {
      const next = {};
      Object.keys(value).forEach((key) => {
        next[key] = resolveThemeTokens(value[key]);
      });
      return next;
    }

    if (typeof value === "string" && value.startsWith("theme:")) {
      return resolveThemeToken(value.replace("theme:", ""));
    }

    return value;
  }

  function mergeChartOptions(base, custom) {
    if (!custom) {
      return base;
    }

    const merged = deepClone(base);
    Object.keys(custom).forEach((key) => {
      const value = custom[key];
      if (
        value &&
        typeof value === "object" &&
        !Array.isArray(value) &&
        merged[key] &&
        typeof merged[key] === "object"
      ) {
        merged[key] = mergeChartOptions(merged[key], value);
      } else {
        merged[key] = value;
      }
    });
    return merged;
  }

  function getBaseChartOptions(type) {
    const textSoft = getCssVar("--text-soft");
    const textFaint = getCssVar("--text-faint");
    const border = getCssVar("--border");

    const shared = {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: "index",
        intersect: false,
      },
      plugins: {
        legend: {
          labels: {
            color: textSoft,
            boxWidth: 10,
            boxHeight: 10,
            usePointStyle: true,
            pointStyle: "circle",
            font: {
              family: "Manrope",
              size: 12,
              weight: "700",
            },
          },
        },
        tooltip: {
          backgroundColor: "#0f172a",
          titleColor: "#f8fafc",
          bodyColor: "#cbd5e1",
          borderWidth: 0,
          padding: 12,
          displayColors: true,
        },
      },
    };

    if (type === "doughnut" || type === "pie" || type === "polarArea") {
      return shared;
    }

    if (type === "radar") {
      return mergeChartOptions(shared, {
        scales: {
          r: {
            angleLines: { color: border },
            grid: { color: border },
            pointLabels: { color: textSoft },
            ticks: { display: false },
          },
        },
      });
    }

    return mergeChartOptions(shared, {
      scales: {
        x: {
          border: { display: false },
          grid: { display: false },
          ticks: {
            color: textFaint,
            font: { family: "Manrope", size: 11, weight: "700" },
          },
        },
        y: {
          border: { display: false },
          grid: { color: border },
          ticks: {
            color: textFaint,
            font: { family: "Manrope", size: 11, weight: "700" },
          },
        },
      },
    });
  }

  function renderCharts() {
    if (typeof window.Chart === "undefined") {
      return;
    }

    while (chartInstances.length) {
      const chart = chartInstances.pop();
      chart.destroy();
    }

    const chartConfigs = Array.isArray(window.kaCharts) ? window.kaCharts : [];
    chartConfigs.forEach((config) => {
      const canvas = document.getElementById(config.id);
      if (!canvas) {
        return;
      }

      const chartConfig = resolveThemeTokens(deepClone(config));
      chartConfig.options = mergeChartOptions(
        getBaseChartOptions(chartConfig.type),
        chartConfig.options || {}
      );

      const instance = new window.Chart(canvas, chartConfig);
      chartInstances.push(instance);
    });
  }

  function initCharts() {
    renderCharts();
    document.addEventListener("ka:theme-changed", () => {
      window.setTimeout(renderCharts, 50);
    });
  }

  function initToastTriggers() {
    document.addEventListener("click", (event) => {
      const button = event.target.closest("[data-toast]");
      if (!button) {
        return;
      }
      showToast(button.getAttribute("data-toast"), button.dataset.tone || "primary");
    });
  }

  function initMisc() {
    document.querySelectorAll("[data-current-year]").forEach((item) => {
      item.textContent = String(new Date().getFullYear());
    });

    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape") {
        document
          .querySelectorAll("[data-modal], [data-drawer]")
          .forEach((element) => element.classList.add("hidden"));
        document.body.classList.remove("mobile-sidebar-open");
      }
    });
  }

  window.kaToast = showToast;

  document.addEventListener("DOMContentLoaded", () => {
    initTheme();
    initSidebar();
    initModals();
    initDrawers();
    initDataTables();
    initCharts();
    initToastTriggers();
    initMisc();
  });
})();

