"use client";

import {
  toast as hotToast,
  type ToastOptions,
  type ToastPosition,
} from "react-hot-toast";

import { resolveLocale } from "@/lib/locale";

type ToastVariant = "default" | "success" | "error" | "loading";

type ToastMessage = string;

function getCurrentLocale() {
  if (typeof window === "undefined") {
    return "de" as const;
  }

  const pathname = window.location.pathname;
  const maybeLocale = pathname.split("/")[1] || "de";

  return resolveLocale(maybeLocale);
}

function getToastPosition(isArabic: boolean): ToastPosition {
  return isArabic ? "top-right" : "top-left";
}

function getToastOptions(): ToastOptions {
  const locale = getCurrentLocale();
  const isArabic = locale === "ar";

  return {
    duration: 1800,
    position: getToastPosition(isArabic),
  };
}

function showToast(message: ToastMessage, variant: ToastVariant = "default") {
  const options = getToastOptions();

  if (variant === "success") {
    return hotToast.success(message, options);
  }

  if (variant === "error") {
    return hotToast.error(message, options);
  }

  if (variant === "loading") {
    return hotToast.loading(message, options);
  }

  return hotToast(message, options);
}

export const toast = Object.assign(
  (message: ToastMessage) => showToast(message, "default"),
  {
    success: (message: ToastMessage) => showToast(message, "success"),
    error: (message: ToastMessage) => showToast(message, "error"),
    loading: (message: ToastMessage) => showToast(message, "loading"),
    dismiss: hotToast.dismiss,
    remove: hotToast.remove,
  },
);
