// Toast Notification System
const toast = (function () {
  let container = null;
  let toastCounter = 0;

  const defaultOptions = {
    autoClose: 1200,
    position: "top-right",
    closeButton: true,
    progressBar: true,
    className: "",
  };

  const icons = {
    success: "✓",
    error: "✕",
    warning: "⚠",
    info: "ℹ",
  };

  function createContainer(position) {
    if (!container || container.className.indexOf(position) === -1) {
      if (container) {
        container.remove();
      }

      container = document.createElement("div");
      container.className = `toast-container ${position}`;
      document.body.appendChild(container);
    }
    return container;
  }

  function createToast(message, type, options) {
    const opt = { ...defaultOptions, ...options };
    const container = createContainer(opt.position);
    const toastId = `toast-${++toastCounter}`;

    const toast = document.createElement("div");
    toast.id = toastId;
    toast.className = `toast toast-${type} ${opt.className}`;

    const icon = document.createElement("div");
    icon.className = "toast-icon";
    icon.textContent = icons[type];

    const content = document.createElement("div");
    content.className = "toast-content";

    const messageEl = document.createElement("div");
    messageEl.className = "toast-message";
    messageEl.textContent = message;
    content.appendChild(messageEl);

    toast.appendChild(icon);
    toast.appendChild(content);

    if (opt.closeButton) {
      const closeBtn = document.createElement("button");
      closeBtn.className = "toast-close";
      closeBtn.innerHTML = "×";
      closeBtn.onclick = () => removeToast(toastId);
      toast.appendChild(closeBtn);
    }

    if (opt.progressBar && opt.autoClose) {
      const progress = document.createElement("div");
      progress.className = "toast-progress";
      progress.style.animationDuration = `${opt.autoClose}ms`;
      toast.appendChild(progress);
    }

    container.appendChild(toast);

    if (opt.autoClose) {
      setTimeout(() => removeToast(toastId), opt.autoClose);
    }

    return toastId;
  }

  function removeToast(toastId) {
    const toast = document.getElementById(toastId);
    if (toast) {
      toast.classList.add("toast-exit");
      setTimeout(() => {
        toast.remove();

        if (container && container.children.length === 0) {
          container.remove();
          container = null;
        }
      }, 300);
    }
  }

  return {
    success: (message, options) => createToast(message, "success", options),
    error: (message, options) => createToast(message, "error", options),
    warning: (message, options) => createToast(message, "warning", options),
    info: (message, options) => createToast(message, "info", options),
    dismiss: (toastId) => removeToast(toastId),
  };
})();
