
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface User {
  id: string;
  email: string;
  name: string;
}

interface AuthContextType {
  user: User | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    // Check for existing session on mount
    const savedUser = localStorage.getItem('auth_user');
    if (savedUser) {
      setUser(JSON.parse(savedUser));
    }
    // Optional: Token könnte hier geprüft werden
  }, []);

  const login = async (email: string, password: string) => {
    setIsLoading(true);
    try {
      console.log('Login url:',`${import.meta.env.VITE_WEBHOOK_URL || ''}/auth/login`); 
      // JWT-Login: API-Call
      const response = await fetch(`${import.meta.env.VITE_WEBHOOK_URL || ''}/auth_login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include', // <-- wichtig für Cookies!
        body: JSON.stringify({ email, password }),
      });
      if (!response.ok) {
        throw new Error('Login fehlgeschlagen');
      }
      const data = await response.json();
      // Erwartet: { token: '...', user: { ... } }
      const token = data.token;
      const userData: User = data.user || {
        id: '1',
        email,
        name: email.split('@')[0],
      };
      if (!token) throw new Error('Kein Token erhalten');
      // Speichere Token & User
      localStorage.setItem('auth_token', token);
      setUser(userData);
      localStorage.setItem('auth_user', JSON.stringify(userData));
    } catch (error: any) {
      throw new Error(error.message || 'Login failed');
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('auth_user');
    localStorage.removeItem('auth_token');
  };

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