import { Alpine } from "./alpine";
import { showToast } from "./toast";

function showErrorToast(message: string): void {
  showToast(message, "error", 8000);

  // Add retry button to the toast
  setTimeout(() => {
    const toastContainer = document.getElementById("toast-container");
    if (toastContainer && toastContainer.lastElementChild) {
      const toast = toastContainer.lastElementChild as HTMLElement;
      const retryBtn = document.createElement("button");
      retryBtn.className =
        "ml-4 px-3 py-1 bg-white/20 hover:bg-white/30 rounded text-sm font-medium transition-colors";
      retryBtn.textContent = "Retry";
      retryBtn.onclick = function () {
        window.location.reload();
      };

      // Insert before the close button
      const closeBtn = toast.querySelector(".toast-close");
      if (closeBtn && closeBtn.parentElement) {
        closeBtn.parentElement.insertBefore(retryBtn, closeBtn);
      } else {
        toast.appendChild(retryBtn);
      }
    }
  }, 100);
}

export { showErrorToast };

Alpine.data("toastError", () => ({
  showErrorToast,
}));
