import { create } from "zustand";

export type ToastType = "success" | "error" | "info" | "warning";

interface Toast {
  id: string;
  message: string;
  type: ToastType;
  sticky?: boolean;
}

interface ToastStore {
  toasts: Toast[];
  addToast: (message: string, type?: ToastType, opts?: { sticky?: boolean }) => void;
  removeToast: (id: string) => void;
}

export const useToast = create<ToastStore>((set) => ({
  toasts: [],
  addToast: (message, type = "info", opts = {}) => {
    // ponytail: crypto.randomUUID for stable unique ids (the old module
    // counter was shared across imports and brittle in tests).
    const id = crypto.randomUUID();
    set((state) => {
      // ponytail: cap visible at 3 — older ones get pushed off so a noisy
      // session doesn't stack a wall of toasts over the content.
      const next = [...state.toasts, { id, message, type, sticky: opts.sticky }];
      return { toasts: next.slice(-3) };
    });
    if (!opts.sticky) {
      setTimeout(() => {
        set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }));
      }, 4000);
    }
  },
  removeToast: (id) => {
    set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }));
  },
}));

const typeStyles: Record<ToastType, { bg: string; border: string; icon: string }> = {
  success: {
    bg: "bg-[var(--color-success)]/10",
    border: "border-[var(--color-success)]/40",
    icon: "✓",
  },
  error: {
    bg: "bg-[var(--color-danger)]/10",
    border: "border-[var(--color-danger)]/40",
    icon: "✕",
  },
  info: {
    bg: "bg-[var(--color-gold-bright)]/10",
    border: "border-[var(--color-gold-bright)]/40",
    icon: "ℹ",
  },
  warning: {
    bg: "bg-[var(--color-gold-muted)]/10",
    border: "border-[var(--color-gold-muted)]/40",
    icon: "⚠",
  },
};

export function ToastContainer() {
  const { toasts, removeToast } = useToast();

  return (
    <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 pointer-events-none">
      {toasts.map((toast) => {
        const style = typeStyles[toast.type];
        return (
          <div
            key={toast.id}
            className={`pointer-events-auto glass-card px-4 py-3 flex items-center gap-2 text-sm ${style.bg} border ${style.border} animate-[slideIn_0.2s_ease-out]`}
          >
            <span className="text-base">{style.icon}</span>
            <span className="text-[var(--color-text-primary)]">{toast.message}</span>
            <button
              onClick={() => removeToast(toast.id)}
              className="ml-2 text-[var(--color-text-dim)] hover:text-[var(--color-text-primary)] cursor-pointer"
            >
              ×
            </button>
          </div>
        );
      })}
    </div>
  );
}