/**
 * toast.mjs — Toast notification component
 * Shows brief, non-blocking messages (success, error, warning, info)
 */

import store from '../store.mjs';
import eventBus, { EVENTS } from '../event-bus.mjs';
import { $, createElement, icon } from '../utils/dom.mjs';

const MAX_VISIBLE = 5;
const ICON_MAP = {
  success: 'check-circle',
  error: 'alert-circle',
  warning: 'alert-triangle',
  info: 'info'
};

let container = null;
let activeToasts = [];

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

  // Subscribe to NOTIFICATION events from the event bus
  eventBus.on(EVENTS.NOTIFICATION, (data) => {
    if (data && data.message) {
      show({
        message: data.message,
        type: data.type || 'info',
        duration: data.duration || 5000
      });
    }
  });
}

function show({ message, type = 'info', duration = 5000 }) {
  if (!container) init();

  // Enforce max visible toasts — remove oldest when exceeded
  while (activeToasts.length >= MAX_VISIBLE) {
    _removeToast(activeToasts[0]);
  }

  const iconName = ICON_MAP[type] || ICON_MAP.info;

  const closeBtn = createElement('button', {
    className: 'toast-close',
    'aria-label': 'Dismiss notification'
  }, [icon('x', { size: 14 })]);

  const toast = createElement('div', {
    className: `toast toast-${type}`,
    role: 'alert',
    'aria-live': 'polite'
  }, [
    createElement('span', { className: 'toast-icon' }, [icon(iconName, { size: 20 })]),
    createElement('span', { className: 'toast-content' }, [message]),
    closeBtn
  ]);

  // Close on button click
  closeBtn.addEventListener('click', () => {
    _removeToast(toast);
  });

  container.appendChild(toast);
  activeToasts.push(toast);

  // Auto-dismiss after duration
  if (duration > 0) {
    toast._dismissTimer = setTimeout(() => {
      _removeToast(toast);
    }, duration);
  }

  return toast;
}

function _removeToast(toast) {
  if (!toast || !toast.parentNode) return;

  // Clear auto-dismiss timer
  if (toast._dismissTimer) {
    clearTimeout(toast._dismissTimer);
    toast._dismissTimer = null;
  }

  // Play exit animation
  toast.classList.add('removing');

  const onEnd = () => {
    toast.removeEventListener('animationend', onEnd);
    if (toast.parentNode) {
      toast.parentNode.removeChild(toast);
    }
    const idx = activeToasts.indexOf(toast);
    if (idx !== -1) activeToasts.splice(idx, 1);
  };

  toast.addEventListener('animationend', onEnd);

  // Fallback in case animationend does not fire
  setTimeout(onEnd, 300);
}

function success(message) {
  return show({ message, type: 'success' });
}

function error(message) {
  return show({ message, type: 'error' });
}

function warning(message) {
  return show({ message, type: 'warning' });
}

function info(message) {
  return show({ message, type: 'info' });
}

export { init, show, success, error, warning, info };
