(function (global) {
  "use strict";

  var PERIODS = ["day", "week", "month"];

  function statsSegmentSelect() {
    return document.getElementById("stats-segment-select");
  }

  function panelFromTrigger(triggerEl) {
    if (triggerEl && triggerEl.closest) {
      var fromBtn = triggerEl.closest(".stats-segment-panel");
      if (fromBtn) return fromBtn;
    }
    return null;
  }

  function activeSegmentPanel(triggerEl) {
    var panel = panelFromTrigger(triggerEl);
    if (panel) return panel;
    var sel = statsSegmentSelect();
    if (!sel) return null;
    var key = sel.value;
    return document.querySelector(
      '.stats-segment-panel[data-stats-segment="' + key + '"]'
    );
  }

  function replaceStatsUrl(params) {
    var q = new URLSearchParams(global.location.search);
    Object.keys(params).forEach(function (k) {
      if (params[k] == null || params[k] === "") q.delete(k);
      else q.set(k, params[k]);
    });
    var qs = q.toString();
    global.history.replaceState(
      null,
      "",
      qs ? global.location.pathname + "?" + qs : global.location.pathname
    );
  }

  function switchStatsPeriod(periodKey, triggerEl) {
    var panel = activeSegmentPanel(triggerEl);
    if (!panel) return;
    var key = PERIODS.indexOf(periodKey) >= 0 ? periodKey : "day";
    panel.querySelectorAll(".stats-period-pane").forEach(function (pane) {
      var match = pane.getAttribute("data-stats-period") === key;
      if (match) pane.removeAttribute("hidden");
      else pane.setAttribute("hidden", "");
    });
    panel.querySelectorAll(".stats-period-tab").forEach(function (btn) {
      var on = btn.getAttribute("data-stats-period") === key;
      btn.classList.toggle("active", on);
      btn.setAttribute("aria-selected", on ? "true" : "false");
    });
    replaceStatsUrl({ stats_period: key });
  }

  function switchStatsSegment() {
    var sel = statsSegmentSelect();
    if (!sel) return;
    var key = sel.value;
    document.querySelectorAll(".stats-segment-panel").forEach(function (p) {
      p.style.display =
        p.getAttribute("data-stats-segment") === key ? "block" : "none";
    });
    replaceStatsUrl({ stats_segment: key });
    var period =
      new URLSearchParams(global.location.search).get("stats_period") || "day";
    switchStatsPeriod(period);
  }

  function ensurePeriodTabDelegation() {
    if (global.__instanceStatsTabsDelegated) return;
    global.__instanceStatsTabsDelegated = true;
    document.addEventListener(
      "click",
      function (e) {
        var btn =
          e.target && e.target.closest
            ? e.target.closest(".stats-period-tab")
            : null;
        if (!btn) return;
        var card = document.getElementById("stats-card");
        if (!card || !card.contains(btn)) return;
        switchStatsPeriod(btn.getAttribute("data-stats-period") || "day", btn);
      },
      true
    );
  }

  function initStatsFromUrl() {
    var sel = statsSegmentSelect();
    if (!sel) return;
    ensurePeriodTabDelegation();
    var url = new URLSearchParams(global.location.search);
    var segKey = url.get("stats_segment");
    if (
      segKey &&
      sel.querySelector('option[value="' + segKey.replace(/"/g, "") + '"]')
    ) {
      sel.value = segKey;
    }
    switchStatsSegment();
    var period = url.get("stats_period") || "day";
    if (PERIODS.indexOf(period) < 0) period = "day";
    switchStatsPeriod(period);
  }

  ensurePeriodTabDelegation();

  global.switchStatsSegment = switchStatsSegment;
  global.switchStatsPeriod = switchStatsPeriod;
  global.initStatsFromUrl = initStatsFromUrl;
  global.initStatsSegmentFromUrl = initStatsFromUrl;
})(window);
