import { createContext, useContext, useState, useEffect } from 'react';
import api from '../services/api';

const AuthContext = createContext(null);
const USER_STORAGE_KEY = 'user';

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = localStorage.getItem('token');
    const cachedUser = localStorage.getItem(USER_STORAGE_KEY);

    if (token && cachedUser) {
      try { setUser(JSON.parse(cachedUser)); } catch { localStorage.removeItem(USER_STORAGE_KEY); }
    }

    if (token) refreshUser();
    else setLoading(false);
  }, []);

  useEffect(() => {
    const syncUser = (event) => {
      if (event.key !== USER_STORAGE_KEY) return;

      if (!event.newValue) {
        setUser(null);
        return;
      }

      try { setUser(JSON.parse(event.newValue)); } catch {}
    };

    window.addEventListener('storage', syncUser);
    return () => window.removeEventListener('storage', syncUser);
  }, []);

  const persistUser = (nextUser) => {
    setUser(nextUser);

    if (nextUser) {
      localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(nextUser));
      window.dispatchEvent(new CustomEvent('auth-user-change', { detail: { user: nextUser } }));
    } else {
      localStorage.removeItem(USER_STORAGE_KEY);
      window.dispatchEvent(new CustomEvent('auth-user-change', { detail: { user: null } }));
    }
  };

  const refreshUser = async () => {
    try {
      const { data } = await api.get('/user');
      persistUser(data.data);
      return data.data;
    } catch {
      localStorage.removeItem('token');
      persistUser(null);
    }
    finally { setLoading(false); }
  };

  const login = async (identifier, password) => {
    const { data } = await api.post('/login', { identifier, password });
    localStorage.setItem('token', data.data.token);
    persistUser(data.data.user);
    return data.data;
  };

  const logout = async () => {
    try { await api.post('/logout'); } catch {}
    localStorage.removeItem('token');
    persistUser(null);
  };

  const updateProfile = async (profileData) => {
    const { data } = await api.put('/user/profile', profileData);
    persistUser(data.data);
    return data;
  };

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

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