import { useEffect } from 'react';
import { usePage } from '@inertiajs/react';
import toast, { Toaster } from 'react-hot-toast';

export default function FlashMessages() {
    const { props } = usePage();

    // Session-based flash messages
    const success = props.flash?.success;
    const error = props.flash?.error;

    // JSON-based messages (from apiResponse)
    const apiSuccess = props.success && props.message ? props.message : null;
    const apiError = !props.success && props.message ? props.message : null;

    const validationErrors = props.errors || {};

    useEffect(() => {
        if (success) toast.success(success);
        if (error) toast.error(error);

        if (apiSuccess) toast.success(apiSuccess);
        if (apiError) toast.error(apiError);

        Object.values(validationErrors).forEach((messages) => {
            toast.error(messages);
        });
    }, [success, error, apiSuccess, apiError, validationErrors]);

    return <Toaster position="top-center" reverseOrder={false} />;
}
