// Tailwind select picker (vanilla JS, no external CSS). Enhances any <select.tw-selectpicker>
(function () {
  const chevron = '<svg class="h-4 absolute top-3 right-3 w-4 text-slate-400 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>';
	const check = '<svg class="h-4 absolute top-3 right-3 w-4 text-slate-400 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>';
  const dot = (active) =>
    '<span class="inline-block h-2.5 w-2.5 rounded-full ' +
    (active ? "bg-indigo-500" : "bg-slate-300 dark:bg-slate-600") +
    '"></span>';

  function enhance(select) {
    if (select.dataset.enhanced === "true") return;
    select.dataset.enhanced = "true";
    select.refreshSelectpicker = () => rebuild();

    const isMultiple = select.multiple;
    // Hide the native select immediately to avoid flash before enhancement
    select.style.visibility = "hidden";
    select.style.display = "none";

    const placeholder = select.getAttribute("data-placeholder") || select.getAttribute("placeholder") || "Nothing selected";
    const enableSearch = select.hasAttribute("data-search") || select.getAttribute("data-live-search");		
	
		const selectClass = select.getAttribute("class") || "";
		
		

    const options = [];
    let hasExplicitSelection = false;
    Array.from(select.children).forEach((node) => {
      if (node.tagName === "OPTGROUP") {
        const group = node.label;
        Array.from(node.children).forEach((opt) => {
          const isSelected = opt.hasAttribute("selected"); // respect explicit selection only
          if (isSelected) hasExplicitSelection = true;
          options.push({ value: opt.value, label: opt.text, selected: isSelected, disabled: opt.disabled, group, element: opt });
        });
      } else if (node.tagName === "OPTION") {
        const isSelected = node.hasAttribute("selected"); // avoid auto-selecting first option
        if (isSelected) hasExplicitSelection = true;
        options.push({ value: node.value, label: node.text, selected: isSelected, disabled: node.disabled, group: null, element: node });
      }
    });

    // If no explicit selection and not multiple, clear native selection so placeholder shows
    if (!isMultiple && !hasExplicitSelection) {
      select.selectedIndex = -1;
      options.forEach((o) => (o.selected = false));
    }

    const wrapper = document.createElement("div");
    wrapper.className = "relative w-full";
    wrapper.dataset.selectpickerWrapper = "true";

    const trigger = document.createElement("button");
    trigger.type = "button";
    trigger.className = selectClass;
    const id = select.id || select.name;
    if (id) {
      trigger.id = select.id + "_trigger";
    }
    const triggerText = document.createElement("span");
    triggerText.className = "truncate mr-3";
    const triggerIcon = document.createElement("span");
    triggerIcon.innerHTML = chevron;
    trigger.appendChild(triggerText);
    trigger.appendChild(triggerIcon);

    const dropdown = document.createElement("div");
    dropdown.className = "fixed z-[10010] bg-white dark:bg-slate-800 rounded-lg shadow-xl border border-slate-200 dark:border-slate-700 origin-top transform opacity-0 scale-95 transition duration-150 hidden";
    dropdown.dataset.selectpickerFloating = "true";

    let searchInput = null;
    if (enableSearch) {
      const searchWrap = document.createElement("div");
      searchWrap.className = "p-2 border-b border-slate-100 dark:border-slate-700";
      searchInput = document.createElement("input");
      searchInput.type = "text";
      searchInput.placeholder = "Search...";
      searchInput.className = "w-full bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-1.5 text-sm text-slate-700 dark:text-slate-200 dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30";
      searchWrap.appendChild(searchInput);
      dropdown.appendChild(searchWrap);
    }

    // Multi-select actions
    if (isMultiple) {
      const actions = document.createElement("div");
      actions.className = "flex items-center  gap-2 px-3 py-2 border-b border-slate-100 dark:border-slate-700 text-xs ";
      const selectAllBtn = document.createElement("button");
      selectAllBtn.type = "button";
      selectAllBtn.className = "px-2 py-1 rounded border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-700 dark:text-slate-200 hover:border-indigo-500";
      selectAllBtn.textContent = "Select All";
      selectAllBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        options.forEach((o) => {
          if (!o.disabled) {
            o.selected = true;
            o.element.selected = true;
          }
        });
        select.dispatchEvent(new Event("change", { bubbles: true }));
        renderOptions(searchInput ? searchInput.value : "");
        updateTrigger();
      });
      const deselectAllBtn = document.createElement("button");
      deselectAllBtn.type = "button";
      deselectAllBtn.className = "px-2 py-1 rounded border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-700 dark:text-slate-200 hover:border-indigo-500";
      deselectAllBtn.textContent = "Deselect All";
      deselectAllBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        options.forEach((o) => {
          if (!o.disabled) {
            o.selected = false;
            o.element.selected = false;
          }
        });
        select.dispatchEvent(new Event("change", { bubbles: true }));
        renderOptions(searchInput ? searchInput.value : "");
        updateTrigger();
      });
      actions.appendChild(selectAllBtn);
      actions.appendChild(deselectAllBtn);
      dropdown.appendChild(actions);
    }

    const list = document.createElement("ul");
    list.className = "max-h-64 overflow-y-auto py-1 space-y-1";
    dropdown.appendChild(list);

    function renderOptions(filter = "") {
      list.innerHTML = "";
      const lf = filter.toLowerCase();
      let currentGroup = null;
      let matches = 0;
      options.forEach((opt, idx) => {
        if (lf && !opt.label.toLowerCase().includes(lf)) return;
        matches++;
        if (opt.group && opt.group !== currentGroup) {
          currentGroup = opt.group;
          const gh = document.createElement("li");
          gh.className = "px-3 pt-2 text-[11px] font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500";
          gh.textContent = currentGroup;
          list.appendChild(gh);
        }
        const li = document.createElement("li");
        li.className =
          "relative px-3 py-2 flex items-center justify-between cursor-pointer transition-colors " +
					(opt.selected ? "bg-indigo-50 dark:bg-slate-700 " : "") +
          (opt.disabled ? "opacity-50 cursor-not-allowed bg-slate-50 dark:bg-slate-900" : "hover:bg-indigo-50 dark:hover:bg-slate-700");
        li.dataset.index = idx;

        const textSpan = document.createElement("span");
        textSpan.className = "text-sm text-slate-700 dark:text-slate-200";
        textSpan.textContent = opt.label;
        const indicator = document.createElement("span");
        indicator.className = "ml-2 inline-flex items-center justify-center";
        indicator.innerHTML = opt.selected ? check : '';

        li.appendChild(textSpan);
        li.appendChild(indicator);

        if (!opt.disabled) {
          li.addEventListener("click", (e) => {
            e.stopPropagation();
            toggleOption(idx);
          });
        }
        list.appendChild(li);
      });
      if (!matches) {
        const li = document.createElement("li");
        li.className = "text-sm text-slate-400 dark:text-slate-500 px-3 py-3 text-center";
        li.textContent = "No results";
        list.appendChild(li);
      }
    }

    function updateTrigger() {
      const sel = options.filter((o) => o.selected);
      if (!sel.length) {
        triggerText.textContent = placeholder;
        triggerText.classList.add("text-slate-400");
      } else {
        triggerText.classList.remove("text-slate-400");
        if (isMultiple) {										
          if (sel.length === options.length) {
            triggerText.textContent = `All selected (${sel.length})`;
          } else if (sel.length <= 3) {
            triggerText.textContent = sel.map((o) => o.label).join(", ");
          } else {
            const first = sel.slice(0, 3).map((o) => o.label).join(", ");
            const remaining = sel.length - 3;
            triggerText.textContent = `${first} +${remaining}`;
          }
        } else {
          triggerText.textContent = sel[0].label;
        }
      }
    }

    function toggleOption(index) {
      const opt = options[index];
      if (isMultiple) {
        opt.selected = !opt.selected;
      } else {
        options.forEach((o) => (o.selected = false));
        opt.selected = true;
        close();
      }
      opt.element.selected = opt.selected;
      select.dispatchEvent(new Event("change", { bubbles: true }));
      renderOptions(searchInput ? searchInput.value : "");
      updateTrigger();
    }

    function positionDropdown() {
      const rect = trigger.getBoundingClientRect();
      const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
      const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;
      const margin = 8;
      const preferredHeight = 320;
      const spaceBelow = viewportHeight - rect.bottom - margin;
      const spaceAbove = rect.top - margin;
      const openUpward = spaceBelow < 220 && spaceAbove > spaceBelow;
      const maxHeight = Math.max(160, Math.min(preferredHeight, openUpward ? spaceAbove - 8 : spaceBelow - 8));

      dropdown.style.width = rect.width + "px";
      dropdown.style.left = Math.max(margin, Math.min(rect.left, viewportWidth - rect.width - margin)) + "px";
      dropdown.style.top = openUpward
        ? Math.max(margin, rect.top - maxHeight - margin) + "px"
        : Math.min(viewportHeight - maxHeight - margin, rect.bottom + margin) + "px";

      list.style.maxHeight = Math.max(96, maxHeight - (enableSearch ? 60 : 8) - (isMultiple ? 46 : 0)) + "px";
      dropdown.dataset.placement = openUpward ? "top" : "bottom";
    }

    function handleViewportChange() {
      if (!dropdown.classList.contains("hidden")) {
        positionDropdown();
      }
    }

    function open() {
      positionDropdown();
      dropdown.classList.remove("hidden");
      requestAnimationFrame(() => {
        dropdown.classList.remove("opacity-0", "scale-95");
        dropdown.classList.add("opacity-100", "scale-100");
      });
      const icon = trigger.querySelector("svg");
      if (icon) icon.classList.add("rotate-180");
      if (searchInput) searchInput.focus();
      document.addEventListener("click", handleOutside);
      window.addEventListener("resize", handleViewportChange);
      window.addEventListener("scroll", handleViewportChange, true);
    }

    function close() {
      dropdown.classList.remove("opacity-100", "scale-100");
      dropdown.classList.add("opacity-0", "scale-95");
      const icon = trigger.querySelector("svg");
      if (icon) icon.classList.remove("rotate-180");
      setTimeout(() => {
        if (!dropdown.classList.contains("opacity-100")) dropdown.classList.add("hidden");
      }, 120);
      document.removeEventListener("click", handleOutside);
      window.removeEventListener("resize", handleViewportChange);
      window.removeEventListener("scroll", handleViewportChange, true);
      if (searchInput) {
        searchInput.value = "";
        renderOptions();
      }
    }

    function handleOutside(e) {
      if (!wrapper.contains(e.target) && !dropdown.contains(e.target)) {
        close();
      }
    }

    trigger.addEventListener("click", (e) => {
      e.stopPropagation();
      dropdown.classList.contains("hidden") ? open() : close();
    });
    if (enableSearch && searchInput) {
      searchInput.addEventListener("click", (e) => e.stopPropagation());
      searchInput.addEventListener("input", (e) => renderOptions(e.target.value));
    }

    renderOptions();
    updateTrigger();

    function rebuild() {
      // reset options from native select
      options.length = 0;
      hasExplicitSelection = false;
      Array.from(select.children).forEach((node) => {
        if (node.tagName === "OPTGROUP") {
          const group = node.label;
          Array.from(node.children).forEach((opt) => {
            const isSelected = opt.selected || opt.hasAttribute("selected");
            if (isSelected) hasExplicitSelection = true;
            options.push({ value: opt.value, label: opt.text, selected: isSelected, disabled: opt.disabled, group, element: opt });
          });
        } else if (node.tagName === "OPTION") {
          const isSelected = optHasSelected(node);
          if (isSelected) hasExplicitSelection = true;
          options.push({ value: node.value, label: node.text, selected: isSelected, disabled: node.disabled, group: null, element: node });
        }
      });
      if (!isMultiple && !hasExplicitSelection) {
        select.selectedIndex = -1;
        options.forEach((o) => (o.selected = false));
      }
      renderOptions(searchInput ? searchInput.value : "");
      updateTrigger();
    }

    function optHasSelected(node) {
      return node.selected || node.hasAttribute("selected");
    }

    select.classList.add("hidden");
    select.parentNode.insertBefore(wrapper, select.nextSibling);
    wrapper.appendChild(trigger);
    document.body.appendChild(dropdown);
  }

  function init() {
    document.querySelectorAll("select.tw-selectpicker").forEach(enhance);
  }

  // jQuery bridge for compatibility: $(el).selectpicker() / $(el).selectpicker('refresh')
  if (window.jQuery) {
    const $ = window.jQuery;
    $.fn.selectpicker = function (action) {
      if (action === "refresh") {
        this.each(function () {
          if (typeof this.refreshSelectpicker === "function") {
            this.refreshSelectpicker();
          }
        });
        return this;
      }
      // default initialize
      this.each(function () {
        enhance(this);
      });
      return this;
    };
  }

  // expose global refresh similar to bootstrap select
  window.refreshSelectpicker = function (selector) {
    if (selector && selector.tagName === "SELECT") {
      if (typeof selector.refreshSelectpicker === "function") {
        selector.refreshSelectpicker();
      } else {
        enhance(selector);
      }
      return;
    }
    document.querySelectorAll(selector || "select.tw-selectpicker").forEach((el) => {
      if (typeof el.refreshSelectpicker === "function") {
        el.refreshSelectpicker();
      }
    });
  };

  if (document.readyState === "interactive" || document.readyState === "complete") {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init);
  }
})();
