const { useState, useEffect } = React;

/* PaywallGate — mounted once at the app root. Reads account_status and:
 *  - HARD BLOCKS (full-screen overlay) when the trial has ended or the plan was
 *    canceled and no payment is on file → drives to Billing to add payment.
 *  - SOFT NUDGES (dismissible top banner) when the user is out of credits (trial
 *    still active or paid) → drives to Billing's credit packs.
 * Internal + paid plans never gate. Never blocks the Billing/public screens.
 * Refreshes on mount, window focus, and the global `aiciq-credits` event. */
function PaywallGate({ go, current }) {
  const ciq = window.ContactIQ ? window.ContactIQ.useContactIQ() : { isAuthed: false };
  const [st, setSt] = useState(null);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    if (!window.ContactIQ || !ciq.isAuthed) { setSt(null); return; }
    let alive = true;
    const load = () => window.ContactIQ.getAccountStatus().then(s => { if (alive) setSt(s); }).catch(() => {});
    load();
    window.addEventListener("aiciq-credits", load);
    window.addEventListener("focus", load);
    return () => { alive = false; window.removeEventListener("aiciq-credits", load); window.removeEventListener("focus", load); };
  }, [ciq.isAuthed]);

  const PUBLIC = ["landing", "login", "signup"];
  if (!st || !st.authed) return null;
  if (PUBLIC.includes(current) || String(current).startsWith("waitlist")) return null;

  const signOut = async () => {
    try { await window.ContactIQ.clearExtensionJwt(); } catch (_) {}
    try { await window.ContactIQ.signOut(); } catch (_) {}
    go("landing");
  };

  // ── Hard gate: trial ended / canceled, no payment on file ──────────────
  if (st.needs_payment && current !== "billing") {
    const canceled = st.reason === "canceled";
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(15,23,42,0.62)",
                    display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
                    fontFamily: "var(--font-sans, -apple-system, sans-serif)" }}>
        <div style={{ width: 440, maxWidth: "100%", background: "var(--bg, #fff)", borderRadius: 16,
                      border: "1px solid var(--border-1, #e5e9ef)", boxShadow: "0 24px 70px rgba(0,0,0,0.35)",
                      padding: "30px 32px", textAlign: "center" }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, margin: "0 auto 16px",
                        background: "var(--accent-bg, #eff4ff)", color: "var(--accent, #2563eb)",
                        display: "flex", alignItems: "center", justifyContent: "center", fontSize: 22 }}>◆</div>
          <h2 style={{ margin: "0 0 10px", font: "700 21px var(--font-sans)", color: "var(--fg-1, #0f172a)" }}>
            {canceled ? "Your subscription was canceled" : "Your free trial has ended"}
          </h2>
          <p style={{ margin: "0 0 22px", font: "500 14px var(--font-sans)", color: "var(--fg-2, #475569)", lineHeight: 1.6 }}>
            {canceled
              ? "Reactivate your plan to keep access to AI ContactIQ — the map, CRM, 17.7M building-anchored organizations, and the extension."
              : "Add a payment method to keep access to AI ContactIQ — the map, CRM, 17.7M building-anchored organizations, and the extension. It's $5/month, cancel anytime."}
          </p>
          <button onClick={() => go("billing")}
            style={{ width: "100%", height: 44, border: "none", borderRadius: 10, background: "var(--accent, #2563eb)",
                     color: "#fff", font: "600 14px var(--font-sans)", cursor: "pointer" }}>
            {canceled ? "Reactivate — go to billing" : "Add payment method"}
          </button>
          <button onClick={signOut}
            style={{ marginTop: 10, width: "100%", height: 40, border: "none", background: "none",
                     color: "var(--fg-3, #94a3b8)", font: "500 13px var(--font-sans)", cursor: "pointer" }}>
            Sign out
          </button>
        </div>
      </div>
    );
  }

  // ── Soft nudge: out of credits (trial active or paid) ──────────────────
  if (st.credits_out && !dismissed && current !== "billing") {
    return (
      <div style={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 150,
                    background: "#7c2d12", color: "#fff", display: "flex", alignItems: "center",
                    gap: 12, padding: "9px 16px", font: "500 13px var(--font-sans, sans-serif)" }}>
        <span style={{ fontWeight: 700 }}>You're out of credits.</span>
        <span style={{ opacity: 0.9 }}>Contact reveals and web enrichment need credits.</span>
        <span style={{ flex: 1 }}/>
        <button onClick={() => go("billing")}
          style={{ height: 28, padding: "0 12px", border: "none", borderRadius: 7, background: "#fff",
                   color: "#7c2d12", font: "600 12px var(--font-sans)", cursor: "pointer" }}>Buy credits</button>
        <button onClick={() => setDismissed(true)} aria-label="Dismiss"
          style={{ background: "none", border: "none", color: "#fff", fontSize: 18, lineHeight: 1, cursor: "pointer", opacity: 0.8 }}>×</button>
      </div>
    );
  }

  return null;
}

window.PaywallGate = PaywallGate;
