import React, { createContext, useState, useEffect } from 'react';
import { pb } from '../lib/pocketbase';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(pb.authStore.model);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        // Subscribe to auth state changes
        const unsubscribe = pb.authStore.onChange((token, model) => {
            setUser(model);
        });

        return () => {
            // Unsubscribe (authStore.onChange returns a compiled unsubscribe function)
            unsubscribe();
        };
    }, []);

    const login = async (email, password) => {
        setLoading(true);
        try {
            await pb.collection('users').authWithPassword(email, password);
        } catch (error) {
            console.error("Login failed:", error);
            throw error;
        } finally {
            setLoading(false);
        }
    };

    const logout = () => {
        pb.authStore.clear();
    };

    return (
        <AuthContext.Provider value={{ user, login, logout, loading }}>
            {children}
        </AuthContext.Provider>
    );
};
