"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import {
  clearSession as clearStored,
  getInvestorId,
  getToken,
  setSession as setStored,
} from "@/lib/api";

interface SessionContextValue {
  investorId: string | null;
  hasToken: boolean;
  ready: boolean; // hydrated from localStorage
  apply: (investorId: string, token: string) => void;
  clear: () => void;
}

const SessionContext = createContext<SessionContextValue | null>(null);

export function SessionProvider({ children }: { children: React.ReactNode }) {
  const [investorId, setInvestorId] = useState<string | null>(null);
  const [hasToken, setHasToken] = useState(false);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    setInvestorId(getInvestorId());
    setHasToken(Boolean(getToken()));
    setReady(true);
  }, []);

  const apply = useCallback((id: string, token: string) => {
    setStored(id, token);
    setInvestorId(id);
    setHasToken(Boolean(token));
  }, []);

  const clear = useCallback(() => {
    clearStored();
    setInvestorId(null);
    setHasToken(false);
  }, []);

  const value = useMemo(
    () => ({ investorId, hasToken, ready, apply, clear }),
    [investorId, hasToken, ready, apply, clear],
  );

  return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}

export function useSession() {
  const ctx = useContext(SessionContext);
  if (!ctx) {
    throw new Error("useSession must be used within a SessionProvider");
  }
  return ctx;
}
