// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// account.tsx : contexte de compte partagé — profil connecté + favoris ♥
//   Un seul fetch au montage ; les favoris vivent au HUB Groupe KA (magasin
//   central « Mon univers Ka ») : toggle optimiste, poussé au serveur qui
//   relaie au hub. Non connecté -> clic ♥ redirige vers la connexion KA ID.
// -----------------------------------------------------------------------------
import {
  ReactNode, createContext, useCallback, useContext, useEffect, useState,
} from "react";
import {
  Listing, User, favItemFromListing, fetchFavorites, fetchMe, toggleFavorite,
} from "./api";

interface AccountState {
  user: User | null;
  enabled: boolean;
  loaded: boolean;
  favs: Set<string>;
  toggleFav: (l: Listing) => void;
  refresh: () => void;
}

const Ctx = createContext<AccountState>({
  user: null, enabled: false, loaded: false, favs: new Set(),
  toggleFav: () => {}, refresh: () => {},
});

export const useAccount = () => useContext(Ctx);

/** Redirige vers la connexion KA ID, avec retour sur la page courante. */
export function kaLogin() {
  const next = window.location.pathname + window.location.search;
  window.location.href = `/api/auth/ka/login?next=${encodeURIComponent(next)}`;
}

export function AccountProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [enabled, setEnabled] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [favs, setFavs] = useState<Set<string>>(new Set());

  const refresh = useCallback(() => {
    fetchMe()
      .then((r) => {
        setUser(r.user);
        setEnabled(r.enabled !== false);
        setLoaded(true);
        if (r.user && r.user.ka_id) {
          fetchFavorites()
            .then((f) => setFavs(new Set(f.ids)))
            .catch(() => setFavs(new Set()));
        } else {
          setFavs(new Set());
        }
      })
      .catch(() => { setUser(null); setLoaded(true); });
  }, []);

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

  const toggleFav = useCallback((l: Listing) => {
    if (!user || !user.ka_id) { kaLogin(); return; }
    setFavs((prev) => {
      const next = new Set(prev);
      const on = !next.has(l.uid);
      if (on) next.add(l.uid); else next.delete(l.uid);
      toggleFavorite(on, favItemFromListing(l)).catch((e) => {
        if (String(e).includes("401")) kaLogin();
      });
      return next;
    });
  }, [user]);

  return (
    <Ctx.Provider value={{ user, enabled, loaded, favs, toggleFav, refresh }}>
      {children}
    </Ctx.Provider>
  );
}
