import axios from 'axios';
import { toast } from 'sonner';
import { usePage } from '@inertiajs/react';

export default function useThemeUpdater() {
    const { auth } = usePage().props;
    const user = auth.user;

    const updateTheme = async (newTheme) => {
        if (!user) {
            console.log("Guest theme changed. Not saving to backend.");
            return;
        }

        const url = user.role === 'admin' 
            ? '/api/admin/theme' 
            : '/api/user/theme';

        try {
            await axios.patch(url, { theme: newTheme });
        } catch (error) {
            console.error("Failed to save theme preference:", error);
            toast.error("Could not save your theme preference.");
        }
    };

    return { updateTheme };
}