/**
 * BrewmyApp Admin UI Scripts — v2.0
 */
(function () {
  "use strict";

  /* ── Copy to clipboard ─────────────────── */
  function copyToClipboard(text, button) {
    if (!text) return;

    var fallback = function () {
      var textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.left = "-9999px";
      document.body.appendChild(textarea);
      textarea.select();
      try {
        document.execCommand("copy");
      } catch (e) {
        /* noop */
      }
      document.body.removeChild(textarea);
    };

    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).catch(fallback);
    } else {
      fallback();
    }

    if (button) {
      var original = button.innerHTML;
      button.classList.add("copied");
      button.innerHTML =
        '<span class="dashicons dashicons-yes-alt"></span> Copied!';
      setTimeout(function () {
        button.innerHTML = original;
        button.classList.remove("copied");
      }, 1500);
    }
  }

  /* ── Copy from textarea (legacy) ───────── */
  function copyFromTextarea(id) {
    var el = document.getElementById(id);
    if (!el) return;
    copyToClipboard(el.value || el.textContent || "");
  }

  /* ── Event delegation ──────────────────── */
  document.addEventListener("click", function (event) {
    // Legacy copy target
    var legacyCopy = event.target.closest("[data-copy-target]");
    if (legacyCopy) {
      var target = legacyCopy.getAttribute("data-copy-target");
      if (target) {
        var el = document.getElementById(target);
        if (el) {
          copyToClipboard(el.value || el.textContent || "", legacyCopy);
        }
      }
      return;
    }

    // New copy text
    var copyBtn = event.target.closest("[data-copy-text]");
    if (copyBtn) {
      copyToClipboard(copyBtn.getAttribute("data-copy-text"), copyBtn);
      return;
    }
  });

  /* ── Toggle target user IDs field ──────── */
  var targetSelect = document.getElementById("bma_push_target");
  var targetIdsRow = document.getElementById("bma_target_ids_row");
  if (targetSelect && targetIdsRow) {
    targetSelect.addEventListener("change", function () {
      targetIdsRow.style.display =
        this.value === "specific" ? "table-row" : "none";
    });
  }

  /* ── Order status toggle row styling ───── */
  document
    .querySelectorAll(
      '.bma-order-status-table .bma-toggle input[type="checkbox"]',
    )
    .forEach(function (cb) {
      cb.addEventListener("change", function () {
        var row = this.closest("tr");
        if (!row) return;
        if (this.checked) {
          row.classList.remove("bma-row-disabled");
          row.classList.add("bma-row-enabled");
        } else {
          row.classList.remove("bma-row-enabled");
          row.classList.add("bma-row-disabled");
        }
      });
    });

  /* ── Tabs (if used inline) ─────────────── */
  document.addEventListener("click", function (e) {
    var tab = e.target.closest(".bma-tab[data-tab]");
    if (!tab) return;

    var container = tab.closest(".bma-tab-container") || document;
    var tabs = container.querySelectorAll(".bma-tab[data-tab]");
    var panels = container.querySelectorAll(".bma-tab-panel");

    tabs.forEach(function (t) {
      t.classList.remove("active");
    });
    panels.forEach(function (p) {
      p.style.display = "none";
    });

    tab.classList.add("active");
    var panelId = tab.getAttribute("data-tab");
    var panel = document.getElementById(panelId);
    if (panel) panel.style.display = "block";
  });

  /* ── Smooth page load ──────────────────── */
  var wrap = document.querySelector(".bma-wrap");
  if (wrap) {
    wrap.style.opacity = "0";
    wrap.style.transform = "translateY(8px)";
    wrap.style.transition = "opacity 0.3s ease, transform 0.3s ease";
    requestAnimationFrame(function () {
      wrap.style.opacity = "1";
      wrap.style.transform = "translateY(0)";
    });
  }

  /* ── Health check ping ─────────────────── */
  var healthDot = document.getElementById("bma-health-dot");
  var healthText = document.getElementById("bma-health-text");
  if (healthDot && typeof bmaAdmin !== "undefined" && bmaAdmin.restUrl) {
    fetch(bmaAdmin.restUrl + "bma/v1/ping", { method: "GET" })
      .then(function (r) {
        return r.json();
      })
      .then(function (data) {
        if (data && data.active) {
          healthDot.classList.add("active");
          healthDot.classList.remove("inactive");
          if (healthText)
            healthText.textContent = "API Active — v" + (data.version || "?");
        }
      })
      .catch(function () {
        healthDot.classList.add("inactive");
        healthDot.classList.remove("active");
        if (healthText) healthText.textContent = "API Unreachable";
      });
  }
})();
