import "./custom-select.css";
import "./admin-term-meta.css";
import { initLegacyCustomSelects } from "./custom-select";

jQuery(document).ready(function ($) {
  function initColorPicker($input) {
    if (!$input || !$input.length) {
      return;
    }
    if ($input.data("wpColorPicker")) {
      return;
    }

    let closeTimer = null;
    $input.wpColorPicker({
      change: function (event) {
        // Close shortly after a color is selected (debounced so dragging doesn't instantly close).
        if (closeTimer) {
          window.clearTimeout(closeTimer);
        }
        closeTimer = window.setTimeout(function () {
          try {
            $(event.target).wpColorPicker("close");
          } catch (e) {
            // Ignore close errors from picker instances that have already detached.
          }
        }, 200);
      },
    });
  }

  // Initialize any color inputs already on the screen.
  $(".b3-wvs-color-picker").each(function () {
    initColorPicker($(this));
  });

  initLegacyCustomSelects($, $(document), "#b3_wvs_type");

  // Close open pickers when the interaction happens outside the picker UI.
  $(document).on("mousedown touchstart", function (e) {
    if (!$(e.target).closest(".wp-picker-container").length) {
      $(".b3-wvs-color-picker").each(function () {
        const $this = $(this);
        if ($this.data("wpColorPicker")) {
          $this.wpColorPicker("close");
        }
      });
    }
  });

  function toggleFields(type) {
    const $colorField = $(".b3-wvs-color-field");
    const $colorLabel = $colorField.find('label[for="b3_wvs_color"]').first();
    const $labelField = $(".b3-wvs-label-field");
    const defaultLabel = String($colorField.data("labelDefault") || "Color");
    const buttonLabel = String($colorField.data("labelButton") || defaultLabel);

    if ($colorLabel.length) {
      $colorLabel.text(type === "button" ? buttonLabel : defaultLabel);
    }

    $colorField.hide();
    $labelField.hide();

    if (type === "color" || type === "button") {
      $colorField.show();
      initColorPicker($("#b3_wvs_color"));
    } else {
      // Clear base color state when a different type owns the field set.
      $("#b3_wvs_color").val("");
      try {
        $("#b3_wvs_color").wpColorPicker("color", "");
      } catch (e) {
        // Ignore reset errors from picker instances that have not initialized yet.
      }
      $("#b3_wvs_color").trigger("change");
    }

    if (type === "button") {
      $labelField.show();
    }
  }

  $(document).on("change", "#b3_wvs_type", function () {
    toggleFields($(this).val());
  });

  // Normalize the initial field state and clear stale hidden values.
  toggleFields($("#b3_wvs_type").val());
});
