import React, { createContext, useContext, useState, useEffect } from "react";
import { jwtDecode } from "jwt-decode";
import axios from "axios"; // ← ajoute cet import

const AuthContext = createContext();
export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
  const [token, setToken] = useState(localStorage.getItem("token"));
  const [user, setUser] = useState(null);

  useEffect(() => {
    if (token) {
      try {
        const decoded = jwtDecode(token);
        setUser(decoded);
        // ✅ Recharge le token axios si la page est rafraîchie
        axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
      } catch (error) {
        console.error("Erreur lors du décodage du token:", error);
        setUser(null);
      }
    } else {
      setUser(null);
      // ✅ Supprime le header si pas de token
      delete axios.defaults.headers.common["Authorization"];
    }
  }, [token]);

  const login = (newToken) => {
    localStorage.setItem("token", newToken);
    // ✅ Configure axios dès le login
    axios.defaults.headers.common["Authorization"] = `Bearer ${newToken}`;
    setToken(newToken);
  };

  const logout = () => {
    localStorage.removeItem("token");
    // ✅ Supprime le header à la déconnexion
    delete axios.defaults.headers.common["Authorization"];
    setToken(null);
    setUser(null);
  };

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