// ============================================================
// Toast — 轻量通知组件
// 职责：3 秒自动消失的通知提示
// ============================================================

import { useCallback, useEffect, useState } from "react";
import { registerToastSetter, type ToastItem } from "../../lib/toast";

export type { ToastItem };

/** Toast 容器组件，放在 App 根部 */
export function ToastContainer() {
  const [toasts, setToasts] = useState<ToastItem[]>([]);

  // 注册全局 setter
  useEffect(() => {
    registerToastSetter(setToasts);
    return () => registerToastSetter(null);
  }, []);

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

  return (
    <div className="toast-container">
      {toasts.map((t) => (
        <ToastItemView key={t.id} item={t} onDismiss={dismiss} />
      ))}
    </div>
  );
}

function ToastItemView({
  item,
  onDismiss,
}: {
  item: ToastItem;
  onDismiss: (id: number) => void;
}) {
  useEffect(() => {
    const timer = setTimeout(() => onDismiss(item.id), 3000);
    return () => clearTimeout(timer);
  }, [item.id, onDismiss]);

  return (
    <div className={`toast toast--${item.type}`} onClick={() => onDismiss(item.id)}>
      {item.message}
    </div>
  );
}
