jQuery(function ($) {
  "use strict";

  // Safety checks
  if (typeof window.fold82smMetaboxData === "undefined") return;

  const data = window.fold82smMetaboxData;

  const $search = $("#wpsmartfolder-search");
  const $container = $("#wpsmartfolder-folders-container");
  const $saveBtn = $("#wpsmartfolder-save-selection");
  const $selectedCount = $("#selected-count");
  const $totalCount = $("#total-count");

  if (!$container.length) return;

  const i18n = data.i18n || {};
  const txtNoFolders = i18n.no_folders_found || "No folders found";
  const txtSaving = i18n.saving || "Saving...";
  const txtSaved = i18n.saved || "Saved!";
  const txtErrorSaving = i18n.error_saving || "Error saving selection";

  const folders = Array.isArray(data.available_folders) ? data.available_folders : [];
  const initiallySelected = Array.isArray(data.selected_folders) ? data.selected_folders.map(Number) : [];

  // State
  let selected = new Set(initiallySelected);
  let lastRenderedIds = []; // used for counters / "shown"
  let isDirty = false;
  let isSaving = false;

  function escHtml(str) {
    return String(str)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }

  function setButtonState() {
    if (!$saveBtn.length) return;
    const shouldEnable = isDirty && !isSaving;
    $saveBtn.prop("disabled", !shouldEnable);
  }

  function updateCounters() {
    if ($selectedCount.length) $selectedCount.text(selected.size);
    if ($totalCount.length) $totalCount.text(lastRenderedIds.length);
  }

  function filterFolders(query) {
    const q = (query || "").trim().toLowerCase();
    if (!q) return folders;

    return folders.filter((f) => {
      const name = (f && f.name) ? String(f.name).toLowerCase() : "";
      return name.indexOf(q) !== -1;
    });
  }

  function renderList(list) {
    $container.empty();

    if (!Array.isArray(list) || list.length === 0) {
      $container.append(
        '<div style="padding:6px 2px; color:#666; font-size:12px;">' + escHtml(txtNoFolders) + "</div>"
      );
      lastRenderedIds = [];
      updateCounters();
      return;
    }

    // Render as checkboxes
    const html = [];
    lastRenderedIds = [];

    list.forEach((f) => {
      if (!f || typeof f.id === "undefined") return;

      const id = Number(f.id);
      const name = (typeof f.name !== "undefined") ? String(f.name) : "";
      const isChecked = selected.has(id);

      lastRenderedIds.push(id);

      html.push(
        '<label style="display:flex; align-items:center; gap:8px; padding:4px 0; font-size:12px; cursor:pointer;">' +
          '<input type="checkbox" class="wpsmartfolder-folder-checkbox" data-folder-id="' + id + '"' + (isChecked ? " checked" : "") + " />" +
          '<span style="flex:1;">' + escHtml(name) + "</span>" +
        "</label>"
      );
    });

    $container.append(html.join(""));
    updateCounters();
  }

  function markDirty() {
    isDirty = true;
    setButtonState();
  }

  function markClean() {
    isDirty = false;
    setButtonState();
  }

  function setSavingState(saving) {
    isSaving = !!saving;
    if ($saveBtn.length) {
        if (isSaving) {
            // Salva il testo originale
            const originalText = $saveBtn.text();
            if (!originalText.includes("...")) { // Evita di sovrascrivere se già c'è "Saving..."
                $saveBtn.data("original-text", originalText);
            }
            $saveBtn.text(txtSaving);
        } else {
            // Ripristina SEMPRE il testo originale dopo il salvataggio
            const original = $saveBtn.data("original-text") || "Save Selection";
            $saveBtn.text(original);
            $saveBtn.removeData("original-text");
        }
    }
    setButtonState();
}

function showTempButtonLabel(label, ms) {
    if (!$saveBtn.length) return;
    const original = $saveBtn.text();
    // Save original text only if it's not a temporary state
    if (original !== txtSaving && original !== txtSaved) {
        $saveBtn.data("original-text", original);
    }
    $saveBtn.text(label);
    setTimeout(function () {
        // Restore original text after timeout - this ensures the button always returns to its proper state
        const restoreText = $saveBtn.data("original-text") || "Save Selection";
        $saveBtn.text(restoreText);
        $saveBtn.removeData("original-text");
    }, ms || 1200);
}

  function getSelectedArray() {
    return Array.from(selected).map(Number).filter((n) => n > 0);
  }

  function saveSelection() {
    if (isSaving) return;
    if (!isDirty) return;

    setSavingState(true);

    $.ajax({
      url: data.ajax_url,
      method: "POST",
      dataType: "json",
      data: {
        action: data.action || "fold82sm_save_folder_selection",
        nonce: data.nonce,
        post_id: data.post_id,
        folder_ids: getSelectedArray(),
      },
    })
      .done(function (resp) {
        if (resp && resp.success) {
          markClean();
          showTempButtonLabel(txtSaved, 1000);
        } else {
          const msg =
            (resp && resp.data && resp.data.message) ? String(resp.data.message) : txtErrorSaving;
          window.alert(msg);
        }
      })
      .fail(function () {
        window.alert(txtErrorSaving);
      })
      .always(function () {
        setSavingState(false);
      });
  }

  // Initial render
  renderList(filterFolders(""));
  updateCounters();
  markClean(); // initial state is clean

  // Events
  $search.on("input", function () {
    const list = filterFolders($(this).val());
    renderList(list);
  });

  // Checkbox toggle (delegated)
  $container.on("change", ".wpsmartfolder-folder-checkbox", function () {
    const id = Number($(this).data("folder-id"));
    if (!id) return;

    if ($(this).is(":checked")) {
      selected.add(id);
    } else {
      selected.delete(id);
    }

    markDirty();
    updateCounters();
  });

  // Save button
  $saveBtn.on("click", function (e) {
    e.preventDefault();
    saveSelection();
  });
});