import React, { createContext, useContext, useEffect, useState } from 'react'; interface User { id: string; email: string; display_name: string; role: 'organizer' | 'vendor'; } interface AuthContextValue { user: User | null; loading: boolean; login: (email: string, password: string) => Promise; register: (email: string, password: string, displayName: string, role?: string) => Promise; logout: () => Promise; } const AuthContext = createContext(null); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); // Restore session on mount useEffect(() => { fetch('/api/auth/me', { credentials: 'include' }) .then(res => res.ok ? res.json() : null) .then(data => { if (data?.user) setUser(data.user); }) .catch(() => {}) .finally(() => setLoading(false)); }, []); async function login(email: string, password: string) { const res = await fetch('/api/auth/login', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'התחברות נכשלה'); setUser(data.user); } async function register(email: string, password: string, displayName: string, role = 'organizer') { const res = await fetch('/api/auth/register', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password, display_name: displayName, role }), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'הרשמה נכשלה'); setUser(data.user); } async function logout() { await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }); setUser(null); } return ( {children} ); } export function useAuth() { const ctx = useContext(AuthContext); if (!ctx) throw new Error('useAuth must be used within AuthProvider'); return ctx; }