const { useState, useEffect } = React;

/* CreditsBadge — persistent credit-balance pill shown in every signed-in shell
 * (CRM topbar + AppShell utility bar), mirroring the map's top-bar credits.
 * Shows the live balance and a quick "Top up" that routes to Billing's packs.
 *
 * Refreshes on mount, on window focus, and whenever any flow dispatches the
 * global `aiciq-credits` event after a spend/grant — call
 * window.refreshCreditsBadge() or window.dispatchEvent(new Event('aiciq-credits'))
 * from a reveal/enrich path to update it immediately. */
function CreditsBadge({ go }) {
  const ciq = window.ContactIQ ? window.ContactIQ.useContactIQ() : { isAuthed: false };
  const [bal, setBal] = useState(null);

  useEffect(() => {
    let alive = true;
    const load = () => {
      if (!window.ContactIQ || !ciq.isAuthed) { if (alive) setBal(null); return; }
      window.ContactIQ.getCreditBalance().then((n) => { if (alive) setBal(Number(n) || 0); }).catch(() => {});
    };
    load();
    const onFocus = () => load();
    window.addEventListener("focus", onFocus);
    window.addEventListener("aiciq-credits", onFocus);
    window.refreshCreditsBadge = load;
    return () => {
      alive = false;
      window.removeEventListener("focus", onFocus);
      window.removeEventListener("aiciq-credits", onFocus);
    };
  }, [ciq.isAuthed]);

  if (!ciq.isAuthed) return null;
  const low = bal != null && bal <= 5;

  return (
    <div className={"credits-badge" + (low ? " low" : "")}>
      <button className="credits-pill" title="Your credit balance — used for contact reveals & web enrichment" onClick={() => go && go("billing")}>
        <span className="credits-diamond">◆</span>
        <span className="credits-num">{bal == null ? "—" : bal.toLocaleString()}</span>
        <span className="credits-lbl">credits</span>
      </button>
      <button className="credits-topup" title="Buy more credits" onClick={() => go && go("billing")}>+ Top up</button>
    </div>
  );
}

window.CreditsBadge = CreditsBadge;
