document.addEventListener("alpine:init", () => {
  Alpine.data("scrollToTop", () => ({
    showTopButton: !1,
    init() {
      window.addEventListener("scroll", () => this.scrollFunction());
    },
    scrollFunction() {
      this.showTopButton =
        document.body.scrollTop > 50 || document.documentElement.scrollTop > 50;
    },
    goToTop() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    },
  }));

  Alpine.data("header", () => ({
    activeDropdown: null,
    messages: [],
    init() {
      const e = window.location.pathname,
        t = Array.from(document.querySelectorAll("ul.relative a")).find(
          (t) => t.getAttribute("href") === e
        );
      if (!t) return;
      t.classList.add("active");
      const a = t.closest("ul.sub-menu");
      if (a) {
        const e = a.closest("li.menu")?.querySelector("button.nav-link");
        e &&
          (e.classList.add("active"),
          (this.activeDropdown = e.textContent.trim()));
      }
    },
    removeMessage(e) {
      this.messages = this.messages.filter((t) => t.id !== e);
    },
  }));

  Alpine.data("tableLogic", () => ({
    datatable: null,
    originalList: [],
    filteredList: [],
    search: "",
    params: {},
    modalOpen: !1,
    modelName: "",
    submitExternally: !1,
    hiddenColumns: [],
    columns: [],
    init() {
      this.modelName = this.$el.dataset.model;
      this.submitExternally = this.$el.dataset.submit === "true";
      this.hiddenColumns = (this.$el.dataset.hiddenColumns || "")
        .split(",")
        .map((e) => e.trim());
      this.originalList = this.parseTableData();
      this.columns = this.getAllColumns();
      this.columns.forEach((e, t) => e.hidden && this.showHideColumns(t, !0));
      this.initDataTable();
    },
    parseTableData() {
      return Array.from(this.$el.querySelectorAll("[data-row]")).map((e) =>
        JSON.parse(e.getAttribute("data-row"))
      );
    },
    getAllColumns() {
      return Array.from(this.$refs.table.querySelectorAll("thead th")).map(
        (e, t) => {
          const a = e.innerText.trim();
          return {
            name: a,
            hidden: this.hiddenColumns.includes(this.slugify(a)),
            index: t,
          };
        }
      );
    },
    slugify: (e) =>
      e
        .toString()
        .toLowerCase()
        .replace(/\s+/g, "_")
        .replace(/[^\w\-]+/g, ""),
    showHideColumns(e, t) {
      this.columns[e].hidden = t;
      this.$refs.table.querySelectorAll("tr").forEach((a) => {
        const i = a.children[this.columns[e].index];
        if (i) i.style.display = t ? "none" : "";
      });
    },
    initDataTable() {
      this.datatable = new simpleDatatables.DataTable(this.$refs.table, {
        perPage: 10,
        perPageSelect: [10, 20, 30, 50],
        columns: [{ select: 0, sort: "asc" }, { select: 5 }],
        firstLast: !0,
        labels: {
          placeholder: "جستجو...",
          perPage: "{select} ورودی در هر صفحه",
          noRows: "هیچ ورودی یافت نشد",
          noResults: "هیچ نتیجه ای با عبارت جستجو مطابقت ندارد",
          info: "نمایش {start} تا {end} از {rows} ورودی",
        },
      });
      this.datatable.on("datatable.search", (e) => {
        this.search = e.detail?.value || "";
      });
    },
    triggerDownload(e, t) {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(e);
      a.download = t;
      a.click();
      URL.revokeObjectURL(a.href);
    },
    exportTable(e) {
      const t = this.columns.filter((e) => !e.hidden).map((e) => e.index),
        a = this.columns.filter((e) => !e.hidden).map((e) => e.name),
        i = Array.from(this.$refs.table.querySelectorAll("tbody tr"))
          .filter((e) => e.style.display !== "none")
          .map((e) => t.map((t) => e.children[t]?.innerText.trim() || ""));
      if (e === "json") {
        const e = i.map((row) =>
          Object.fromEntries(row.map((val, idx) => [a[idx], val]))
        );
        this.triggerDownload(
          new Blob([JSON.stringify(e, null, 2)], { type: "application/json" }),
          "table.json"
        );
      } else {
        const sep = e === "csv" ? ";" : "\t",
          content = [a.join(sep), ...i.map((row) => row.join(sep))].join("\n");
        this.triggerDownload(
          new Blob([content], { type: "text/plain" }),
          `table.${e}`
        );
      }
    },
    printTable() {
      const tIdx = this.columns.filter((e) => !e.hidden).map((e) => e.index),
        tNames = this.columns.filter((e) => !e.hidden).map((e) => e.name),
        rows = Array.from(this.$refs.table.querySelectorAll("tbody tr"))
          .filter((e) => e.style.display !== "none")
          .map((tr) => tIdx.map((i) => tr.children[i]?.innerHTML.trim() || "")),
        html = `<table><thead><tr>${tNames
          .map((e) => `<th>${e}</th>`)
          .join("")}</tr></thead><tbody>${rows
          .map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`)
          .join("")}</tbody></table>`,
        win = window.open("", "", "width=900,height=700");
      win.document.write(`<html><head><title>چاپ جدول</title><style>
        body { font-family: IRANSansWeb, Nunito, sans-serif; direction: rtl; padding: 10px; margin: 0; }
        table { border-collapse: separate; border-spacing: 0; width: 100%; text-align: center; border-radius: 12px; overflow: hidden; }
        th { background-color: #4CAF50; color: white; padding: 12px; font-weight: bold; font-size: 14px; }
        td { border-bottom: 1px solid #ddd; padding: 10px; font-size: 13px; vertical-align: middle; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        tr:hover { background-color: #e8f5e9; }
        th:first-child { border-top-right-radius: 12px; }
        th:last-child { border-top-left-radius: 12px; }
        td img { max-width: 80px; max-height: 80px; border-radius: 8px; }
      </style></head><body>${html}</body></html>`);
      win.document.close();
      win.focus();
      win.print();
      win.close();
    },
  }));
});

// ---- اضافه کردن نمایش پیام‌ها بعد از هر بار بارگذاری HTMX ----
function showMessages(container) {
  const messages = container.querySelectorAll(".js-message");
  messages.forEach((msg) => {
    const level = msg.dataset.level;
    const text = msg.dataset.text;
    const color =
      {
        debug: "secondary",
        info: "info",
        success: "success",
        warning: "warning",
        error: "danger",
      }[level] || "primary";
    Swal.mixin({
      toast: true,
      position: "bottom-start",
      showConfirmButton: false,
      timer: 5000,
      showCloseButton: true,
      animation: false,
      customClass: { popup: `color-${color}` },
      target: document.getElementById(color + "-toast"),
    }).fire({ title: text });
  });
}

document.addEventListener("DOMContentLoaded", () => {
  const e = document.getElementById("js-config");
  if (!e || !window.Alpine) return;
  const config = {
    theme: e.dataset.theme,
    menu: e.dataset.menu,
    semidark: e.dataset.semidark === "true",
    layout: e.dataset.layout,
    rtlClass: e.dataset.rtl,
    navbar: e.dataset.navbar,
    animation: e.dataset.animation,
    sidebar: false,
    toggleTheme(val) {
      this.theme = val;
    },
    toggleMenu(val) {
      this.menu = val;
    },
    toggleSemidark() {
      this.semidark = !this.semidark;
    },
    toggleLayout(val) {
      this.layout = val;
    },
    toggleRTL(val) {
      this.rtlClass = val;
    },
    toggleNavbar(val) {
      this.navbar = val;
    },
    toggleAnimation(val) {
      this.animation = val;
    },
    toggleSidebar() {
      this.sidebar = !this.sidebar;
    },
  };
  Alpine.store("app", config);
  showMessages(document.getElementById("body_htmlx")); // پیام‌ها در لود اولیه

  $(".persian-date").persianDatepicker({
    initialValueType: "persian",
    format: "YYYY/MM/DD",
    autoClose: true,
  });
  $(".persian-datetime").persianDatepicker({
    initialValueType: "persian",
    format: "YYYY/MM/DD H:m",
    autoClose: true,
    timePicker: { enabled: true, meridiem: { enabled: true } },
  });
  $(".persian-time").persianDatepicker({
    initialValueType: "persian",
    onlyTimePicker: true,
    format: "H:m",
    autoClose: true,
    timePicker: { enabled: true, meridiem: { enabled: true } },
  });
});

// اجرای بعد از هر بار بارگذاری HTMX
document.body.addEventListener("htmx:afterSwap", (event) => {
  showMessages(event.target);
});
