(function ($) {
  "use strict";

  var theme = window.kaApexTheme = window.kaApexTheme || {};

  theme.readVar = function (name, fallback) {
    var value = window.getComputedStyle(document.body).getPropertyValue(name).trim();
    return value || fallback;
  };

  theme.refreshFromCss = function () {
    theme.palette = {
      primary: theme.readVar("--ka-primary", "#F59E0B"),
      secondary: theme.readVar("--ka-secondary", "#3B82F6"),
      success: theme.readVar("--ka-success", "#10B981"),
      danger: theme.readVar("--ka-danger", "#EF4444"),
      warning: theme.readVar("--ka-warning", "#F97316"),
      purple: theme.readVar("--ka-purple", "#8B5CF6"),
      pink: theme.readVar("--ka-pink", "#EC4899"),
      teal: theme.readVar("--ka-teal", "#14B8A6")
    };

    theme.chartUtils = {
      fontFamily: '"DM Sans", sans-serif',
      foreColor: theme.readVar("--ka-text-muted", "#94A3B8"),
      gridColor: theme.readVar("--ka-border", "rgba(255,255,255,0.06)"),
      trackColor: "rgba(255,255,255,0.08)",
      labelColor: theme.readVar("--ka-text", "#DBE6F3"),
      background: theme.readVar("--ka-bg-elevated", "#101624")
    };
  };

  theme.refreshFromCss();

  function applyApexDefaults() {
    if (!window.ApexCharts || window.__kaApexThemePatched) {
      return;
    }

    var NativeApexCharts = window.ApexCharts;

    function sanitizeApexOptions(options) {
      var next = $.extend(true, {}, options || {});
      var utils = theme.chartUtils;
      var sparklineEnabled = !!(next.chart && next.chart.sparkline && next.chart.sparkline.enabled);

      next.chart = $.extend(true, {
        background: "transparent",
        foreColor: utils.foreColor,
        dropShadow: {
          enabled: false
        },
        toolbar: {
          show: false
        },
        animations: {
          enabled: true,
          easing: "easeinout",
          speed: 520
        }
      }, next.chart);
      next.chart.dropShadow = $.extend(true, {}, next.chart.dropShadow, {
        enabled: false
      });

      next.theme = $.extend(true, {
        mode: "dark",
        monochrome: {
          enabled: false
        }
      }, next.theme);

      next.states = $.extend(true, {
        hover: {
          filter: {
            type: "none"
          }
        },
        active: {
          filter: {
            type: "none"
          }
        }
      }, next.states);

      next.tooltip = $.extend(true, {
        theme: "dark",
        fillSeriesColor: false,
        style: {
          fontFamily: utils.fontFamily
        }
      }, next.tooltip);

      next.legend = $.extend(true, {
        labels: {
          colors: utils.foreColor
        },
        fontSize: "12px",
        fontFamily: utils.fontFamily
      }, next.legend);

      next.dataLabels = $.extend(true, {
        style: {
          fontFamily: utils.fontFamily
        }
      }, next.dataLabels);

      next.markers = $.extend(true, {
        size: sparklineEnabled ? 0 : 3,
        strokeColors: utils.background,
        strokeWidth: 2,
        hover: {
          sizeOffset: sparklineEnabled ? 2 : 3
        }
      }, next.markers);

      next.noData = $.extend(true, {
        style: {
          color: utils.foreColor,
          fontFamily: utils.fontFamily
        }
      }, next.noData);

      if (!sparklineEnabled) {
        next.grid = $.extend(true, {
          borderColor: utils.gridColor,
          strokeDashArray: 4,
          padding: {
            left: 8,
            right: 8
          }
        }, next.grid);
      }

      next.xaxis = $.extend(true, {
        labels: {
          style: {
            colors: utils.foreColor,
            fontFamily: utils.fontFamily
          }
        },
        axisBorder: {
          color: utils.gridColor
        },
        axisTicks: {
          color: utils.gridColor
        }
      }, next.xaxis);

      next.yaxis = $.extend(true, {
        labels: {
          style: {
            colors: utils.foreColor,
            fontFamily: utils.fontFamily
          }
        }
      }, next.yaxis);

      if (next.fill && next.fill.gradient) {
        next.fill.gradient = $.extend(true, {
          shade: "dark",
          inverseColors: false,
          shadeIntensity: 0.18,
          opacityFrom: sparklineEnabled ? 0.24 : 0.28,
          opacityTo: sparklineEnabled ? 0.01 : 0.06,
          stops: [0, 100]
        }, next.fill.gradient);
        next.fill.gradient.shade = "dark";
        next.fill.gradient.inverseColors = false;
        next.fill.gradient.shadeIntensity = 0.18;
        next.fill.gradient.opacityFrom = sparklineEnabled ? 0.24 : 0.28;
        next.fill.gradient.opacityTo = sparklineEnabled ? 0.01 : 0.06;
        next.fill.gradient.stops = [0, 100];
      }

      if (next.plotOptions && next.plotOptions.bar) {
        next.plotOptions.bar = $.extend(true, {
          borderRadius: 10,
          columnWidth: "48%"
        }, next.plotOptions.bar);
      }

      if (next.chart && (next.chart.type === "area" || next.chart.type === "line")) {
        next.stroke = $.extend(true, {
          width: sparklineEnabled ? 2.5 : 3,
          curve: "smooth"
        }, next.stroke);
      }

      if (next.plotOptions && next.plotOptions.radialBar) {
        next.plotOptions.radialBar = $.extend(true, {
          hollow: {
            size: "74%",
            background: "transparent"
          },
          track: {
            background: utils.trackColor,
            strokeWidth: "72%"
          },
          dataLabels: {
            value: {
              color: utils.labelColor,
              fontFamily: '"Syne", sans-serif'
            },
            name: {
              color: utils.foreColor,
              fontFamily: utils.fontFamily
            }
          }
        }, next.plotOptions.radialBar);
      }

      if (next.plotOptions && next.plotOptions.pie) {
        next.plotOptions.pie = $.extend(true, {
          expandOnClick: false,
          donut: {
            size: "72%",
            labels: {
              show: next.chart && next.chart.type === "donut",
              total: {
                show: true,
                color: utils.labelColor,
                fontFamily: utils.fontFamily
              },
              value: {
                color: utils.labelColor,
                fontFamily: '"Syne", sans-serif'
              },
              name: {
                color: utils.foreColor,
                fontFamily: utils.fontFamily
              }
            }
          }
        }, next.plotOptions.pie);
      }

      if (next.stroke) {
        next.stroke = $.extend(true, {
          lineCap: "round"
        }, next.stroke);
      }

      return next;
    }

    window.Apex = $.extend(true, {}, window.Apex || {}, {
      chart: {
        foreColor: theme.chartUtils.foreColor,
        toolbar: {
          show: false
        }
      },
      tooltip: {
        theme: "dark"
      },
      grid: {
        borderColor: theme.chartUtils.gridColor
      },
      legend: {
        labels: {
          colors: theme.chartUtils.foreColor
        }
      }
    });

    function PatchedApexCharts(element, options) {
      return new NativeApexCharts(element, sanitizeApexOptions(options));
    }

    PatchedApexCharts.prototype = NativeApexCharts.prototype;
    Object.setPrototypeOf(PatchedApexCharts, NativeApexCharts);
    window.ApexCharts = PatchedApexCharts;
    window.__kaApexThemePatched = true;
  }

  function applyChartJsDefaults() {
    if (!window.Chart) {
      return;
    }

    theme.refreshFromCss();

    Chart.defaults.color = theme.chartUtils.foreColor;
    Chart.defaults.font.family = theme.chartUtils.fontFamily;
    Chart.defaults.borderColor = theme.chartUtils.gridColor;
    Chart.defaults.plugins.legend.labels.color = theme.chartUtils.foreColor;
    Chart.defaults.plugins.tooltip.backgroundColor = "rgba(11, 15, 28, 0.96)";
    Chart.defaults.plugins.tooltip.titleColor = theme.chartUtils.labelColor;
    Chart.defaults.plugins.tooltip.bodyColor = theme.chartUtils.labelColor;
    Chart.defaults.plugins.tooltip.borderColor = theme.chartUtils.gridColor;
    Chart.defaults.plugins.tooltip.borderWidth = 1;
    Chart.defaults.elements.line.borderWidth = 3;
    Chart.defaults.elements.point.radius = 0;
    Chart.defaults.elements.point.hoverRadius = 4;
  }

  function initPerfectScrollbar(selector) {
    if (window.PerfectScrollbar && document.querySelector(selector)) {
      new PerfectScrollbar(selector);
    }
  }

  function formatCount(value, decimals) {
    return value.toLocaleString("en-US", {
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals
    });
  }

  function animateCount(el) {
    if (!el || el.dataset.counted === "true") {
      return;
    }

    var source = (el.dataset.countup || el.textContent || "").trim();
    var match = source.match(/^([^0-9-]*)(-?\d+(?:\.\d+)?)(.*)$/);

    if (!match) {
      el.dataset.counted = "true";
      return;
    }

    var prefix = match[1];
    var target = parseFloat(match[2]);
    var suffix = match[3];
    var decimals = (match[2].split(".")[1] || "").length;
    var startedAt = null;
    var duration = 900;

    function step(timestamp) {
      if (!startedAt) {
        startedAt = timestamp;
      }

      var progress = Math.min((timestamp - startedAt) / duration, 1);
      var eased = 1 - Math.pow(1 - progress, 3);
      var current = target * eased;

      el.textContent = prefix + formatCount(current, decimals) + suffix;

      if (progress < 1) {
        window.requestAnimationFrame(step);
      } else {
        el.textContent = source;
        el.dataset.counted = "true";
      }
    }

    window.requestAnimationFrame(step);
  }

  function initCountups() {
    var items = document.querySelectorAll("[data-countup]");

    if (!items.length) {
      return;
    }

    if (!("IntersectionObserver" in window)) {
      items.forEach(animateCount);
      return;
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          animateCount(entry.target);
          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.55
    });

    items.forEach(function (item) {
      observer.observe(item);
    });
  }

  function tagCards() {
    document.querySelectorAll(".card").forEach(function (card) {
      if (card.closest(".search-popup, .mega-menu, .offcanvas, .modal")) {
        return;
      }

      var hasChart = !!card.querySelector(".apexcharts-canvas, canvas, [id^='chart']");
      var hasTable = !!card.querySelector(".table, .table-responsive, .dataTables_wrapper");
      var hasList = !!card.querySelector(".list-group, .order-list, .customer-notes, .email-list, .chat-list");
      var hasStat = !!card.querySelector("[data-countup], .display-number, .wh-42, .wh-48, .wh-64");

      if (hasChart) {
        card.classList.add("ka-card-chart");
      }

      if (hasTable) {
        card.classList.add("ka-card-table");
      }

      if (hasList) {
        card.classList.add("ka-card-list");
      }

      if (hasStat && !hasChart && !hasTable) {
        card.classList.add("ka-card-stat");
      }
    });
  }

  function bindThemeSwitch(selector, themeName) {
    $(selector).on("click", function () {
      $("html").attr("data-bs-theme", themeName);
      window.setTimeout(function () {
        theme.refreshFromCss();
        applyChartJsDefaults();
      }, 0);
    });
  }

  applyApexDefaults();
  applyChartJsDefaults();

  $(function () {
    $("body").addClass("ka-app");
    window.requestAnimationFrame(function () {
      $("body").addClass("ui-ready");
    });

    initPerfectScrollbar(".notify-list");
    initPerfectScrollbar(".search-content");

    $(".btn-toggle").on("click", function () {
      if ($("body").hasClass("toggled")) {
        $("body").removeClass("toggled");
        $(".sidebar-wrapper").off("mouseenter mouseleave");
        return;
      }

      $("body").addClass("toggled");
      $(".sidebar-wrapper").hover(function () {
        $("body").addClass("sidebar-hovered");
      }, function () {
        $("body").removeClass("sidebar-hovered");
      });
    });

    $("#sidenav").metisMenu();

    $(".sidebar-close").on("click", function () {
      $("body").removeClass("toggled");
    });

    $(".dark-mode i").on("click", function () {
      $(this).text(function (index, value) {
        return value === "dark_mode" ? "light_mode" : "dark_mode";
      });
    });

    $(".dark-mode").on("click", function () {
      $("html").attr("data-bs-theme", function (index, value) {
        return value === "dark" ? "light" : "dark";
      });
      window.setTimeout(function () {
        theme.refreshFromCss();
        applyChartJsDefaults();
      }, 0);
    });

    $(window).on("scroll", function () {
      $(".top-header .navbar").toggleClass("sticky-header", $(this).scrollTop() > 60);
    });

    $(".email-toggle-btn").on("click", function () {
      $(".email-wrapper").toggleClass("email-toggled");
    });

    $(".email-toggle-btn-mobile").on("click", function () {
      $(".email-wrapper").removeClass("email-toggled");
    });

    $(".compose-mail-btn").on("click", function () {
      $(".compose-mail-popup").show();
    });

    $(".compose-mail-close").on("click", function () {
      $(".compose-mail-popup").hide();
    });

    $(".chat-toggle-btn").on("click", function () {
      $(".chat-wrapper").toggleClass("chat-toggled");
    });

    $(".chat-toggle-btn-mobile").on("click", function () {
      $(".chat-wrapper").removeClass("chat-toggled");
    });

    bindThemeSwitch("#BlueTheme", "blue-theme");
    bindThemeSwitch("#LightTheme", "light");
    bindThemeSwitch("#DarkTheme", "dark");
    bindThemeSwitch("#SemiDarkTheme", "semi-dark");
    bindThemeSwitch("#BoderedTheme", "bodered-theme");

    $(".search-control").on("click", function () {
      $(".search-popup").addClass("d-block");
      $(".search-close").addClass("d-block");
    });

    $(".search-close").on("click", function () {
      $(".search-popup").removeClass("d-block");
      $(".search-close").removeClass("d-block");
    });

    $(".mobile-search-btn").on("click", function () {
      $(".search-popup").addClass("d-block");
    });

    $(".mobile-search-close").on("click", function () {
      $(".search-popup").removeClass("d-block");
    });

    var current = window.location;
    $(".metismenu li a").filter(function () {
      return this.href === current;
    }).parent().addClass("mm-active").parents("ul").addClass("mm-show").parents("li").addClass("mm-active");

    initCountups();
    tagCards();
  });
})(jQuery);
