// =========================================================
// FILE: toast.js
// =========================================================

let activeToasts = [];

export function showToast(
  message,
  type = "success",
  duration = 3500
) {
  const container = document.getElementById("toastContainer");

  if (!container) {
    console.warn("Toast container not found.");
    return;
  }

  if (!message) return;

  const toast = document.createElement("div");

  toast.className = `toast toast-${type}`;

  let icon = "●";

  switch (type) {
    case "error":
      icon = "✕";
    break;

    case "warning":
      icon = "▲";
    break;

    case "info":
      icon = "●";
    break;

    default:
      icon = "✓";
  }

  toast.innerHTML = `
    <div class="toast-icon">${icon}</div>

    <div class="toast-content">
      <div class="toast-title">
        ${getToastTitle(type)}
      </div>

      <div class="toast-message">
        ${message}
      </div>
    </div>

    <button class="toast-close-btn">
      ✕
    </button>
  `;

  container.appendChild(toast);

  activeToasts.push(toast);

  requestAnimationFrame(() => {
    toast.classList.add("show");
  });

  const closeButton = toast.querySelector(".toast-close-btn");

  let removed = false;

  const removeToast = () => {
    if (removed) return;

    removed = true;

    toast.classList.remove("show");

    toast.style.height = `${toast.offsetHeight}px`;

    requestAnimationFrame(() => {
      toast.style.height = "0px";
      toast.style.margin = "0px";
      toast.style.paddingTop = "0px";
      toast.style.paddingBottom = "0px";
      toast.style.opacity = "0";
    });

    setTimeout(() => {
      toast.remove();

      activeToasts = activeToasts.filter(
        (item) => item !== toast
      );
    }, 300);
  };

  closeButton.addEventListener("click", removeToast);

  setTimeout(removeToast, duration);

  if (activeToasts.length > 5) {
    const oldestToast = activeToasts[0];

    if (oldestToast) {
      oldestToast.remove();
      activeToasts.shift();
    }
  }
}

function getToastTitle(type) {
  switch (type) {
    case "error":
      return "Error";

    case "warning":
      return "Warning";

    case "info":
      return "Information";

    default:
      return "Success";
  }
}