(function() {
  var CONTAINER_ID = 'crank-toast-container';
  var nextToastId = 0;

  function ensureContainer() {
    var container = document.getElementById(CONTAINER_ID);
    if (container) return container;

    container = document.createElement('div');
    container.id = CONTAINER_ID;
    container.className = 'toast-stack';
    document.body.appendChild(container);
    return container;
  }

  function dismiss(toast) {
    if (!toast || !toast.parentNode) return;
    toast.classList.add('closing');
    window.setTimeout(function() {
      if (toast.parentNode) toast.parentNode.removeChild(toast);
    }, 180);
  }

  function notify(options) {
    var config = options || {};
    var duration = config.duration === 0 ? 0 : (config.duration || 3600);
    var toast = document.createElement('div');

    toast.id = 'toast_' + (++nextToastId);
    toast.className = 'toast-card toast-' + (config.type || 'info');
    toast.innerHTML =
      '<div class="toast-copy">' +
        (config.title ? '<div class="toast-title">' + config.title + '</div>' : '') +
        (config.message ? '<div class="toast-message">' + config.message + '</div>' : '') +
      '</div>' +
      '<button class="toast-close" type="button" aria-label="Dismiss">' +
        '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round">' +
          '<line x1="1" y1="1" x2="11" y2="11"></line>' +
          '<line x1="11" y1="1" x2="1" y2="11"></line>' +
        '</svg>' +
      '</button>';

    toast.querySelector('.toast-close').addEventListener('click', function() {
      dismiss(toast);
    });

    ensureContainer().appendChild(toast);

    if (duration > 0) {
      window.setTimeout(function() {
        dismiss(toast);
      }, duration);
    }

    return toast.id;
  }

  window.CrankUi = {
    notify: notify,
    success: function(message, title) {
      return notify({ type: 'success', title: title || 'Done', message: message });
    },
    error: function(message, title) {
      return notify({ type: 'error', title: title || 'Request failed', message: message });
    },
    info: function(message, title) {
      return notify({ type: 'info', title: title || 'Info', message: message });
    }
  };
}());
