/**
 * RagGo Toast Notification System
 *
 * Usage:
 *   RagGoToast.success('Document deleted')
 *   RagGoToast.error('Something went wrong')
 *   RagGoToast.info('Exported to file')
 *   RagGoToast.warning('Large file — may take several minutes')
 *
 * Also listens for HTMX afterRequest events to auto-show toasts
 * from HX-Trigger headers containing raggo-toast-* events.
 */
;(function () {
  'use strict';

  var MAX_TOASTS = 5;
  var AUTO_DISMISS_MS = 4000;
  var container = null;

  function ensureContainer() {
    if (container && document.body.contains(container)) return container;
    container = document.createElement('div');
    container.id = 'toast-container';
    container.setAttribute('aria-live', 'polite');
    container.setAttribute('aria-atomic', 'false');
    document.body.appendChild(container);
    return container;
  }

  function makeSvg(paths) {
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '16');
    svg.setAttribute('height', '16');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    paths.forEach(function (def) {
      var el = document.createElementNS(ns, def[0]);
      var attrs = def[1];
      Object.keys(attrs).forEach(function (k) { el.setAttribute(k, attrs[k]); });
      svg.appendChild(el);
    });
    return svg;
  }

  function getIcon(type) {
    switch (type) {
      case 'success':
        return makeSvg([
          ['path', { d: 'M22 11.08V12a10 10 0 1 1-5.93-9.14' }],
          ['polyline', { points: '22 4 12 14.01 9 11.01' }]
        ]);
      case 'error':
        return makeSvg([
          ['circle', { cx: '12', cy: '12', r: '10' }],
          ['line', { x1: '15', y1: '9', x2: '9', y2: '15' }],
          ['line', { x1: '9', y1: '9', x2: '15', y2: '15' }]
        ]);
      case 'warning':
        return makeSvg([
          ['path', { d: 'M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z' }],
          ['line', { x1: '12', y1: '9', x2: '12', y2: '13' }],
          ['line', { x1: '12', y1: '17', x2: '12.01', y2: '17' }]
        ]);
      default: // info
        return makeSvg([
          ['circle', { cx: '12', cy: '12', r: '10' }],
          ['line', { x1: '12', y1: '16', x2: '12', y2: '12' }],
          ['line', { x1: '12', y1: '8', x2: '12.01', y2: '8' }]
        ]);
    }
  }

  function makeCloseIcon() {
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '14');
    svg.setAttribute('height', '14');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2.5');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    var l1 = document.createElementNS(ns, 'line');
    l1.setAttribute('x1', '18'); l1.setAttribute('y1', '6');
    l1.setAttribute('x2', '6');  l1.setAttribute('y2', '18');
    var l2 = document.createElementNS(ns, 'line');
    l2.setAttribute('x1', '6');  l2.setAttribute('y1', '6');
    l2.setAttribute('x2', '18'); l2.setAttribute('y2', '18');
    svg.appendChild(l1);
    svg.appendChild(l2);
    return svg;
  }

  function createToast(message, type) {
    var c = ensureContainer();

    // Enforce max stacked
    while (c.children.length >= MAX_TOASTS) {
      c.removeChild(c.firstChild);
    }

    var toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.setAttribute('role', 'status');

    // Icon
    var iconWrap = document.createElement('span');
    iconWrap.className = 'toast-icon';
    iconWrap.appendChild(getIcon(type));
    toast.appendChild(iconWrap);

    // Message
    var msg = document.createElement('span');
    msg.className = 'toast-message';
    msg.textContent = message;
    toast.appendChild(msg);

    // Close button
    var close = document.createElement('button');
    close.className = 'toast-close';
    close.setAttribute('aria-label', 'Dismiss');
    close.appendChild(makeCloseIcon());
    close.addEventListener('click', function () {
      dismissToast(toast);
    });
    toast.appendChild(close);

    c.appendChild(toast);

    // Trigger enter animation on next frame
    requestAnimationFrame(function () {
      toast.classList.add('toast-enter');
    });

    // Auto-dismiss only for success and info toasts; error/warning stay until manually closed
    if (type !== 'error' && type !== 'warning') {
      // Add countdown bar for auto-dismiss toasts
      var countdown = document.createElement('div');
      countdown.className = 'toast-countdown';
      toast.appendChild(countdown);
      // Start animation on next frame so transition triggers
      requestAnimationFrame(function () {
        countdown.style.width = '0%';
      });

      var timer = setTimeout(function () {
        dismissToast(toast);
      }, AUTO_DISMISS_MS);

      toast._timer = timer;
    }

    return toast;
  }

  function dismissToast(toast) {
    if (!toast || !toast.parentNode) return;
    clearTimeout(toast._timer);
    toast.classList.add('toast-exit');
    toast.addEventListener('animationend', function () {
      if (toast.parentNode) toast.parentNode.removeChild(toast);
    });
  }

  // Public API
  window.RagGoToast = {
    success: function (msg) { return createToast(msg, 'success'); },
    error:   function (msg) { return createToast(msg, 'error'); },
    info:    function (msg) { return createToast(msg, 'info'); },
    warning: function (msg) { return createToast(msg, 'warning'); }
  };

  // Listen for HTMX custom trigger events for toasts
  document.addEventListener('htmx:afterRequest', function (evt) {
    var xhr = evt.detail.xhr;
    if (!xhr) return;
    var trigger = xhr.getResponseHeader('HX-Trigger');
    if (!trigger) return;
    try {
      var parsed = JSON.parse(trigger);
      if (parsed['toast-success']) RagGoToast.success(parsed['toast-success']);
      if (parsed['toast-error'])   RagGoToast.error(parsed['toast-error']);
      if (parsed['toast-info'])    RagGoToast.info(parsed['toast-info']);
      if (parsed['toast-warning']) RagGoToast.warning(parsed['toast-warning']);
    } catch (e) {
      // HX-Trigger might be a plain string event name, not JSON -- that is fine
    }
  });
})();
