"use client";

import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from "react";

export type ToastKind = "success" | "error" | "info";
type ToastItem = { id: number; message: string; kind: ToastKind };

const ToastContext = createContext<{ show: (message: string, kind?: ToastKind) => void }>({ show: () => {} });

export function useToast() {
  return useContext(ToastContext);
}

export default function ToastProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<ToastItem[]>([]);
  const last = useRef<{ message: string; at: number } | null>(null);
  const idRef = useRef(0);

  const show = useCallback((message: string, kind: ToastKind = "info") => {
    const now = Date.now();
    if (last.current && last.current.message === message && now - last.current.at < 2000) return;
    last.current = { message, at: now };
    const id = ++idRef.current;
    setToasts((current) => [...current.slice(-3), { id, message, kind }]);
    setTimeout(() => setToasts((current) => current.filter((t) => t.id !== id)), 3200);
  }, []);

  const value = useMemo(() => ({ show }), [show]);

  return (
    <ToastContext.Provider value={value}>
      {children}
      <div
        aria-live="polite"
        style={{ position: "fixed", bottom: 18, left: "50%", transform: "translateX(-50%)", display: "grid", gap: 8, zIndex: 9999, width: "min(92vw, 360px)" }}
      >
        {toasts.map((toast) => (
          <div
            key={toast.id}
            role="status"
            style={{
              padding: "10px 14px",
              borderRadius: 10,
              fontSize: 13,
              fontWeight: 600,
              color: "#0b1114",
              background: toast.kind === "error" ? "#ffffff" : toast.kind === "success" ? "#e26161" : "#f44c4c",
              boxShadow: "0 10px 30px rgba(0,0,0,.35)",
              textAlign: "center",
            }}
          >
            {toast.message}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}
