$(document).ready(function () {
  $("[data-timepicker-input]").each(function () {
    const $input = $(this);
    const $container = $input.closest(".inail-combobox-input-container");
    const $options = $container.find("[data-timepicker-list]");
    const $message = $container.closest(".combobox").find("[data-timepicker-message]");
    let justSelected = false;

    // === Parse intervallo ===
    function parseInterval(str) {
      if (/^\d+$/.test(str)) return parseInt(str, 10);
      if (/(\d+)\s*m/i.test(str)) return parseInt(RegExp.$1, 10);
      if (/(\d+)\s*h/i.test(str)) return parseInt(RegExp.$1, 10) * 60;
      return 30;
    }

    // === Genera opzioni orario ===
    function generateTimeOptions() {
      $options.empty();
      const format = $input.data("timepicker-format") || "24h";
      const locale = $input.data("locale") || "en-US";
      const interval = parseInterval($input.data("time-interval") || "30m");
      const [minH, minM] = ($input.data("time-min") || "00:00").split(":").map(Number);
      const [maxH, maxM] = ($input.data("time-max") || "23:59").split(":").map(Number);

      let start = minH * 60 + minM;
      let end = maxH * 60 + maxM;

      for (let t = start; t <= end; t += interval) {
        let h = Math.floor(t / 60);
        let m = t % 60;
        const d = new Date();
        d.setHours(h);
        d.setMinutes(m);
        d.setSeconds(0);
        d.setMilliseconds(0);
        let label = new Intl.DateTimeFormat(locale, {
          hour: "2-digit",
          minute: "2-digit",
          hour12: format === "12h",
        }).format(d);
        $options.append(
          `<div class="option" tabindex="0" role="option" data-date="${d.toString()}">${label}</div>`
        );
      }
    }
    generateTimeOptions();

    // === Mostra tutte le opzioni ===
    function showAllOptions() {
      $options.show();
      $input.attr("aria-expanded", "true");

      const $selected = $options.find(".option.selected").first();
      if ($selected.length) {
        setActiveOption($selected);
      } else {
        const $first = $options.find(".option").first();
        if ($first.length) setActiveOption($first);
      }
    }

    // === Validazione input ===
    function validateInput() {
      const val = $input.val().trim();
      const format = $input.data("timepicker-format") || "24h";
      let regex =
        format === "12h"
          ? /^([0-9]{1,2}):([0-9]{2})\s?(AM|PM)$/i
          : /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;

      if (!regex.test(val)) {
        $message.html(
          '<span class="inail-span-error"><i class="fa-solid fa-circle-exclamation"></i> Formato errato</span>'
        );
        $input.addClass("inail-input-error");
      } else {
        $message.empty();
        $input.removeClass("inail-input-error");
      }
    }

    // === Gestione attivo/selected ===
    // function setActiveOption($option) {
    //   $options.find(".option").removeClass("active").attr("aria-selected", "false");
    //   $option.addClass("active").attr("aria-selected", "true");
    //   // CHANGED: removed .focus() so caret stays in input
    // }

    function setActiveOption($option) {
  $options.find(".option").removeClass("active").attr("aria-selected", "false");
  $option.addClass("active").attr("aria-selected", "true");

  // NEW: ensure the active option is visible in the scrollable list
  $option[0].scrollIntoView({
    block: "nearest",   // keeps it within the visible area
    inline: "nearest"
  });
}


    function selectOption($option) {
      $options.find(".option").removeClass("selected");
      $option.addClass("selected");
      const val = $option.text();
      const dateVal = $option.data("date");
      $input.val(val).trigger("change");
      $input.data("selected-date", dateVal);
      $options.hide();
      $input.attr("aria-expanded", "false");
      $message.text("");
      $("[data-time-picker-value]").text("Selezionato: " + val + " (" + dateVal + ")");
    }

    // === Eventi input ===
    $input
      .on("keydown", function (e) {
        if (e.key === "Enter") {
          e.preventDefault();
          if ($options.is(":visible")) {
            // CHANGED: select active option if dropdown is open
            const $active = $options.find(".option.active:visible").first();
            if ($active.length) {
              selectOption($active);
            }
          } else {
            // if dropdown closed, open it
            showAllOptions();
          }
        } else if (e.key === "ArrowDown") {
  if ($options.is(":visible")) {
    e.preventDefault();
    const $visible = $options.find(".option:visible");
    const $active = $options.find(".option.active:visible").first();
    const $selected = $options.find(".option.selected:visible").first();

    if ($active.length) {
      // already active → move to next
      const currentIndex = $visible.index($active);
      if (currentIndex + 1 < $visible.length) {
        setActiveOption($visible.eq(currentIndex + 1));
      }
    } else if ($selected.length) {
      // CHANGED: if selected exists but not active, jump to the NEXT one
      const currentIndex = $visible.index($selected);
      if (currentIndex + 1 < $visible.length) {
        setActiveOption($visible.eq(currentIndex + 1));
      } else {
        setActiveOption($selected); // stay if last
      }
    } else {
      // nothing selected/active → start at first
      const $first = $visible.first();
      if ($first.length) setActiveOption($first);
    }
  }
} else if (e.key === "ArrowUp") {
  if ($options.is(":visible")) {
    e.preventDefault();
    const $visible = $options.find(".option:visible");
    const $active = $options.find(".option.active:visible").first();
    const $selected = $options.find(".option.selected:visible").first();

    if ($active.length) {
      // already active → move to previous
      const currentIndex = $visible.index($active);
      if (currentIndex > 0) {
        setActiveOption($visible.eq(currentIndex - 1));
      }
    } else if ($selected.length) {
      // CHANGED: if selected exists but not active, jump to the PREVIOUS one
      const currentIndex = $visible.index($selected);
      if (currentIndex > 0) {
        setActiveOption($visible.eq(currentIndex - 1));
      } else {
        setActiveOption($selected); // stay if already first
      }
    } else {
      // nothing selected/active → start at first
      const $first = $visible.first();
      if ($first.length) setActiveOption($first);
    }
  }
} else if (e.key === "Tab") {
          $options.hide();
          $input.attr("aria-expanded", "false");
        }
      })
      .on("click", function () {
        showAllOptions();
        $input.focus(); // keep caret in input
      })
      .on("blur", function () {
        setTimeout(() => {
          if (!$container.find(":focus").length && !justSelected) {
            $options.hide();
            $input.attr("aria-expanded", "false");
            validateInput();
          }
          justSelected = false;
        }, 150);
      })
      .on("input change", function () {
        validateInput();
        const val = $input.val().trim();
        const $match = $options.find(".option").filter(function () {
          return $(this).text() === val;
        }).first();

        // CHANGED: clear both selected and active when input changes
        $options.find(".option").removeClass("selected active").attr("aria-selected", "false");
if ($match.length) {
  $match.addClass("selected");
  setActiveOption($match); // CHANGED: also make it active
}

      });

    // === Eventi opzioni ===
    $options
      .on("click", ".option", function () {
        justSelected = true;
        selectOption($(this));
      })
      .on("keydown", ".option", function (e) {
        const $visible = $options.find(".option:visible");
        const currentIndex = $visible.index(this);

        if (e.key === "Enter") {
          e.preventDefault();
          selectOption($(this));
        } else if (e.key === "ArrowDown") {
          e.preventDefault();
          if (currentIndex + 1 < $visible.length) {
            setActiveOption($visible.eq(currentIndex + 1));
          }
        } else if (e.key === "ArrowUp") {
          e.preventDefault();
          if (currentIndex > 0) {
            setActiveOption($visible.eq(currentIndex - 1));
          } else {
            $input.focus();
            $options.find(".option").removeClass("active").attr("aria-selected", "false");
          }
        }
      });

    // === Click fuori chiude ===
    $(document).on("click", function (e) {
      if (!$(e.target).closest(".combobox").length) {
        $options.hide();
        $input.attr("aria-expanded", "false");
      }
    });
  });
});
