(function initFivaDropdownEngine(global) {
  "use strict";

  const DROPDOWN_VERSION = "2026-05-14-human-dropdown";
  if (global.FIVA?.DropdownEngine?.version === DROPDOWN_VERSION) return;

  const HumanSelect = global.FIVA?.HumanDropdownSelect || global.FIVA?.HumanSelectOption;

  function normalize(value = "") {
    return HumanSelect?.normalize
      ? HumanSelect.normalize(value)
      : String(value || "").trim().toUpperCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
  }

  function validOptions(select, isPlaceholder) {
    const options = HumanSelect?.validOptions
      ? HumanSelect.validOptions(select)
      : Array.from(select?.options || []).filter((option) => String(option.value || "").trim());
    return typeof isPlaceholder === "function" ? options.filter((option) => !isPlaceholder(option)) : options;
  }

  async function waitForOptions(select, options = {}) {
    if (!HumanSelect?.waitForDropdownReady) return validOptions(select, options.isPlaceholder).length > 0;
    const result = await HumanSelect.waitForDropdownReady(select, options);
    return result.ready === true;
  }

  async function selectOption(select, option, options = {}) {
    if (!HumanSelect?.applyHumanSelection) return false;
    return HumanSelect.applyHumanSelection(select, option, options);
  }

  async function choose(select, options = {}) {
    if (!HumanSelect?.choose) {
      return { success: false, reason: "human_dropdown_missing", attempts: 0 };
    }
    return HumanSelect.choose(select, options);
  }

  const DropdownEngine = Object.freeze({
    version: DROPDOWN_VERSION,
    choose,
    normalize,
    selectOption,
    validOptions,
    waitForOptions
  });

  global.FIVA = Object.assign(global.FIVA || {}, { DropdownEngine });
})(typeof globalThis !== "undefined" ? globalThis : this);
