/**
 * modal.mjs — Modal dialog component
 * Shows centered dialogs with glass styling, focus trapping, and confirm/cancel flows
 */

import store from '../store.mjs';
import { $, createElement, icon } from '../utils/dom.mjs';

let container = null;
let activeModal = null;
let _escapeHandler = null;

function init() {
  container = $('.modal-container');
  if (!container) {
    container = createElement('div', { className: 'modal-container' });
    document.body.appendChild(container);
  }
}

function show({ title, content, actions = [], closable = true }) {
  if (!container) init();

  // Clean any existing modal
  _clearModal();

  // Build header
  const headerChildren = [
    createElement('h2', { className: 'modal-title' }, [title])
  ];

  if (closable) {
    const closeBtn = createElement('button', {
      className: 'modal-close',
      'aria-label': 'Close dialog'
    }, [icon('x', { size: 18 })]);
    closeBtn.addEventListener('click', close);
    headerChildren.push(closeBtn);
  }

  const header = createElement('div', { className: 'modal-header' }, headerChildren);

  // Build body
  const body = createElement('div', { className: 'modal-body' });
  if (typeof content === 'string') {
    body.innerHTML = content;
  } else if (content instanceof Node) {
    body.appendChild(content);
  }

  // Build footer with action buttons
  const footerChildren = actions.map(action => {
    const btn = createElement('button', {
      className: action.className || 'glass-button'
    }, [action.label]);
    if (action.onClick) {
      btn.addEventListener('click', action.onClick);
    }
    return btn;
  });

  const footer = footerChildren.length > 0
    ? createElement('div', { className: 'modal-footer' }, footerChildren)
    : null;

  // Build backdrop
  const backdrop = createElement('div', { className: 'modal-backdrop' });
  if (closable) {
    backdrop.addEventListener('click', close);
  }

  // Assemble dialog
  const dialogChildren = [header, body];
  if (footer) dialogChildren.push(footer);

  const dialog = createElement('div', {
    className: 'modal-dialog',
    role: 'dialog',
    'aria-modal': 'true',
    'aria-labelledby': 'modal-title'
  }, dialogChildren);

  // Clear container and populate
  container.innerHTML = '';
  container.appendChild(backdrop);
  container.appendChild(dialog);
  container.classList.add('active');

  activeModal = { dialog, closable };

  // Escape key handler
  if (closable) {
    _escapeHandler = (e) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        close();
      }
    };
    document.addEventListener('keydown', _escapeHandler);
  }

  // Trap focus inside the dialog
  _trapFocus(dialog);
}

function close() {
  if (!container) return;

  container.classList.remove('active');

  // Cleanup escape handler
  if (_escapeHandler) {
    document.removeEventListener('keydown', _escapeHandler);
    _escapeHandler = null;
  }

  // Allow transition to complete before clearing DOM
  setTimeout(() => {
    _clearModal();
  }, 300);
}

function _clearModal() {
  if (container) {
    container.innerHTML = '';
    container.classList.remove('active');
  }
  activeModal = null;
}

function confirm({ title, message, confirmLabel = 'Confirm', cancelLabel = 'Cancel' }) {
  return new Promise((resolve) => {
    show({
      title,
      content: message,
      closable: true,
      actions: [
        {
          label: cancelLabel,
          className: 'glass-button',
          onClick: () => {
            close();
            resolve(false);
          }
        },
        {
          label: confirmLabel,
          className: 'glass-button glass-button-accent',
          onClick: () => {
            close();
            resolve(true);
          }
        }
      ]
    });
  });
}

function _trapFocus(dialog) {
  // Focus the first focusable element inside the dialog
  requestAnimationFrame(() => {
    const focusableSelectors = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
    const focusable = dialog.querySelectorAll(focusableSelectors);
    if (focusable.length > 0) {
      focusable[0].focus();
    }

    // Trap tab navigation within the dialog
    dialog.addEventListener('keydown', (e) => {
      if (e.key !== 'Tab') return;

      const focusableEls = dialog.querySelectorAll(focusableSelectors);
      if (focusableEls.length === 0) return;

      const first = focusableEls[0];
      const last = focusableEls[focusableEls.length - 1];

      if (e.shiftKey) {
        if (document.activeElement === first) {
          e.preventDefault();
          last.focus();
        }
      } else {
        if (document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
      }
    });
  });
}

export { init, show, close, confirm };
