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

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(() => {
    try { return JSON.parse(localStorage.getItem('teamflow_user')); } catch { return null; }
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = localStorage.getItem('teamflow_token');
    if (token && !user) {
      api.auth.me().then(u => { setUser(u); localStorage.setItem('teamflow_user', JSON.stringify(u)); setLoading(false); })
        .catch(() => { localStorage.removeItem('teamflow_token'); setLoading(false); });
    } else {
      setLoading(false);
    }
  }, []);

  const login = async (email, password) => {
    const data = await api.auth.login({ email, password });
    localStorage.setItem('teamflow_token', data.token);
    localStorage.setItem('teamflow_user', JSON.stringify(data.user));
    setUser(data.user);
    return data;
  };

  const logout = () => {
    localStorage.removeItem('teamflow_token');
    localStorage.removeItem('teamflow_user');
    setUser(null);
  };

  const refresh = async () => {
    try {
      const u = await api.auth.me();
      localStorage.setItem('teamflow_user', JSON.stringify(u));
      setUser(u);
    } catch {}
  };

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

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