"use client";

import { useState, useCallback, useRef } from "react";
import { ToastContext, type ToastPosition } from "@/hooks/useToast";
import Toast from "./Toast";

export default function ToastProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [message, setMessage] = useState("");
  const [position, setPosition] = useState<ToastPosition>("top");
  const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const show = useCallback((msg: string, pos: ToastPosition = "top") => {
    clearTimeout(timerRef.current);
    setMessage(msg);
    setPosition(pos);
    timerRef.current = setTimeout(() => setMessage(""), 2200);
  }, []);

  return (
    <ToastContext.Provider value={{ show }}>
      {children}
      <Toast message={message} position={position} />
    </ToastContext.Provider>
  );
}
