import { useEffect, useState } from "react";
import { apiFetch } from "../lib/api";

export type Plan = "free" | "pro" | "legend";

type MeResponse = {
  id: string;
  email: string;
  username: string;
  plan: Plan;
};

let cachedPlan: Plan | null = null;

/**
 * Holt den User-Plan vom Backend (/api/auth/me).
 * Plan wird in DB gespeichert (nicht in user_metadata) — daher BFF-Call nötig.
 */
export function useUserPlan(): { plan: Plan; loading: boolean } {
  const [plan, setPlan] = useState<Plan>(cachedPlan ?? "free");
  const [loading, setLoading] = useState(cachedPlan === null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await apiFetch<MeResponse>("/api/auth/me");
        if (cancelled) return;
        cachedPlan = res.plan ?? "free";
        setPlan(cachedPlan);
      } catch (e) {
        console.warn("[useUserPlan] failed:", e);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  return { plan, loading };
}
