'use client';

import * as React from 'react';
import { Toast, ToastProvider as RadixToastProvider, ToastTitle, ToastViewport } from '@/components/ui/toast';

interface ToastState {
  id: number;
  title: string;
}

const ToastContext = React.createContext<{ showToast: (title: string) => void } | null>(null);

const PIN_TOAST_MESSAGE = 'Требуется подтверждение PIN-кода';

export function AppToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = React.useState<ToastState[]>([]);
  const recentMessagesRef = React.useRef<Map<string, number>>(new Map());

  const showToast = React.useCallback((title: string) => {
    if (title === PIN_TOAST_MESSAGE) return;

    const now = Date.now();
    const lastShown = recentMessagesRef.current.get(title);
    if (lastShown && now - lastShown < 4000) return;

    recentMessagesRef.current.set(title, now);
    const id = now;
    setToasts((current) => {
      if (current.some((toast) => toast.title === title)) return current;
      return [...current, { id, title }];
    });
    window.setTimeout(() => {
      setToasts((current) => current.filter((toast) => toast.id !== id));
    }, 4500);
  }, []);

  return (
    <ToastContext.Provider value={{ showToast }}>
      <RadixToastProvider swipeDirection="right">
        {children}
        {toasts.map((toast) => (
          <Toast key={toast.id} open>
            <ToastTitle>{toast.title}</ToastTitle>
          </Toast>
        ))}
        <ToastViewport />
      </RadixToastProvider>
    </ToastContext.Provider>
  );
}

export function useToast() {
  const context = React.useContext(ToastContext);
  if (!context) {
    throw new Error('useToast должен использоваться внутри AppToastProvider');
  }
  return context;
}
