(() => {
  async function postForm(url, fields) {
    const body = new FormData();
    Object.entries(fields || {}).forEach(([k, v]) => body.append(k, v == null ? "" : String(v)));
    const res = await fetch(url, { method: "POST", body, headers: { Accept: "application/json" } });
    return res.json();
  }

  function bindPicker(root) {
    const search = root.querySelector("[data-printer-search]");
    const items = [...root.querySelectorAll("[data-printer-item]")];
    const hidden = root.querySelector("[data-printer-value]");
    const empty = root.querySelector("[data-printer-empty]");
    const unc = root.querySelector("[data-printer-unc]");
    const add = root.querySelector("[data-printer-unc-add]");

    const filter = () => {
      const q = (search?.value || "").trim().toLowerCase();
      let n = 0;
      items.forEach((el) => {
        const hay = (el.dataset.search || el.textContent || "").toLowerCase();
        const show = !q || hay.includes(q);
        el.hidden = !show;
        if (show) n += 1;
      });
      if (empty) empty.hidden = n > 0;
    };
    search?.addEventListener("input", filter);

    const select = (id, btn) => {
      if (hidden) hidden.value = id;
      items.forEach((b) => b.classList.toggle("on", b === btn));
    };
    items.forEach((el) => {
      el.addEventListener("click", () => select(el.dataset.id || "", el));
    });
    add?.addEventListener("click", async () => {
      const v = (unc?.value || "").trim();
      if (!v) return;
      const form = root.closest("form");
      const url = form?.dataset.connectUrl;
      const csrf = form?.dataset.csrf || form?.querySelector("[name=csrf_token]")?.value || "";
      const status = document.querySelector("[data-printer-status]");
      if (url) {
        if (status) status.textContent = "Σύνδεση…";
        try {
          const data = await postForm(url, { csrf_token: csrf, printer: v });
          if (data && data.ok) {
            if (hidden) hidden.value = v;
            location.reload();
            return;
          }
          if (status) status.textContent = data.error || "Δεν συνδέθηκε. Αποθηκεύεται το όνομα για εκτύπωση.";
        } catch (e) {
          if (status) status.textContent = "Δεν συνδέθηκε. Θα χρησιμοποιηθεί το όνομα όπως είναι.";
        }
      }
      if (hidden) hidden.value = v;
      items.forEach((b) => b.classList.remove("on"));
    });
  }

  document.querySelectorAll("[data-printer-picker]").forEach(bindPicker);

  document.querySelectorAll("[data-print-now]").forEach((form) => {
    let map = {};
    try {
      map = JSON.parse(form.dataset.printerMap || "{}");
    } catch (e) {
      map = {};
    }
    const sku = form.querySelector("[data-print-sku]");
    form.querySelectorAll("[data-size-id]").forEach((btn) => {
      btn.addEventListener("click", () => {
        const id = btn.dataset.sizeId || "all";
        if (sku) sku.value = id;
        form.querySelectorAll("[data-size-id]").forEach((b) => b.classList.toggle("on", b === btn));
        const mapped = map[id];
        if (!mapped) return;
        const hidden = form.querySelector("[data-printer-value]");
        if (hidden) hidden.value = mapped;
        form.querySelectorAll("[data-printer-item]").forEach((b) => {
          b.classList.toggle("on", (b.dataset.id || "") === mapped);
        });
      });
    });
  });

  const settings = document.querySelector("[data-settings-form]");
  if (settings) {
    const csrf = settings.dataset.csrf || settings.querySelector("[name=csrf_token]")?.value || "";
    const status = () => document.querySelector("[data-printer-status]");

    async function pickFolder(current, title) {
      if (typeof browseFolder === "function") {
        try {
          const path = await browseFolder(current || "");
          return (path || "").trim();
        } catch (e) {}
      }
      const data = await postForm(settings.dataset.browseUrl, {
        csrf_token: csrf,
        current: current || "",
        title: title || "Επιλογή φακέλου",
      });
      if (!data.ok && data.error) {
        alert(data.error);
        return "";
      }
      return (data.path || "").trim();
    }

    settings.querySelectorAll("[data-browse-folder]").forEach((btn) => {
      btn.addEventListener("click", async () => {
        const target = btn.dataset.target;
        const input = settings.querySelector(`[data-folder-input="${target}"]`) || settings.querySelector(`[name="${target}"]`);
        if (!input) return;
        btn.disabled = true;
        try {
          const path = await pickFolder(input.value, btn.dataset.title || "Επιλογή φακέλου");
          if (path) input.value = path;
        } finally {
          btn.disabled = false;
        }
      });
    });

    settings.querySelector("[data-add-printer]")?.addEventListener("click", async () => {
      const note = status();
      if (typeof addPrinter === "function") {
        try {
          await addPrinter();
          if (note) {
            note.textContent = settings.dataset.os === "mac"
              ? "Άνοιξαν οι Ρυθμίσεις του Mac. Πρόσθεσε τον εκτυπωτή εκεί και μετά πάτα Ανανέωση λίστας."
              : "Άνοιξαν οι ρυθμίσεις εκτυπωτή. Όταν τελειώσεις, πάτα Ανανέωση λίστας.";
          }
          return;
        } catch (e) {}
      }
      try {
        const data = await postForm(settings.dataset.addPrinterUrl, { csrf_token: csrf });
        if (note) {
          note.textContent = data.ok
            ? (settings.dataset.os === "mac"
              ? "Άνοιξαν οι Ρυθμίσεις του Mac. Πρόσθεσε τον εκτυπωτή εκεί και μετά πάτα Ανανέωση λίστας."
              : "Άνοιξαν οι ρυθμίσεις εκτυπωτή. Όταν τελειώσεις, πάτα Ανανέωση λίστας.")
            : (data.error || "Δεν άνοιξε ο οδηγός σύνδεσης.");
        }
      } catch (e) {
        if (note) note.textContent = "Δεν άνοιξε ο οδηγός σύνδεσης.";
      }
    });
  }
})();
