import { useState, useEffect, useCallback } from "react";

type BIPEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
};

let globalEvt: BIPEvent | null = null;
const listeners = new Set<() => void>();

function notify() {
  listeners.forEach((fn) => fn());
}

export function setInstallPromptEvent(evt: BIPEvent | null) {
  globalEvt = evt;
  notify();
}

export function getInstallPromptEvent(): BIPEvent | null {
  return globalEvt;
}

export function useInstallPrompt() {
  const [evt, setEvt] = useState<BIPEvent | null>(globalEvt);

  useEffect(() => {
    const cb = () => setEvt(globalEvt);
    listeners.add(cb);
    return () => { listeners.delete(cb); };
  }, []);

  const prompt = useCallback(async () => {
    if (!globalEvt) return { outcome: "dismissed" as const };
    await globalEvt.prompt();
    const result = await globalEvt.userChoice;
    if (result.outcome === "accepted") {
      globalEvt = null;
      notify();
    }
    return result;
  }, []);

  return { evt, prompt };
}
