/**
 * Alerts / toasts component.
 * - Event delegation for .alert__dismiss (close on click).
 * - Toast.show() to open floating toasts; Toast.close() to remove programmatically.
 *
 * Markup: floating toasts are appended to a container (default #floating-toasts).
 * Ensure the page has <div class="alerts--floating" id="floating-toasts"></div> or pass container in show().
 *
 * @example
 * Toast.show({ variant: 'error', message: 'Something went wrong.' });
 * Toast.show({ variant: 'success', message: 'Saved.', container: '#my-toasts' });
 * const el = Toast.show({ variant: 'info', message: 'Hello' });
 * Toast.close(el);
 */
const VARIANTS = ['error', 'warning', 'success', 'info'];

const DEFAULT_CONTAINER = '#floating-toasts';

function getContainer(container) {
  if (!container) return document.querySelector(DEFAULT_CONTAINER);
  if (typeof container === 'string') return document.querySelector(container);
  if (container?.nodeType === 1) return container;
  return document.querySelector(DEFAULT_CONTAINER);
}

function createToast(variant, message) {
  const el = document.createElement('div');
  el.className = `alert alert--floating alert--${variant}`;
  el.setAttribute('role', 'alert');
  el.innerHTML =
    `<p class="alert__message">${escapeHtml(message)}</p>` +
    '<button type="button" class="alert__dismiss" aria-label="Dismiss"><i class="fa-solid fa-xmark" aria-hidden="true"></i></button>';
  return el;
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

const Toast = {
  /**
   * Show a floating toast.
   * @param {Object} options - { variant: 'error'|'warning'|'success'|'info', message: string, container?: string|Element }
   * @returns {HTMLElement|null} The toast element, or null if container not found.
   */
  show(options = {}) {
    const variant = VARIANTS.includes(options.variant) ? options.variant : 'info';
    const message = options.message ?? '';
    const container = getContainer(options.container);
    if (!container) return null;
    const el = createToast(variant, message);
    container.appendChild(el);
    return el;
  },

  /**
   * Remove a toast element from the DOM.
   * @param {HTMLElement} el - The toast element returned by show().
   */
  close(el) {
    if (el?.parentNode) el.remove();
  }
};

function initDismissDelegation() {
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.alert__dismiss')) return;
    const alert = e.target.closest('.alert');
    if (alert) alert.remove();
  });
}

initDismissDelegation();

window.Toast = Toast;
