$(document).ready(function () {
  let params = new URLSearchParams(window.location.search);
  let currentIndex = -1;
  // Inactivity handlers removed for Users page

  // Hide main content and show loading spinner
  $("#main-content").hide();

  $("body").prepend(`
  <div id="loadingContainer">
    <div id="loadingSpinner">
        <div class="spinner-line" id="line1"></div>
        <div class="spinner-line" id="line2"></div>
        <div class="spinner-line" id="line3"></div>
    </div>
    <p id="loadingText">Chargement...</p>
  </div>
        `);

  $("#loadingContainer").show();

  let pendingCheckbox = null;
  let pendingIdUser = null;
  let pendingIsChecked = null;

  /*------------------------------------------------------------*/
  /*-------------------- gridUtilisateurs  ---------------------*/
  /*------------------------------------------------------------*/
  let resetBtn;

  var gridUtilisateurs = new DataTable("#gridUtilisateurs", {
    paging: true,
    scrollCollapse: true,
    scrollY: "57vh",
    scrollX: false,
    ordering: true,
    info: true,
    footer: true,
    stateSave: true,
    pageLength: 100,
    columnDefs: [
      {
        targets: [6],
        createdCell: function (td) {
          td.style.textAlign = "center";
          td.style.fontWeight = "bold";
        },
      },
      {
        targets: [7],
        createdCell: function (td) {
          td.style.textAlign = "center";
          td.style.fontWeight = "bold";
        },
      },
      {
        targets: [11],
        orderable: false,
      },
    ],
    columns: [
      { width: "50px" },
      { width: "auto" },
      { width: "auto" },
      { width: "auto" },
      { width: "200px" },
      { width: "200px" },
      { width: "200px" },
      { width: "200px" },
      { width: "200px" },
      { width: "auto" },
      { width: "auto" },
      { width: "95px" },
    ],
    language: {
      info: "Affichage page _PAGE_ / _PAGES_, Total : _TOTAL_ ligne(s).",
      infoEmpty: "Aucun enregistrement trouvé.",
      infoFiltered: "(filtrage de _MAX_ total enregistrements)",
      lengthMenu: "Afficher _MENU_ records par page",
      zeroRecords: "Aucun enregistrement trouvé - désolé",
      search: "<b>Recherche Global : <b>",
      stateRestore: {
        creationModal: {
          length: "Length:",
        },
      },
      buttons: {
        pageLength: {
          _: "Afficher %d éléments",
          "-1": "Tout afficher",
        },
        copyTitle: "Copie réussie",
        copySuccess: {
          1: "1 ligne copiée dans le presse-papiers",
          _: "%d lignes copiées dans le presse-papiers",
        },
        copy: "Copier",
        print: "Imprimer",
      },
    },
    lengthMenu: [
      [10, 25, 50, 100, 500, -1],
      [
        "10 lignes",
        "25 lignes",
        "50 lignes",
        "100 lignes",
        "500 lignes",
        "Afficher tous",
      ],
    ],
    layout: {
      topStart: {
        buttons: [
          {
            extend: "pageLength",
          },
          {
            extend: "copyHtml5",
            filename: "LISTE DES UTILISATEURS",
            text: '<i class="fas fa-copy" style="color: #6f42c1;"></i>&nbsp',
            titleAttr: "Copier dans le presse-papiers",
          },
          {
            extend: "excel",
            filename: "LISTE DES UTILISATEURS",
            text: '<i class="fas fa-file-excel" style="color: #28a745;"></i>&nbsp',
            titleAttr: "Exporter au format Excel",
          },
          {
            extend: "pdf",
            filename: "LISTE DES UTILISATEURS",
            text: '<i class="fas fa-file-pdf" style="color: #dc3545;"></i>&nbsp',
            titleAttr: "Exporter au format PDF",
            exportOptions: {
              columns: ":not(.no-export)",
            },
          },
          {
            extend: "print",
            filename: "LISTE DES UTILISATEURS",
            text: '<i class="fas fa-print" style="color: #fd7e14;"></i>&nbsp',
            titleAttr: "Imprimer la table",
            exportOptions: {
              columns: ":not(.no-export)",
            },
          },
          {
            text: '<i class="fas fa-sync-alt"></i>&nbsp',
            titleAttr: "Réinitialiser et recharger",
            action: function (e, dt, node, config) {
              dt.state.clear();
              dt.search("").columns().search("").draw();
              location.reload();
            },
          },
          {
            text: '<i class="fas fa-plus"></i> Ajouter un utilisateur',
            titleAttr: "Ajouter un nouveau utilisateur",
            attr: {
              id: "btnAddUser",
            },
          },
        ],
      },
    },
    initComplete: function () {
      var api = this.api();
      var excludedColumns = [11];
      var calendarColumns = [7, 8];

      $.datepicker.setDefaults($.datepicker.regional["fr"]);

      api.columns().every(function () {
        this.search("");
      });
      api.search("").draw();

      api.columns().every(function (index) {
        if (excludedColumns.includes(index)) return;

        let column = this;
        let title = column.footer().textContent;

        let wrapper = document.createElement("div");
        wrapper.classList.add("input-group");

        let input = document.createElement("input");
        input.placeholder = title;
        input.value = column.search();
        input.classList.add("form-control");
        input.classList.add("form-control-sm");

        if (calendarColumns.includes(index)) {
          input.classList.add("show-calendar");

          let iconSpan = document.createElement("span");
          iconSpan.className = "input-group-text";
          (iconSpan.innerHTML = '<i class="fas fa-calendar-alt"></i>&nbsp'),
            iconSpan.addEventListener("click", function () {
              $(input).datepicker("show");
            });

          wrapper.appendChild(input);
          wrapper.appendChild(iconSpan);

          $(input).datepicker({
            format: "yy-mm-dd",
            autoclose: true,
            todayHighlight: true,
            clearBtn: true,
            onSelect: function (dateText) {
              if (column.search() !== dateText) {
                column.search(dateText).draw();
                updateResetButton();
              }
            },
          });
        } else {
          wrapper.appendChild(input);
        }

        column.footer().replaceChildren(wrapper);

        input.addEventListener("input", function () {
          if (column.search() !== this.value) {
            column.search(this.value).draw();
            updateResetButton();
          }
        });
      });

      let resetFooter = api.column(11).footer();
      resetFooter.innerHTML = "";

      resetBtn = document.createElement("button");
      resetBtn.textContent = "Réinitialiser";
      resetBtn.className = "btn btn-outline-secondary btn-sm d-none";
      resetBtn.addEventListener("click", function () {
        api.columns().every(function () {
          this.search("");
        });

        api.search("").draw();
        $(api.table().footer()).find("input").val("");
        $(".dt-search input[type='search']").val("");
        resetBtn.classList.add("d-none");
      });

      resetFooter.appendChild(resetBtn);

      function updateResetButton() {
        const hasColumnFilter = api
          .columns()
          .indexes()
          .toArray()
          .some(function (index) {
            return api.column(index).search().trim() !== "";
          });

        const hasGlobalSearch = api.search().trim() !== "";

        if (hasColumnFilter || hasGlobalSearch) {
          resetBtn.classList.remove("d-none", "btn-outline-secondary");
          resetBtn.classList.add("btn-danger");
        } else {
          resetBtn.classList.add("d-none");
          resetBtn.classList.remove("btn-danger");
          resetBtn.classList.add("btn-outline-secondary");
        }
      }

      updateResetButton();

      $('.dt-search input[type="search"]').on("input", function () {
        updateResetButton();
      });
    },
  });

  gridUtilisateurs.column("1:visible").order("asc").draw();

  // Remove any layout buttons duplicated by the layout row (keep this behaviour)
  $(".dt-layout-row").last().find(".dt-buttons").remove();

  $("#gridUtilisateurs").css("font-size", "14px");
  $("#gridUtilisateurs td, #gridUtilisateurs head, #gridUtilisateurs th").css({
    "padding-top": "2px",
    "padding-bottom": "2px",
  });

  // Robust handling for moving the DataTables scrollFoot under the scrollHead
  // and synchronizing column widths. We do this on init.dt and draw.dt to
  // avoid null access when DataTables hasn't finished cloning the DOM.
  (function () {
    var $table = $("#gridUtilisateurs");

    function moveScrollFootAfterHead($wrapper) {
      try {
        var $scrollHead = $wrapper.find('.dataTables_scrollHead, .dt-scroll-head').first();
        var $scrollFoot = $wrapper.find('.dataTables_scrollFoot, .dt-scroll-foot').first();
        if ($scrollHead.length && $scrollFoot.length) {
          // jQuery insertAfter is safe and handles DOM placement
          $scrollFoot.insertAfter($scrollHead);
        }
      } catch (e) {
        console.warn('moveScrollFootAfterHead error', e);
      }
    }

    function copyHeaderWidthsToFooterAndAdjust(dtInstance) {
      try {
        // small timeout to let browsers finish layout after DataTables operations
        setTimeout(function () {
          var $wrapper = $table.closest('.dataTables_scroll, .dt-scroll');
          var $headThs = $wrapper.find('.dataTables_scrollHeadInner table thead th, .dt-scroll-head table thead th');
          var $footThs = $wrapper.find('.dataTables_scrollFootInner table tfoot th, .dt-scroll-foot table tfoot th');

          if (!$headThs.length || !$footThs.length) return;

          try { dtInstance.columns.adjust(); } catch (e) { /* ignore */ }

          $headThs.each(function (i, th) {
            var w = $(th).outerWidth();
            var $f = $footThs.eq(i);
            if ($f.length) {
              $f.css({ width: w + 'px', 'min-width': w + 'px' });
            }
          });

          try { dtInstance.columns.adjust(); } catch (e) { /* ignore */ }
        }, 60);
      } catch (e) {
        console.warn('copyHeaderWidthsToFooterAndAdjust error', e);
      }
    }

    function onDataTableRendered(e, settings) {
      var dtInstance = null;
      try {
        if ($table.length && $table.DataTable) dtInstance = $table.DataTable();
      } catch (err) {
        dtInstance = null;
      }

      var $wrapper = $table.closest('.dataTables_scroll, .dt-scroll');
      if (!$wrapper.length) return;

      moveScrollFootAfterHead($wrapper);
      if (dtInstance) copyHeaderWidthsToFooterAndAdjust(dtInstance);
    }

    // Bind to DataTables lifecycle events
    $table.on('init.dt draw.dt', onDataTableRendered);

    // Safety: if already initialised, run once immediately
    $(function () {
      try {
        if ($table.length && $table.DataTable && $table.hasClass('dataTable')) {
          onDataTableRendered();
        }
      } catch (e) {
        /* ignore */
      }
    });

    // Re-run on window resize (debounced)
    var resizeTimer;
    $(window).on('resize', function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        try {
          if ($table.length && $table.DataTable) copyHeaderWidthsToFooterAndAdjust($table.DataTable());
        } catch (e) { /* ignore */ }
      }, 150);
    });
  })();

  // Hide loading spinner and show main content
  // Après toute l'initialisation, cacher le loader et afficher le contenu principal
  if (typeof $ !== "undefined") {
    if (jQuery("#loadingContainer").length) {
      jQuery("#loadingContainer").fadeOut(600, function () {
        jQuery(this).remove();
        jQuery("#main-content").fadeIn();
      });
    } else {
      jQuery("#main-content").fadeIn();
    }
  } else {
    // si jQuery absent, tenter un affichage direct
    var loaderEl = document.getElementById("loadingContainer");
    var mainEl = document.getElementById("main-content");
    if (loaderEl && loaderEl.parentNode)
      loaderEl.parentNode.removeChild(loaderEl);
    if (mainEl) mainEl.style.display = "block";
  }
});
