$(document).ready(function () {

  $("#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();

    var gridAnnonceClient = new DataTable("#gridAnnonceClient", {
      progress: true,
      paging: true,
      scrollCollapse: false,
      scrollY: "57vh",
      scrollX: false,
      ordering: true,
      info: true,
      footer: true,
      stateSave: true,
      responsive: true,
      pageLength: 100,
      columnDefs: [
        {
          width: "50px",
          targets: [0],
        },
        {
          targets: [1],
        },
        {
          width: "300px",
          targets: [lastCol - 2],
        },
        {
          width: "80px",
          targets: [lastCol - 1],
          orderable: false,
        },
        {
          width: "95px",
          targets: [lastCol],
          orderable: false,
        },
      ],
      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 VISITES REPRÉSENTANTS",
              text: '<i class="fas fa-copy" style="color: #6f42c1;"></i>&nbsp',
              titleAttr: "Copier dans le presse-papiers",
              exportOptions: {
                columns: ":not(.no-export)",
              },
            },
            {
              extend: "excel",
              filename: "LISTE DES VISITES REPRÉSENTANTS",
              text: '<i class="fas fa-file-excel" style="color: #28a745;"></i>&nbsp',
              titleAttr: "Exporter au format Excel",
              exportOptions: {
                columns: ":not(.no-export)",
              },
            },
            {
              extend: "pdf",
              filename: "LISTE DES VISITES REPRÉSENTANTS",
              text: '<i class="fas fa-file-pdf" style="color: #dc3545;"></i>&nbsp',
              titleAttr: "Exporter au format PDF",
              exportOptions: {
                columns: ":not(.no-export)",
              },
            },
            {
              extend: "print",
              title: "LISTE DES VISITES REPRÉSENTANTS",
              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" style="color:rgb(80, 86, 90);"></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> Nouvelle Visite',
              titleAttr: "Ajouter une nouvelle visite",
              attr: {
                id: "btnAddVisite",
              },
            },
          ],
        },
      },
      initComplete: function () {
        var api = this.api();
        var excludedColumns = [lastCol - 1, lastCol];
        var calendarColumns = [];

        if (useOnlyFirstDate) {
          calendarColumns = [3];
        } else {
          calendarColumns = [3, 4];
        }
        var resetBtn;

        $.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) && useOnlyFirstDate) {
            input.classList.add("show-calendar");

            // Create FROM date input
            let fromInput = document.createElement("input");
            fromInput.placeholder = "De...";
            fromInput.classList.add(
              "form-control",
              "form-control-sm",
              "me-1",
              "calendar-filter"
            );
            fromInput.type = "text";

            // Create TO date input
            let toInput = document.createElement("input");
            toInput.placeholder = "À...";
            toInput.classList.add(
              "form-control",
              "form-control-sm",
              "calendar-filter"
            );
            toInput.type = "text";

            // Wrap them in the input group
            wrapper.classList.remove("input-group");
            wrapper.classList.add("d-flex", "gap-1");
            wrapper.appendChild(fromInput);
            wrapper.appendChild(toInput);

            // Initialize datepickers
            $(fromInput).datepicker({
              dateFormat: "yy-mm-dd",
              changeMonth: true,
              changeYear: true,
              onSelect: filterByDateRange,
            });

            $(toInput).datepicker({
              dateFormat: "yy-mm-dd",
              changeMonth: true,
              changeYear: true,
              onSelect: filterByDateRange,
            });

            function filterByDateRange() {
              let fromDate = fromInput.value;
              let toDate = toInput.value;

              $.fn.dataTable.ext.search = $.fn.dataTable.ext.search.filter(
                (fn) => fn.name !== "rangeFilterColumn3"
              );

              $.fn.dataTable.ext.search.push(function rangeFilterColumn3(
                settings,
                data,
                dataIndex
              ) {
                let colValue = data[3]; // column 3 value: "2025-05-08 de 09:58 à 21:00"
                let dateMatch = colValue.match(/^\d{4}-\d{2}-\d{2}/);
                if (!dateMatch) return false;

                let cellDate = new Date(dateMatch[0]); // extract "2025-05-08"
                let from = fromDate ? new Date(fromDate) : null;
                let to = toDate ? new Date(toDate) : null;

                return (!from || cellDate >= from) && (!to || cellDate <= to);
              });

              api.draw();
              updateResetButton();
            }
          } else {
            input.type = "text";
            input.classList.add("calendar-filter");
            $(input).datepicker({
              dateFormat: "yy-mm-dd",
              changeMonth: true,
              changeYear: true,
              onSelect: function () {
                let selectedDate = input.value;

                $.fn.dataTable.ext.search = $.fn.dataTable.ext.search.filter(
                  (fn) => fn.name !== `singleDateFilterColumn${index}`
                );

                $.fn.dataTable.ext.search.push(function singleDateFilterColumn(
                  settings,
                  data,
                  dataIndex
                ) {
                  let colValue = data[index];
                  let dateMatch = colValue.match(/^\d{4}-\d{2}-\d{2}/);
                  if (!dateMatch) return false;

                  let cellDate = dateMatch[0];
                  return selectedDate === "" || cellDate === selectedDate;
                });

                api.draw();
                updateResetButton();
              },
            });

            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(lastCol).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("");
          $(".calendar-filter").val("");
          $(".dt-search input[type='search']").val("");

          $.fn.dataTable.ext.search = $.fn.dataTable.ext.search.filter(
            (fn) => fn.name !== "rangeFilterColumn3"
          );

          api.draw();

          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() !== "";

          const hasDateFilter =
            $(".calendar-filter").filter(function () {
              return $(this).val().trim() !== "";
            }).length > 0;

          if (hasColumnFilter || hasGlobalSearch || hasDateFilter) {
            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();
        });
      },
    });

    gridAnnonceClient.column("0:visible").order("desc").draw();

    var dtscroll = document.querySelector(".dt-scroll");
    var scrollHead = document.querySelector(".dt-scroll-head");
    var scrollBody = document.querySelector(".dt-scroll-body");
    var scrollFoot = document.querySelector(".dt-scroll-foot");

    // Défensive: vérifier la présence des éléments avant d'insérer
    if (dtscroll && scrollHead && scrollFoot) {
      dtscroll.insertBefore(scrollFoot, scrollHead.nextSibling);
    } else if (scrollHead && scrollFoot && scrollHead.parentNode) {
      // fallback si la structure est différente
      scrollHead.parentNode.insertBefore(scrollFoot, scrollHead.nextSibling);
    }

    if (scrollFoot) {
      var thElements = scrollFoot.querySelectorAll("tfoot tr th");
      thElements.forEach((th) => {
        th.style.borderBottom = "2px solid rgba(0, 0, 0, 0.3)";
      });
    }

    $(".dt-layout-row").last().find(".dt-buttons").remove();

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

  

  // Après toute l'initialisation, cacher le loader et afficher le contenu principal
  if (typeof $ !== 'undefined') {
    if ($("#loadingContainer").length) {
      $("#loadingContainer").fadeOut(600, function() {
        $(this).remove();
        $("#main-content").fadeIn();
      });
    } else {
      $("#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';
  }

});

