// ============================================================
// /success — Stripe redirect après paiement réussi
// ============================================================
// Poll la table public.subscriptions toutes les 2 secondes (max 5 tentatives)
// jusqu'à voir plan="pro". Si le webhook tarde, on laisse quand même passer
// en montrant un message rassurant.
// ============================================================
const WSuccess = ({ go }) => {
  const W = window.W;
  const [status, setStatus] = React.useState("polling"); // polling | active | timeout | error
  const [attempts, setAttempts] = React.useState(0);

  React.useEffect(() => {
    let cancelled = false;
    const MAX = 5;
    const tick = async (n) => {
      if (cancelled) return;
      try {
        const sb = window.nomerusSb();
        if (!sb) {
          if (!cancelled) setStatus("error");
          return;
        }
        const session = await window.nomerusAuth.getSession();
        if (!session) {
          if (!cancelled) setStatus("error");
          return;
        }
        const { data, error } = await sb
          .from("subscriptions")
          .select("plan, status, founder_coupon_used")
          .maybeSingle();
        if (!cancelled) setAttempts(n + 1);
        if (error) {
          if (n + 1 >= MAX) { if (!cancelled) setStatus("timeout"); return; }
        } else if (data && data.plan === "pro") {
          if (!cancelled) setStatus("active");
          return;
        }
        if (n + 1 >= MAX) {
          if (!cancelled) setStatus("timeout");
          return;
        }
        if (!cancelled) setTimeout(() => tick(n + 1), 2000);
      } catch (e) {
        if (n + 1 >= MAX) { if (!cancelled) setStatus("timeout"); return; }
        if (!cancelled) setTimeout(() => tick(n + 1), 2000);
      }
    };
    tick(0);
    return () => { cancelled = true; };
  }, []);

  return (
    <div style={{ minHeight: "70vh", display: "flex", alignItems: "center", justifyContent: "center", padding: "60px 24px" }}>
      <div style={{
        maxWidth: 520, width: "100%",
        background: W.panel, border: `1px solid ${W.border}`, borderRadius: 6,
        padding: "40px 32px", textAlign: "center",
      }}>
        <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 16 }}>
          // PAIEMENT
        </div>

        {status === "polling" && (
          <>
            <h1 style={{ fontFamily: W.sans, fontSize: 28, fontWeight: 700, letterSpacing: -0.8, margin: "0 0 14px", color: W.text }}>
              Activation de ton accès Pro…
            </h1>
            <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, lineHeight: 1.6, margin: "0 0 24px" }}>
              Stripe a confirmé ton paiement. On finalise ton compte (quelques secondes)…
            </p>
            <div style={{ fontFamily: W.mono, fontSize: 11, color: W.textMute, letterSpacing: 1 }}>
              Tentative {attempts}/5
            </div>
          </>
        )}

        {status === "active" && (
          <>
            <div style={{ fontSize: 40, marginBottom: 10, color: W.green }}>✓</div>
            <h1 style={{ fontFamily: W.sans, fontSize: 28, fontWeight: 700, letterSpacing: -0.8, margin: "0 0 14px", color: W.text }}>
              Bienvenue dans Nomerus Pro.
            </h1>
            <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, lineHeight: 1.6, margin: "0 0 28px" }}>
              Tout est activé. Comptes broker illimités, Coach IA, analyse graphique débloqués.
            </p>
            <button onClick={() => go("home")} style={{
              background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
              padding: "14px 22px", borderRadius: 4,
              fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
            }}>OUVRIR LE TERMINAL →</button>
          </>
        )}

        {status === "timeout" && (
          <>
            <h1 style={{ fontFamily: W.sans, fontSize: 24, fontWeight: 700, letterSpacing: -0.6, margin: "0 0 14px", color: W.text }}>
              Paiement reçu. Activation en cours.
            </h1>
            <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, lineHeight: 1.6, margin: "0 0 28px" }}>
              Stripe a confirmé ton paiement, mais l'activation prend un peu plus de temps que prévu. Tu peux ouvrir le terminal — si ton accès Pro n'est pas encore visible, rafraîchis la page d'ici 30 secondes.
            </p>
            <button onClick={() => go("home")} style={{
              background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
              padding: "14px 22px", borderRadius: 4,
              fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
            }}>OUVRIR LE TERMINAL →</button>
          </>
        )}

        {status === "error" && (
          <>
            <h1 style={{ fontFamily: W.sans, fontSize: 24, fontWeight: 700, letterSpacing: -0.6, margin: "0 0 14px", color: W.text }}>
              Connecte-toi pour finaliser
            </h1>
            <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, lineHeight: 1.6, margin: "0 0 28px" }}>
              Ton paiement est bien reçu. Connecte-toi avec le même email pour activer ton accès Pro.
            </p>
            <button onClick={() => go("login")} style={{
              background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
              padding: "14px 22px", borderRadius: 4,
              fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
            }}>SE CONNECTER →</button>
          </>
        )}
      </div>
    </div>
  );
};

window.WSuccess = WSuccess;
