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 [profiles, setProfiles] = useState([]);
  const [active, setActive] = useState(null);
  const [loading, setLoading] = useState(false);

  const refresh = useCallback(async () => {
    if (!user) { setProfiles([]); setActive(null); return; }
    setLoading(true);
    try {
      const { data } = await api.get("/profiles");
      setProfiles(data);
      const stored = localStorage.getItem(`kino_profile_${user.id}`);
      const found = data.find((p) => p.id === stored);
      setActive(found || null);
    } finally {
      setLoading(false);
    }
  }, [user]);

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

  const switchTo = (p) => {
    if (!user) return;
    localStorage.setItem(`kino_profile_${user.id}`, p.id);
    setActive(p);
  };

  const clearActive = () => {
    if (!user) return;
    localStorage.removeItem(`kino_profile_${user.id}`);
    setActive(null);
  };

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

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