"use client";

import { useEffect, useRef, type ReactNode } from "react";
import { useToastStore, type Toast as ToastItem } from "@/lib/stores/toast-store";

const typeStyles: Record<ToastItem["type"], string> = {
  success: "bg-green-600 text-white",
  error: "bg-red-600 text-white",
  info: "bg-gold text-black",
};

const icons: Record<ToastItem["type"], ReactNode> = {
  success: (
    <svg className="h-5 w-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
    </svg>
  ),
  error: (
    <svg className="h-5 w-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
    </svg>
  ),
  info: (
    <svg className="h-5 w-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 100 20 10 10 0 000-20z" />
    </svg>
  ),
};

function ToastItem({ toast }: { toast: ToastItem }) {
  const removeToast = useToastStore((s) => s.removeToast);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Trigger enter animation
    requestAnimationFrame(() => {
      ref.current?.classList.remove("translate-y-full", "opacity-0", "md:translate-y-0", "md:-translate-x-full");
      ref.current?.classList.add("translate-y-0", "opacity-100", "md:translate-x-0");
    });
  }, []);

  return (
    <div
      ref={ref}
      role="alert"
      className={`flex items-center gap-2.5 rounded-lg px-4 py-3 text-sm font-medium shadow-lg transition-all duration-300 ease-out translate-y-full opacity-0 md:translate-y-0 md:-translate-x-full ${typeStyles[toast.type]}`}
    >
      {icons[toast.type]}
      <span className="flex-1">{toast.message}</span>
      <button
        onClick={() => removeToast(toast.id)}
        className="ml-1 shrink-0 rounded p-0.5 opacity-70 transition-opacity hover:opacity-100"
        aria-label="Dismiss"
      >
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>
  );
}

export default function ToastContainer() {
  const toasts = useToastStore((s) => s.toasts);

  if (toasts.length === 0) return null;

  return (
    <div
      aria-live="polite"
      className="fixed bottom-20 left-4 right-4 z-[75] flex flex-col items-center gap-2 md:bottom-auto md:left-auto md:right-6 md:top-6 md:items-end"
    >
      {toasts.map((toast) => (
        <ToastItem key={toast.id} toast={toast} />
      ))}
    </div>
  );
}
