import { createContext, useContext, useEffect, useState, useCallback } from "react";
import api from "./api";
import { useAuth } from "./auth";

const ProfileCtx = createContext(null);

export const ProfileProvider = ({ children }) => {
  const { user } = useAuth();
  const [active, setActive] = useState(null);
  const [loading, setLoading] = useState(false);

  const refresh = useCallback(async () => {
    if (!user) { setActive(null); return; }
    setLoading(true);
    try {
      const { data } = await api.get("/profiles");
      setActive(data[0] || null);
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => { refresh(); }, [refresh]);

  return (
    <ProfileCtx.Provider value={{ active, loading, refresh }}>
      {children}
    </ProfileCtx.Provider>
  );
};

export const useProfile = () => useContext(ProfileCtx);
