// @design-system: overlays/Toast

import { useState, useCallback } from 'react';
import type { ToastTone } from './Toast';

export interface ToastActionData {
  label: string;
  altText: string;
  onClick: () => void;
}

/** Data for a single toast notification */
export interface ToastData {
  /** Unique key - auto-generated if not provided. */
  id: string;
  /** Toast title. */
  title: string;
  /** Toast description. */
  description?: string;
  /** Visual tone. @default 'neutral' */
  tone?: ToastTone;
  /** Auto-dismiss duration in ms. @default 5000 */
  duration?: number;
  /** Optional inline action such as Undo. */
  action?: ToastActionData;
}

/** Parameters for the `toast()` function */
export type ToastParams = Omit<ToastData, 'id'> & { id?: string };

/** Return type of `useToast` */
export interface UseToastReturn {
  /** Current toasts list. */
  toasts: ToastData[];
  /** Show a new toast. */
  toast: (params: ToastParams) => string;
  /** Dismiss a toast by id. */
  dismiss: (id: string) => void;
  /** Dismiss all toasts. */
  dismissAll: () => void;
}

let counter = 0;

/**
 * `useToast` hook - manages the toast queue.
 *
 * Expose the return value from a context provider and render
 * the toasts inside `<ToastViewport>`.
 *
 * @example
 * ```tsx
 * const { toast, toasts, dismiss } = useToast();
 *
 * toast({ title: t('success'), description: t('saved'), tone: 'success' });
 * ```
 */
export function useToast(): UseToastReturn {
  const [toasts, setToasts] = useState<ToastData[]>([]);

  const toast = useCallback((params: ToastParams): string => {
    const id = params.id ?? `toast-${++counter}`;
    const data: ToastData = { ...params, id };
    setToasts((prev) => [...prev, data].slice(-4));
    return id;
  }, []);

  const dismiss = useCallback((id: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  const dismissAll = useCallback(() => {
    setToasts([]);
  }, []);

  return { toasts, toast, dismiss, dismissAll };
}
