"use client";
import { useState, useEffect } from "react";
import { CheckCircle, XCircle, Info, X } from "lucide-react";

type Toast = { id: string; message: string; type: "success" | "error" | "info" };

let addToast: (msg: string, type?: Toast["type"]) => void = () => {};

export function toast(message: string, type: Toast["type"] = "info") {
  addToast(message, type);
}

export function Toaster() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  useEffect(() => {
    addToast = (message, type = "info") => {
      const id = Date.now().toString();
      setToasts((prev) => [...prev, { id, message, type }]);
      setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 4000);
    };
  }, []);

  const icons = { success: CheckCircle, error: XCircle, info: Info };
  const colors = {
    success: "border-emerald-500/50 text-emerald-400",
    error: "border-red-500/50 text-red-400",
    info: "border-[#e05a68]/50 text-[#e05a68]",
  };

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col gap-3 pointer-events-none">
      {toasts.map((t) => {
        const Icon = icons[t.type];
        return (
          <div
            key={t.id}
            className={`glass flex items-center gap-3 px-4 py-3 rounded-xl border pointer-events-auto animate-fade-in ${colors[t.type]}`}
            style={{ minWidth: 280, maxWidth: 380 }}
          >
            <Icon size={18} />
            <span className="text-sm font-medium" style={{ color: "var(--text-primary)" }}>
              {t.message}
            </span>
            <button
              className="ml-auto opacity-50 hover:opacity-100"
              onClick={() => setToasts((p) => p.filter((x) => x.id !== t.id))}
            >
              <X size={14} />
            </button>
          </div>
        );
      })}
    </div>
  );
}
