/**
 * @file
 * FlowDrop Plugin Selector Component JavaScript.
 *
 * Handles radio button selection and syncs with hidden input for form submission.
 */

(function (Drupal) {
  "use strict";

  /**
   * Initialize plugin selector components.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.flowdropPluginSelector = {
    attach: function (context) {
      // Find all plugin selector containers.
      const selectors = context.querySelectorAll(
        "[data-flowdrop-plugin-selector]:not([data-flowdrop-initialized])"
      );

      selectors.forEach(function (selector) {
        initializeSelector(selector);
        selector.setAttribute("data-flowdrop-initialized", "true");
      });
    },

    detach: function (context, settings, trigger) {
      if (trigger !== "unload") {
        return;
      }

      const selectors = context.querySelectorAll(
        "[data-flowdrop-plugin-selector][data-flowdrop-initialized]"
      );

      selectors.forEach(function (selector) {
        // Remove radio change handlers
        if (selector._flowdropRadioHandlers) {
          selector._flowdropRadioHandlers.forEach(function (entry) {
            entry.radio.removeEventListener("change", entry.handler);
          });
          selector._flowdropRadioHandlers = null;
        }

        // Remove card click handlers
        if (selector._flowdropCardHandlers) {
          selector._flowdropCardHandlers.forEach(function (entry) {
            entry.card.removeEventListener("click", entry.handler);
          });
          selector._flowdropCardHandlers = null;
        }

        // Remove keydown handler
        if (selector._flowdropKeydownHandler) {
          selector.removeEventListener("keydown", selector._flowdropKeydownHandler);
          selector._flowdropKeydownHandler = null;
        }

        selector.removeAttribute("data-flowdrop-initialized");
      });
    },
  };

  /**
   * Initialize a single plugin selector.
   *
   * @param {HTMLElement} selector
   *   The plugin selector container element.
   */
  function initializeSelector(selector) {
    // Find the target hidden input by ID from data attribute.
    const targetInputId = selector.getAttribute("data-flowdrop-target-input");
    const hiddenInput = targetInputId
      ? document.getElementById(targetInputId)
      : null;
    const radios = selector.querySelectorAll("[data-flowdrop-plugin-radio]");
    const cards = selector.querySelectorAll(".fd-plugin-selector__card");

    if (radios.length === 0) {
      return;
    }

    // Store handler references for cleanup.
    selector._flowdropRadioHandlers = [];
    selector._flowdropCardHandlers = [];

    // Handle radio button changes.
    radios.forEach(function (radio) {
      var changeHandler = function () {
        if (this.checked) {
          // Update hidden input value if it exists.
          if (hiddenInput) {
            hiddenInput.value = this.value;
          }

          // Update card selected states.
          cards.forEach(function (card) {
            const cardPluginId = card.getAttribute("data-plugin-id");
            if (cardPluginId === radio.value) {
              card.classList.add("fd-plugin-selector__card--selected");
            } else {
              card.classList.remove("fd-plugin-selector__card--selected");
            }
          });

          // Dispatch a custom event for any listeners.
          const event = new CustomEvent("flowdrop:plugin-selector:selected", {
            detail: {
              pluginId: this.value,
              label: this.closest(".fd-plugin-selector__card")
                ?.querySelector(".fd-plugin-selector__title")
                ?.textContent,
            },
            bubbles: true,
          });
          selector.dispatchEvent(event);
        }
      };
      radio.addEventListener("change", changeHandler);
      selector._flowdropRadioHandlers.push({ radio: radio, handler: changeHandler });
    });

    // Handle card clicks for better UX (click anywhere on card).
    cards.forEach(function (card) {
      var clickHandler = function (e) {
        // Don't interfere if clicking directly on the radio.
        if (e.target.classList.contains("fd-plugin-selector__radio")) {
          return;
        }

        const radio = card.querySelector(".fd-plugin-selector__radio");
        if (radio && !radio.checked) {
          radio.checked = true;
          radio.dispatchEvent(new Event("change", { bubbles: true }));
        }
      };
      card.addEventListener("click", clickHandler);
      selector._flowdropCardHandlers.push({ card: card, handler: clickHandler });
    });

    // Handle keyboard navigation.
    var keydownHandler = function (e) {
      if (e.key === "ArrowDown" || e.key === "ArrowUp" ||
          e.key === "ArrowLeft" || e.key === "ArrowRight") {
        const focusedCard = document.activeElement?.closest(
          ".fd-plugin-selector__card"
        );
        if (!focusedCard) {
          return;
        }

        const allCards = Array.from(cards);
        const currentIndex = allCards.indexOf(focusedCard);

        let nextIndex;
        if (e.key === "ArrowDown" || e.key === "ArrowRight") {
          nextIndex = currentIndex + 1;
          if (nextIndex >= allCards.length) {
            nextIndex = 0;
          }
        } else {
          nextIndex = currentIndex - 1;
          if (nextIndex < 0) {
            nextIndex = allCards.length - 1;
          }
        }

        const nextCard = allCards[nextIndex];
        const nextRadio = nextCard?.querySelector(".fd-plugin-selector__radio");
        if (nextRadio) {
          nextRadio.focus();
          nextRadio.checked = true;
          nextRadio.dispatchEvent(new Event("change", { bubbles: true }));
          e.preventDefault();
        }
      }
    };
    selector.addEventListener("keydown", keydownHandler);
    selector._flowdropKeydownHandler = keydownHandler;
  }
})(Drupal);
