(function (Drupal, once) {
  "use strict";

  let sKeyTimer = null;
  let sKeyPressed = false;

  /**
   * Show the hidden AI page enabled form item when 's' key is held for 3 seconds.
   */
  Drupal.behaviors.aiSettingsForm = {
    attach: function (context, settings) {
      once("ai-settings-form", "body", context).forEach((element) => {
        // Handle key down event
        element.addEventListener("keydown", (event) => {
          if (event.key.toLowerCase() === "s" && !sKeyPressed) {
            sKeyPressed = true;

            // Start the timer for 3 seconds
            sKeyTimer = setTimeout(() => {
              const hiddenElement = document.querySelector(
                ".js-form-item-ai-page-enabled",
              );
              if (hiddenElement) {
                hiddenElement.style.display = "block";
              }
            }, 1000);
          }
        });

        // Handle key up event
        element.addEventListener("keyup", (event) => {
          if (event.key.toLowerCase() === "s" && sKeyPressed) {
            sKeyPressed = false;

            // Clear the timer if 's' key is released before 3 seconds
            if (sKeyTimer) {
              clearTimeout(sKeyTimer);
              sKeyTimer = null;
            }
          }
        });

        // Handle window blur to clear timer if user switches away
        window.addEventListener("blur", () => {
          if (sKeyTimer) {
            clearTimeout(sKeyTimer);
            sKeyTimer = null;
            sKeyPressed = false;
          }
        });
      });
    },
  };
})(Drupal, once);
