/**
 * Simplified Modal Component
 * Uses CSS visibility and opacity for robust animations.
 */
class Modal {
  constructor() {
    this.init();
  }

  init() {
    // Attach events only once the DOM is ready if possible, 
    // but document-level listeners are generally safe anytime.
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => this.attachEvents());
    } else {
      this.attachEvents();
    }
  }

  dispatch(name, el, detail = {}) {
    el.dispatchEvent(new CustomEvent(`modal:${name}`, {
      detail,
      bubbles: true,
      cancelable: true
    }));
  }

  updateAccessibility(modal, isActive) {
    const focusables = modal.querySelectorAll('a, button, input, select, textarea');
    focusables.forEach(el => {
      if (!isActive) {
        el.setAttribute('tabindex', '-1');
        el.setAttribute('aria-hidden', 'true');
      } else {
        el.removeAttribute('tabindex');
        el.removeAttribute('aria-hidden');
      }
    });
  }

  /**
   * Open modal
   */
  open(target, options = {}) {
    if (!target) return;

    let modal;
    if (typeof target === "string") {
      const selector = target.startsWith("#") || target.startsWith(".") ? target : `#${target}`;
      modal = document.querySelector(selector);
    } else {
      modal = target;
    }

    if (!modal) {
      console.warn(`Modal target not found: ${target}`);
      return;
    }

    this.dispatch("beforeOpen", modal);

    // Handle animation options
    if (options.animateIn === "none") {
      modal.classList.add("is-no-animation");
    } else {
      modal.classList.remove("is-no-animation");
    }

    modal.classList.remove("is-modal-out");
    modal.classList.add("is-active");

    // Remove inline display:none if present
    if (modal.style.display === "none") {
      modal.style.display = "";
    }

    document.body.classList.add("is-modal-active");

    this.dispatch("opened", modal);
  }

  /**
   * Close modal
   */
  close(el = null) {
    const modal = el || document.querySelector(".rt-modal.is-active");
    if (!modal) return;

    this.dispatch("beforeClose", modal);

    if (modal.classList.contains("is-no-animation")) {
      modal.classList.remove("is-active");
      modal.style.display = "none";
      document.body.classList.remove("is-modal-active");
      this.dispatch("closed", modal);
      return;
    }

    modal.classList.add("is-modal-out");
    modal.classList.remove("is-active");
    document.body.classList.remove("is-modal-active");

    // Clean up after animation finishes (400ms buffer)
    setTimeout(() => {
      modal.style.display = "none";
      modal.classList.remove("is-modal-out");
      this.dispatch("closed", modal);

      // Clean up trigger states
      if (modal.id) {
        document.querySelectorAll(`.js-modal[href="#${modal.id}"], .js-modal[data-target="${modal.id}"]`).forEach(t => t.classList.remove("is-active"));
      }
    }, 500); // Increased to 500ms for safety buffer
  }

  attachEvents() {
    document.addEventListener("click", (e) => {
      // Open trigger logic
      const trigger = e.target.closest(".js-modal");
      if (trigger && !trigger.classList.contains("disabled")) {
        e.preventDefault();

        // Try to get target from various sources
        const target = trigger.getAttribute("href") || trigger.getAttribute("data-target") || trigger.dataset.target;

        if (target && target !== "#") {
          this.open(target);
          return;
        }
      }

      // Close logic (Overlay or Close button)
      const closeBtn = e.target.closest(".js-modal-close, .rt-modal__close");
      const isOverlay = e.target.classList.contains("rt-modal__overlay");

      if (closeBtn || isOverlay) {
        e.preventDefault();
        const modal = e.target.closest(".rt-modal");
        if (modal) {
          this.close(modal);
        } else if (isOverlay) {
          // If clicking overlay, find the parent modal
          this.close(e.target.parentElement);
        }
      }
    });

    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") this.close();
    });
  }
}

// Global Init - Ensure single instance
document.addEventListener('DOMContentLoaded', () => {
  if (!window.rModal) {
    window.rtModal = new Modal();
  }
});