// Fluent UI-inspired Modal System for WP-Admin

(function() {
  // Creates and shows a modal with given content and options
  window.FluentUIModal = {
    show: function({ title = '', body = '', footer = '', onClose = null } = {}) {
      // Remove any existing modal
      FluentUIModal.hide();

      // Create overlay
      const overlay = document.createElement('div');
      overlay.className = 'fluentui-modal-overlay';

      // Create modal container
      const modal = document.createElement('div');
      modal.className = 'fluentui-modal';
      overlay.appendChild(modal);

      // Modal header
      const header = document.createElement('div');
      header.className = 'fluentui-modal-header';

      const titleElem = document.createElement('span');
      titleElem.textContent = title;
      header.appendChild(titleElem);

      const closeBtn = document.createElement('button');
      closeBtn.className = 'fluentui-modal-close';
      closeBtn.setAttribute('aria-label', 'Close');
      closeBtn.innerHTML = '&times;';
      closeBtn.onclick = function() {
        FluentUIModal.hide();
        if (typeof onClose === 'function') onClose();
      };
      header.appendChild(closeBtn);

      modal.appendChild(header);

      // Modal body
      const bodyElem = document.createElement('div');
      bodyElem.className = 'fluentui-modal-body';
      bodyElem.innerHTML = body;
      modal.appendChild(bodyElem);

      // Modal footer
      if (footer) {
        const footerElem = document.createElement('div');
        footerElem.className = 'fluentui-modal-footer';
        footerElem.innerHTML = footer;
        modal.appendChild(footerElem);
      }

      // Dismiss modal on overlay click
      overlay.addEventListener('click', function(e){
        if (e.target === overlay) {
          FluentUIModal.hide();
          if (typeof onClose === 'function') onClose();
        }
      });

      // Append overlay to body
      document.body.appendChild(overlay);

      // Focus modal for accessibility
      setTimeout(() => {
        modal.setAttribute('tabindex', '-1');
        modal.focus();
      }, 50);
    },

    hide: function() {
      const overlay = document.querySelector('.fluentui-modal-overlay');
      if (overlay) overlay.remove();
    }
  };
})();