// ============================================================
// ONBOARDING — parcours aha post-signup
// ============================================================
// 3 écrans séquentiels :
//   1. WWelcome           → choix démo (loading pendant le seed)
//   2. WWelcomeDebrief    → debrief IA (Haiku ~10-15s) + affichage rapport
//   3. WWelcomeComplete   → CTA double (continue web / download desktop)
//
// Routing géré dans index.html : un user loggé avec
// subscriptions.initial_import_done=false est forcé sur "welcome".
// À la fin du flow, on appelle mark_initial_import_done() pour
// libérer le user vers les routes standard.

// ─── Helper digest pour le welcome debrief ─────────────────────
// Le digest est ce qu'on envoie à Claude. On lui donne assez de matière
// pour pouvoir produire 3 insights chiffrés sans dépasser MAX_DIGEST_CHARS.
function buildWelcomeDigest(trades) {
  const total = trades.length;
  if (!total) return { total: 0 };

  const wins = trades.filter(t => t.result === "WIN").length;
  const losses = total - wins;

  // Par asset
  const byAsset = {};
  for (const t of trades) {
    const a = t.asset;
    if (!byAsset[a]) byAsset[a] = { n: 0, wins: 0, pnl: 0 };
    byAsset[a].n += 1;
    if (t.result === "WIN") byAsset[a].wins += 1;
    byAsset[a].pnl += Number(t.pnl) || 0;
  }

  // Par session
  const bySession = {};
  for (const t of trades) {
    const s = t.session || "OFF";
    if (!bySession[s]) bySession[s] = { n: 0, wins: 0, pnl: 0 };
    bySession[s].n += 1;
    if (t.result === "WIN") bySession[s].wins += 1;
    bySession[s].pnl += Number(t.pnl) || 0;
  }

  // Par tranche horaire UTC (utile pour détecter le pattern soir)
  const byHourBucket = { "0-8": { n:0, wins:0, pnl:0 }, "8-15": { n:0, wins:0, pnl:0 }, "15-21": { n:0, wins:0, pnl:0 }, "21-24": { n:0, wins:0, pnl:0 } };
  for (const t of trades) {
    const h = new Date(t.date).getUTCHours();
    const b = h < 8 ? "0-8" : (h < 15 ? "8-15" : (h < 21 ? "15-21" : "21-24"));
    byHourBucket[b].n += 1;
    if (t.result === "WIN") byHourBucket[b].wins += 1;
    byHourBucket[b].pnl += Number(t.pnl) || 0;
  }

  // R-multiples moyens win / loss
  const avgRWin = trades.filter(t => t.result === "WIN").reduce((s, t) => s + (Number(t.r_multiple) || 0), 0) / Math.max(wins, 1);
  const avgRLoss = trades.filter(t => t.result === "LOSS").reduce((s, t) => s + (Number(t.r_multiple) || 0), 0) / Math.max(losses, 1);

  const totalPnl = trades.reduce((s, t) => s + (Number(t.pnl) || 0), 0);

  return {
    period_days: 90,
    total_trades: total,
    win_rate: +(wins / total).toFixed(3),
    total_pnl: +totalPnl.toFixed(2),
    avg_r_win: +avgRWin.toFixed(2),
    avg_r_loss: +avgRLoss.toFixed(2),
    by_asset: byAsset,
    by_session: bySession,
    by_hour_bucket_utc: byHourBucket,
  };
}

// Hash trivial pour digest_hash (l'Edge Function exige >=8 chars).
function hashStr(s) {
  let h = 5381;
  for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;
  return ("d" + Math.abs(h).toString(36)).slice(0, 16);
}

// ─── 1. Welcome screen ─────────────────────────────────────────
const WWelcome = ({ go, user }) => {
  const W = window.W;
  const [status, setStatus] = React.useState("idle"); // idle | loading | error
  const [message, setMessage] = React.useState("");

  const displayName = (user && (user.user_metadata?.display_name || user.email?.split("@")[0])) || "trader";

  const launchDemo = async () => {
    if (status === "loading") return;
    setStatus("loading");
    setMessage("On charge ta démo (60 trades fictifs cohérents)…");
    const r = await window.nomerusDemoSeeder.seed();
    if (!r.ok) {
      setStatus("error");
      setMessage(r.error || "Erreur lors du chargement de la démo.");
      return;
    }
    // On enchaîne directement sur le debrief. Le RPC consume_welcome_debrief
    // sera appelé là-bas.
    go("welcome-debrief");
  };

  return (
    <div style={{
      minHeight: "100vh", background: W.bg, color: W.text,
      fontFamily: W.sans, display: "flex", alignItems: "center", justifyContent: "center",
      padding: "40px 20px",
    }}>
      <div style={{ maxWidth: 560, width: "100%" }}>
        {/* Pill */}
        <div style={{
          fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2,
          marginBottom: 16,
        }}>
          ÉTAPE 1 / 3 · BIENVENUE
        </div>

        <h1 style={{
          fontFamily: W.sans, fontSize: 38, fontWeight: 700, lineHeight: 1.08,
          letterSpacing: -1, margin: "0 0 16px",
        }}>
          Salut <span style={{ color: W.indigo }}>{displayName}</span>,<br/>
          on te montre Nomerus <span style={{ color: W.green }}>en action</span>.
        </h1>

        <p style={{
          fontFamily: W.sans, fontSize: 16, color: W.textDim, lineHeight: 1.55,
          margin: "0 0 28px",
        }}>
          En 30 secondes, on charge un dataset démo de 60 trades fictifs cohérents
          (EURUSD, BTCUSDT, XAUUSD, SPX500). Le Coach IA analyse ces trades et
          te montre 3 patterns concrets qu'il a trouvés.<br/><br/>
          <span style={{ color: W.textMute, fontSize: 13 }}>
            Tu pourras ensuite importer tes vrais trades (export CSV broker ou
            saisie manuelle) depuis le Journal. D'abord, regardons ce que
            Nomerus voit sur les données démo.
          </span>
        </p>

        <button
          onClick={launchDemo}
          disabled={status === "loading"}
          className="w-btn-primary"
          style={{
            background: W.indigo, color: "#fff", border: "none",
            padding: "14px 28px", borderRadius: 6,
            fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
            cursor: status === "loading" ? "wait" : "pointer",
            opacity: status === "loading" ? 0.65 : 1,
          }}>
          {status === "loading" ? "CHARGEMENT…" : "LANCER LA DÉMO →"}
        </button>

        {message && (
          <div style={{
            marginTop: 18,
            fontFamily: W.sans, fontSize: 14,
            color: status === "error" ? "rgb(255, 120, 120)" : W.textDim,
          }}>
            {message}
          </div>
        )}
      </div>
    </div>
  );
};

window.WWelcome = WWelcome;

// ─── 2. Welcome debrief screen ─────────────────────────────────
const WWelcomeDebrief = ({ go, user }) => {
  const W = window.W;
  const [status, setStatus] = React.useState("loading"); // loading | success | error | already
  const [report, setReport] = React.useState(null);
  const [errorMsg, setErrorMsg] = React.useState("");

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const sb = window.nomerusSb();
        if (!sb) throw new Error("Supabase indisponible.");

        // 1) Consume le one-shot
        const { data: consumeData, error: consumeErr } = await sb.rpc("consume_welcome_debrief");
        if (consumeErr) {
          if ((consumeErr.message || "").includes("subscription_not_found")) {
            throw new Error("Compte mal initialisé. Contacte le support.");
          }
          throw consumeErr;
        }
        const consumed = consumeData === true;

        // 2) Si déjà consommé, on essaie de retrouver le rapport précédent
        if (!consumed) {
          const { data: prior } = await sb
            .from("ai_analyses")
            .select("response_json, created_at")
            .eq("surface", "welcome")
            .order("created_at", { ascending: false })
            .limit(1)
            .maybeSingle();
          if (cancelled) return;
          if (prior?.response_json) {
            setReport(prior.response_json);
            setStatus("already");
          } else {
            setStatus("already");
            setReport(null);
          }
          return;
        }

        // 3) Charger les trades du user (les 60 démos qu'on vient de seeder).
        // On filtre sur is_demo=true pour que la première analyse reste centrée
        // sur le dataset démo même si le user a déjà ajouté des trades réels.
        const { data: trades, error: tradesErr } = await sb
          .from("trades")
          .select("date, asset, direction, pnl, r_multiple, result, session, strategy")
          .eq("is_demo", true)
          .order("date", { ascending: true });
        if (tradesErr) throw tradesErr;
        if (!trades || trades.length === 0) {
          throw new Error("Aucun trade trouvé. La démo a peut-être échoué — refresh la page.");
        }

        // 4) Construire digest + hash
        const digest = buildWelcomeDigest(trades);
        const digest_hash = hashStr(JSON.stringify(digest));

        // 5) Call Edge Function ai-coach
        const { data: { session } } = await sb.auth.getSession();
        if (!session?.access_token) throw new Error("Session expirée. Reconnecte-toi.");
        const fnUrl = "https://ctrbtvqogntpkrkwajvn.supabase.co/functions/v1/ai-coach";
        const resp = await fetch(fnUrl, {
          method: "POST",
          headers: {
            "authorization": `Bearer ${session.access_token}`,
            "content-type": "application/json",
          },
          body: JSON.stringify({ surface: "welcome", digest, digest_hash }),
        });
        if (!resp.ok) {
          const errBody = await resp.json().catch(() => ({}));
          throw new Error(`ai-coach a échoué (${resp.status}): ${errBody.error || "unknown"}`);
        }
        const data = await resp.json();
        if (cancelled) return;
        setReport(data);
        setStatus("success");
      } catch (e) {
        if (cancelled) return;
        console.error("[welcome-debrief]", e);
        setErrorMsg(e.message || "Erreur inconnue.");
        setStatus("error");
      }
    })();
    return () => { cancelled = true; };
  }, []);

  if (status === "loading") {
    return (
      <div style={{
        minHeight: "100vh", background: W.bg, color: W.text, fontFamily: W.sans,
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <div style={{ textAlign: "center", maxWidth: 480 }}>
          <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 20 }}>
            ÉTAPE 2 / 3 · ANALYSE EN COURS
          </div>
          <div style={{
            fontSize: 56, lineHeight: 1, marginBottom: 24,
            animation: "pulse 1.4s ease-in-out infinite alternate",
          }}>
            <span style={{ color: W.indigo }}>◌</span>
          </div>
          <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>
            Le Coach IA lit tes 60 trades…
          </div>
          <div style={{ color: W.textMute, fontSize: 13 }}>
            ~10 secondes. Il cherche 3 patterns concrets sur ton historique.
          </div>
          <style>{`@keyframes pulse { from { opacity: 0.3 } to { opacity: 1 } }`}</style>
        </div>
      </div>
    );
  }

  if (status === "error") {
    return (
      <div style={{
        minHeight: "100vh", background: W.bg, color: W.text, fontFamily: W.sans,
        display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 20px",
      }}>
        <div style={{ maxWidth: 520 }}>
          <div style={{ fontFamily: W.mono, fontSize: 10, color: "rgb(255,120,120)", letterSpacing: 2, marginBottom: 12 }}>
            ANALYSE ÉCHOUÉE
          </div>
          <h2 style={{ fontSize: 24, margin: "0 0 14px" }}>Le Coach IA n'a pas pu finir.</h2>
          <p style={{ color: W.textDim, marginBottom: 24 }}>{errorMsg}</p>
          <button onClick={() => go("welcome-complete")} style={{
            background: "transparent", color: W.text, border: `1px solid ${W.borderStrong}`,
            padding: "10px 20px", borderRadius: 6, cursor: "pointer",
            fontFamily: W.mono, fontSize: 12, letterSpacing: 2,
          }}>CONTINUER QUAND MÊME →</button>
        </div>
      </div>
    );
  }

  // success | already
  return (
    <div style={{
      minHeight: "100vh", background: W.bg, color: W.text, fontFamily: W.sans, padding: "40px 20px",
    }}>
      <div style={{ maxWidth: 720, margin: "0 auto" }}>
        <div style={{ fontFamily: W.mono, fontSize: 10, color: W.green, letterSpacing: 2, marginBottom: 12 }}>
          ÉTAPE 2 / 3 · DEBRIEF DU COACH IA
          {status === "already" && <span style={{ color: W.textMute, marginLeft: 8 }}>(déjà reçu)</span>}
        </div>

        {report?.narrative && (
          <h2 style={{
            fontFamily: W.sans, fontSize: 26, lineHeight: 1.25, fontWeight: 600,
            margin: "0 0 28px", color: W.text,
          }}>
            {report.narrative}
          </h2>
        )}

        {Array.isArray(report?.insights) && report.insights.length > 0 ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {report.insights.map((ins, i) => (
              <div key={i} style={{
                background: "rgba(124,158,255,0.04)",
                border: `1px solid ${W.border}`, borderRadius: 8, padding: "18px 20px",
              }}>
                <div style={{
                  fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 8,
                }}>
                  {(ins.category || "INSIGHT").toUpperCase()}
                  {ins.severity && <span style={{ color: W.textMute, marginLeft: 8 }}>· {ins.severity}</span>}
                </div>
                <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>{ins.title}</div>
                <div style={{ fontSize: 14, color: W.textDim, marginBottom: 8 }}>{ins.observation}</div>
                {ins.recommendation && (
                  <div style={{ fontSize: 13, color: W.green, fontStyle: "italic" }}>→ {ins.recommendation}</div>
                )}
              </div>
            ))}
          </div>
        ) : (
          <p style={{ color: W.textMute }}>Aucun insight à afficher.</p>
        )}

        <div style={{ marginTop: 36, display: "flex", justifyContent: "flex-end" }}>
          <button onClick={() => go("welcome-complete")} className="w-btn-primary" style={{
            background: W.indigo, color: "#fff", border: "none",
            padding: "12px 24px", borderRadius: 6, cursor: "pointer",
            fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
          }}>CONTINUER →</button>
        </div>
      </div>
    </div>
  );
};

window.WWelcomeDebrief = WWelcomeDebrief;

// ─── 3. Welcome complete (outro CTA) ───────────────────────────
const WWelcomeComplete = ({ go, user }) => {
  const W = window.W;
  const [marking, setMarking] = React.useState(false);
  const [error, setError] = React.useState("");
  const markPromiseRef = React.useRef(null);

  // Marque l'onboarding comme terminé dès l'affichage de cet écran.
  // On garde la promesse pour pouvoir l'attendre dans continueWeb : sans
  // ça, un click très rapide pouvait reload avant que le UPDATE ait
  // atteint Postgres, et le gate bootstrap renvoyait l'user sur /welcome.
  React.useEffect(() => {
    markPromiseRef.current = (async () => {
      try {
        const sb = window.nomerusSb();
        if (!sb) return;
        await sb.rpc("mark_initial_import_done");
      } catch (e) {
        console.warn("[welcome-complete] mark_initial_import_done:", e);
      }
    })();
  }, []);

  const continueWeb = async () => {
    setMarking(true);
    try {
      // Garantir que le flag est commit côté serveur AVANT le reload.
      try { await markPromiseRef.current; } catch (_) {}
      // Appel défensif au cas où le mount-time a perdu la course réseau.
      const sb = window.nomerusSb();
      if (sb) {
        try { await sb.rpc("mark_initial_import_done"); } catch (_) {}
      }
      // Reload pour que index.html refasse le check initial_import_done
      // et route directement sur /home.
      window.location.href = window.location.pathname + "?route=home";
    } catch (e) {
      setError(e.message || "");
      setMarking(false);
    }
  };

  const downloadDesktop = () => {
    // V1 : pas encore de release publique → on ouvre le repo Github.
    // Quand on aura une release, on pointera vers le .exe direct.
    window.open("https://github.com/Nomerus-app/Nomerus/releases", "_blank", "noopener");
  };

  return (
    <div style={{
      minHeight: "100vh", background: W.bg, color: W.text, fontFamily: W.sans,
      display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 20px",
    }}>
      <div style={{ maxWidth: 560 }}>
        <div style={{ fontFamily: W.mono, fontSize: 10, color: W.green, letterSpacing: 2, marginBottom: 14 }}>
          ÉTAPE 3 / 3 · TU AS GOÛTÉ À NOMERUS
        </div>

        <h1 style={{
          fontFamily: W.sans, fontSize: 36, fontWeight: 700, lineHeight: 1.1, letterSpacing: -1,
          margin: "0 0 16px",
        }}>
          Et maintenant ?
        </h1>

        <p style={{ color: W.textDim, fontSize: 16, lineHeight: 1.55, marginBottom: 32 }}>
          Tu viens de voir ce que le Coach IA fait sur 60 trades démo.
          Imagine sur tes vrais trades. Tu peux continuer sur le web, ou
          télécharger l'app desktop pour le mode offline et les notifs natives.
        </p>

        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <button
            onClick={continueWeb}
            disabled={marking}
            className="w-btn-primary"
            style={{
              background: W.indigo, color: "#fff", border: "none",
              padding: "14px 28px", borderRadius: 6, cursor: marking ? "wait" : "pointer",
              fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
              opacity: marking ? 0.65 : 1,
            }}>
            CONTINUER SUR LE WEB →
          </button>

          <button
            onClick={downloadDesktop}
            style={{
              background: "transparent", color: W.text, border: `1px solid ${W.borderStrong}`,
              padding: "13px 26px", borderRadius: 6, cursor: "pointer",
              fontFamily: W.mono, fontSize: 12, fontWeight: 600, letterSpacing: 2,
            }}>
            TÉLÉCHARGER L'APP DESKTOP ↓
          </button>
        </div>

        <p style={{ marginTop: 24, fontSize: 12, color: W.textMute }}>
          Tu peux vider la démo et importer tes vrais trades à tout moment
          depuis <strong>Settings</strong>. L'import CSV broker arrive bientôt.
        </p>

        {error && (
          <div style={{ marginTop: 16, color: "rgb(255,120,120)", fontSize: 13 }}>{error}</div>
        )}
      </div>
    </div>
  );
};

window.WWelcomeComplete = WWelcomeComplete;

// ─── Stubs pour T5/T6 (à remplacer) ────────────────────────────
// Présents pour que le tryRender de index.html puisse mounter
// l'App tant que T5/T6 ne sont pas implémentés. Affichent juste
// un placeholder + un bouton de continuation.
const _OnboardingStub = ({ label, nextRoute, go, ctaLabel }) => {
  const W = window.W;
  return (
    <div style={{
      minHeight: "100vh", background: W.bg, color: W.text,
      fontFamily: W.sans, display: "flex", alignItems: "center", justifyContent: "center",
      padding: "40px 20px",
    }}>
      <div style={{ maxWidth: 560, width: "100%", textAlign: "center" }}>
        <div style={{
          fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2,
          marginBottom: 16,
        }}>
          {label}
        </div>
        <p style={{ fontFamily: W.sans, fontSize: 16, color: W.textDim, margin: "0 0 24px" }}>
          Écran bientôt disponible.
        </p>
        {nextRoute && (
          <button
            onClick={() => go(nextRoute)}
            style={{
              background: W.indigo, color: "#fff", border: "none",
              padding: "12px 24px", borderRadius: 6,
              fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
              cursor: "pointer",
            }}>
            {ctaLabel || "CONTINUER →"}
          </button>
        )}
      </div>
    </div>
  );
};

if (!window.WWelcomeDebrief) {
  window.WWelcomeDebrief = ({ go }) =>
    <_OnboardingStub label="ÉTAPE 2 / 3 · DEBRIEF IA" nextRoute="welcome-complete" go={go}/>;
}
if (!window.WWelcomeComplete) {
  window.WWelcomeComplete = ({ go }) =>
    <_OnboardingStub label="ÉTAPE 3 / 3 · BIENVENUE À BORD" nextRoute="home" go={go} ctaLabel="VOIR LE DASHBOARD →"/>;
}
