// Klyvio — Report v5
// Niveau 1 : p3 dans AgentsCard, disclaimer ROI 3 scénarios, benchmark sourcé
// Niveau 2 : explication score (2 dimensions qui tirent vers le bas) sous ScoreDial
// Niveau 3 : description agents enrichie avec verbatim p3
// Niveau 4 (v5) : commercialSignals intégrés
//   - ReportHeader : intro adaptée si budget alloué (o8) ou projet en cours (o7)
//   - AgentsCard   : encart v8 (idée concrète) en complément de p3
//   - BookingCTA   : label CTA affiné selon urgence (r7) et profil

function Report({ company, answers, onBookCall, onAdmin, onRestart }) {
  const data = useMemo(() => {
    const result = window.KLYVIO_COMPUTE.compute(answers);
    return { ...result, roadmap: result.road };
  }, [answers, company]);

  const [tab, setTab] = useState("overview");
  const [simHoursPct, setSimHoursPct] = useState(100);
  const [simStaffPct, setSimStaffPct] = useState(100);

  const tabs = [
    { id: "overview",    label: "Vue d'ensemble",   icon: "target" },
    { id: "painpoints",  label: "Problèmes",         icon: "alert" },
    { id: "automations", label: "Automatisations",   icon: "workflow" },
    { id: "roi",         label: "Simulateur ROI",    icon: "euro" },
    { id: "roadmap",     label: "Roadmap",           icon: "compass" },
    { id: "benchmark",   label: "Benchmark",         icon: "barChart" },
  ];

  const levelLabel =
    data.global < 30 ? "Découverte" :
    data.global < 50 ? "Exploration" :
    data.global < 70 ? "Développement" :
    data.global < 85 ? "Maturité" : "Leader";

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
      <ReportHeader company={company} data={data} levelLabel={levelLabel} onBookCall={onBookCall} onRestart={onRestart} answers={answers} />

      <div style={{
        position: "sticky", top: 60, zIndex: 20,
        background: "rgba(8,15,26,0.92)", backdropFilter: "blur(12px)",
        borderBottom: "1px solid var(--border)", padding: "0 28px",
      }}>
        <div style={{ maxWidth: 1280, margin: "0 auto", display: "flex", gap: 2 }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: "14px 16px", fontSize: 13, fontWeight: 500, border: "none",
              background: "transparent",
              color: tab === t.id ? "var(--white)" : "var(--gray)",
              borderBottom: tab === t.id ? "2px solid var(--accent)" : "2px solid transparent",
              cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 7,
              marginBottom: -1, transition: "all .15s",
            }}>
              <Icon name={t.icon} size={13} />{t.label}
            </button>
          ))}
        </div>
      </div>

      <div style={{ maxWidth: 1280, width: "100%", margin: "0 auto", padding: "40px 28px 80px" }} className="fade-in" key={tab}>
        {tab === "overview"    && <ReportOverview data={data} levelLabel={levelLabel} company={company} answers={answers} onNav={setTab} />}
        {tab === "painpoints"  && <PainPoints data={data} />}
        {tab === "automations" && <Automations data={data} />}
        {tab === "roi"         && <ROISimulator data={data} answers={answers}
          simHoursPct={simHoursPct} setSimHoursPct={setSimHoursPct}
          simStaffPct={simStaffPct} setSimStaffPct={setSimStaffPct} />}
        {tab === "roadmap"     && <Roadmap data={data} />}
        {tab === "benchmark"   && <Benchmark data={data} company={company} />}
      </div>

      <BookingCTA onBookCall={onBookCall} data={data} answers={answers} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────────────────────
const C3_LABELS = [
  "trouver et fidéliser des clients",
  "gérer la croissance sans recruter",
  "réduire les coûts et améliorer les marges",
  "fidéliser et manager les équipes",
  "se différencier de la concurrence",
  "gagner du temps pour se concentrer sur la stratégie",
  "remplacer des départs sans alourdir la masse salariale",
];

const P1_LABELS = [
  "la ressaisie d'informations",
  "la recherche de documents",
  "la rédaction d'emails répétitifs",
  "la production de rapports manuels",
  "les réponses aux mêmes questions clients",
  "les relances commerciales",
  "la préparation de devis",
  "la planification et coordination",
  "le classement et l'archivage",
  "la gestion des congés et plannings",
  "la saisie et correction dans plusieurs outils",
  "la rédaction de comptes-rendus de réunion",
];

function getC3Label(answers) {
  const c3 = answers?.c3;
  if (Array.isArray(c3) && c3.length > 0) {
    const labels = c3.map(i => C3_LABELS[i]).filter(Boolean);
    if (labels.length === 0) return null;
    if (labels.length === 1) return labels[0];
    return `${labels[0]} et ${labels[1]}`;
  }
  if (typeof c3 === "number" && C3_LABELS[c3]) return C3_LABELS[c3];
  return null;
}

function getTop2Irritants(answers) {
  const p1 = Array.isArray(answers?.p1) ? answers.p1 : [];
  return p1.slice(0, 2).map(i => P1_LABELS[i]).filter(Boolean);
}

function getP3(answers) {
  const p3 = answers?.p3;
  return (typeof p3 === "string" && p3.trim().length > 3) ? p3.trim() : null;
}

function getV8(answers) {
  const v8 = answers?.v8;
  return (typeof v8 === "string" && v8.trim().length > 10) ? v8.trim() : null;
}

// ─────────────────────────────────────────────────────────────
// NIVEAU 2 — Explication du score global
// ─────────────────────────────────────────────────────────────
function getScoreExplanation(scores, global) {
  const sorted = [...scores].sort((a, b) => a.value - b.value);
  const bottom2 = sorted.slice(0, 2);

  const DIM_IMPACT = {
    readiness:  "votre capacité à déployer rapidement",
    org:        "votre capacité à faire adopter les changements",
    data:       "la qualité et la circulation de vos informations",
    processes:  "le temps perdu sur des tâches répétitives",
    usage:      "l'adoption de l'IA par vos équipes",
    context:    "la clarté de votre vision IA",
    vision:     "vos objectifs et votre ambition sur le sujet",
  };

  const parts = bottom2.map(d => DIM_IMPACT[d.id] || d.fullLabel);
  return `Score influencé principalement par ${parts.join(" et ")}.`;
}

// ─────────────────────────────────────────────────────────────
// INTRO CONTEXTUELLE — v5
// Adapte le texte d'intro selon les signaux commerciaux
// Priorité : budget alloué > projet en cours > profil dirigeant > fallback
// ─────────────────────────────────────────────────────────────
function buildIntroText(profile, roiDetail, commercial) {
  const p2 = roiDetail?.hoursLostWk || 10;

  // Budget validé + projet en cours → on peut aller vite
  if (commercial?.hasBudget && commercial?.hasActiveProject) {
    return "Vous avez déjà un budget et un projet en cours — c'est le meilleur point de départ. Ce rapport vous montre précisément comment accélérer et sur quoi concentrer l'effort en premier.";
  }

  // Budget alloué mais pas encore de projet structuré
  if (commercial?.hasBudget && !commercial?.hasActiveProject) {
    return "Votre budget est alloué — il reste à cibler les bons cas d'usage. Ce rapport vous donne les priorités claires pour démarrer avec un impact immédiat.";
  }

  // Projet en cours mais pas encore de budget formalisé
  if (commercial?.hasActiveProject && !commercial?.hasBudget) {
    return "Vous avez déjà engagé une réflexion — c'est une longueur d'avance. Ce rapport structure ce qui manque encore pour transformer cette exploration en résultats concrets.";
  }

  // Urgence identifiée sans budget ni projet
  if (commercial?.isUrgent) {
    return `Une échéance approche — chaque semaine compte. Vos équipes passent ${p2} h/sem sur des tâches automatisables. Ce rapport montre ce qu'on peut déployer en moins de 30 jours.`;
  }

  // Fallback — profil dirigeant
  if (profile?.emphasis) return profile.emphasis;

  return `Vos équipes passent en moyenne ${p2} h/sem sur des tâches répétitives. Ce rapport montre où récupérer ce temps et ce que ça représente concrètement pour votre activité.`;
}

// ─────────────────────────────────────────────────────────────
// REPORT HEADER
// ─────────────────────────────────────────────────────────────
function ReportHeader({ company, data, levelLabel, onBookCall, onRestart, answers }) {
  const profile    = data.profile;
  const commercial = data.commercial || {};
  const scoreExplanation = getScoreExplanation(data.scores, data.global);
  const introText  = buildIntroText(profile, data.roiDetail, commercial);

  // Badge contextuel dans le header selon signal fort
  function getContextBadge() {
    if (commercial.hasBudget && commercial.hasActiveProject) {
      return { label: "Projet & budget prêts", color: "#10B981", bg: "rgba(16,185,129,0.1)", border: "rgba(16,185,129,0.3)" };
    }
    if (commercial.hasBudget) {
      return { label: "Budget alloué", color: "#10B981", bg: "rgba(16,185,129,0.1)", border: "rgba(16,185,129,0.3)" };
    }
    if (commercial.hasActiveProject) {
      return { label: "Projet en cours", color: "#F59E0B", bg: "rgba(245,158,11,0.1)", border: "rgba(245,158,11,0.3)" };
    }
    if (commercial.isUrgent) {
      return { label: "Urgence identifiée", color: "#EF4444", bg: "rgba(239,68,68,0.1)", border: "rgba(239,68,68,0.3)" };
    }
    return null;
  }

  const contextBadge = getContextBadge();

  return (
    <div style={{ background: "var(--ink-950)", color: "white", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: -100, right: -80, width: 500, height: 500, borderRadius: "50%", background: "radial-gradient(circle, rgba(0,174,239,0.2), transparent 70%)" }} />
      <div style={{ position: "absolute", bottom: -120, left: 100, width: 400, height: 400, borderRadius: "50%", background: "radial-gradient(circle, rgba(0,174,239,0.1), transparent 70%)" }} />

      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "56px 28px 48px", position: "relative" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 36 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
              <span className="chip chip-success" style={{ background: "rgba(16,185,129,0.15)", color: "#10B981", border: "1px solid rgba(16,185,129,0.3)" }}>
                <span className="dot" /> Rapport prêt
              </span>
              <span style={{ fontSize: 12, color: "rgba(255,255,255,0.55)" }}>
                Généré le {new Date().toLocaleDateString("fr-FR", { day: "numeric", month: "long", year: "numeric" })}
              </span>
              {/* Badge profil dirigeant */}
              {profile && (
                <span style={{ fontSize: 12, color: "rgba(0,174,239,0.8)", background: "rgba(0,174,239,0.1)", border: "1px solid rgba(0,174,239,0.2)", borderRadius: 6, padding: "2px 8px" }}>
                  {profile.label}
                </span>
              )}
              {/* Badge contextuel — signal commercial fort */}
              {contextBadge && (
                <span style={{
                  fontSize: 12, fontWeight: 600,
                  color: contextBadge.color,
                  background: contextBadge.bg,
                  border: `1px solid ${contextBadge.border}`,
                  borderRadius: 6, padding: "2px 8px",
                }}>
                  {contextBadge.label}
                </span>
              )}
            </div>

            <div className="eyebrow" style={{ color: "rgba(255,255,255,0.55)", marginBottom: 10 }}>
              Audit de maturité IA · {company?.name || "Votre entreprise"} · {data.sectorLabel}
            </div>

            <h1 className="display" style={{ fontSize: 56, margin: 0, lineHeight: 1.04, color: "white", maxWidth: 760 }}>
              Votre niveau : <em style={{ fontStyle: "italic", color: "var(--accent-300)" }}>{levelLabel}.</em>
            </h1>

            <p style={{ fontSize: 17, color: "rgba(255,255,255,0.65)", maxWidth: 620, margin: "16px 0 0", lineHeight: 1.5 }}>
              {introText}
            </p>
          </div>

          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn btn-ghost" style={{ color: "white", borderColor: "rgba(255,255,255,0.2)", background: "rgba(255,255,255,0.05)" }}>
              <Icon name="download" size={13} /> PDF
            </button>
            <button className="btn btn-ghost" style={{ color: "white", borderColor: "rgba(255,255,255,0.2)", background: "rgba(255,255,255,0.05)" }}>
              <Icon name="share" size={13} /> Partager
            </button>
            <button className="btn btn-ghost" style={{ color: "white", borderColor: "rgba(255,255,255,0.2)", background: "rgba(255,255,255,0.05)" }} onClick={onRestart}>
              <Icon name="refresh" size={13} /> Refaire
            </button>
          </div>
        </div>

        {/* Métriques clés */}
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr 1fr 1fr", gap: 16 }}>
          <div style={{ padding: "28px 28px 24px", borderRadius: 18, background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 24, marginBottom: 16 }}>
              <ScoreDial value={data.global} size={120} stroke={10} label="Score global" sub={levelLabel} />
              <div>
                <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Position</div>
                <div className="display" style={{ fontSize: 26, color: "white", margin: 0 }}>Top {100 - data.bench.percentile}%</div>
                <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)", marginTop: 4 }}>vs {data.sectorLabel}</div>
              </div>
            </div>
            {/* Niveau 2 — explication du score */}
            <div style={{
              padding: "10px 12px",
              background: "rgba(255,255,255,0.04)",
              border: "1px solid rgba(255,255,255,0.08)",
              borderRadius: 8,
              fontSize: 12,
              color: "rgba(255,255,255,0.5)",
              lineHeight: 1.5,
            }}>
              {scoreExplanation}
            </div>
          </div>

          <MetricTile eyebrow="Gain annuel estimé"  value={formatEur(data.roi.totalGain)}    sub={`sur ${data.autos.length} automatisations`} color="var(--accent-300)" />
          <MetricTile eyebrow="Heures économisées"  value={formatHours(data.roi.totalHours)} sub="par an"                                      color="#10B981" />
          <div style={{ padding: "22px 24px", borderRadius: 18, background: "rgba(8,15,26,0.95)", border: "1px solid rgba(255,255,255,0.1)" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 18 }}>Retour sur invest.</div>
            <div className="display" style={{ fontSize: 38, color: "#F59E0B", margin: 0 }}>{data.roi.payback} mois</div>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)", marginTop: 4, marginBottom: 10 }}>pour rentabiliser</div>
            <div style={{ borderTop: "1px dashed rgba(255,255,255,0.1)", paddingTop: 10 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "rgba(255,255,255,0.85)", marginBottom: 3 }}>
                {data.roiDetail?.offerName || data.offer?.name || `${data.tier === "starter" ? "1" : data.tier === "duo" ? "2" : "3"} agents autonomes`}
              </div>
              <div style={{ fontSize: 12, color: "#F59E0B", fontWeight: 700 }}>
                {formatEur(data.roi.totalInvest)} la 1ère année
              </div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.4)" }}>
                puis {formatEur(data.roiDetail?.subscription || (data.roi.totalInvest - (data.roiDetail?.setup || 0)))}/an
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function MetricTile({ eyebrow, value, sub, color = "var(--accent-300)" }) {
  return (
    <div style={{ padding: "22px 24px", borderRadius: 18, background: "rgba(8,15,26,0.95)", border: "1px solid rgba(255,255,255,0.1)" }}>
      <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 18 }}>{eyebrow}</div>
      <div className="display" style={{ fontSize: 38, color, margin: 0 }}>{value}</div>
      <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)", marginTop: 4 }}>{sub}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// REPORT OVERVIEW
// ─────────────────────────────────────────────────────────────
function ReportOverview({ data, levelLabel, company, answers, onNav }) {
  const top3      = data.autos.slice(0, 3);
  const highPains = data.pains.filter(p => p.severity === "high").slice(0, 3);
  const defi      = getC3Label(answers);
  const irritants = getTop2Irritants(answers);
  const usageScore = (data.scores.find(s => s.id === "usage") || { value: 50 }).value;
  const p2        = data.roiDetail?.hoursLostWk || 10;

  const syntheseIntro = [
    company?.name ? `${company.name} se situe` : "Votre entreprise se situe",
    `au niveau ${levelLabel.toLowerCase()}.`,
    defi ? (Array.isArray(answers?.c3) && answers.c3.length > 1 ? `Vos deux défis prioritaires — ${defi} —` : `Votre défi principal — ${defi} —`) : "Vos priorités",
    "sont directement adressables par l'IA.",
  ].join(" ");

  const syntheseBody = [
    `Vos équipes consacrent en moyenne ${p2} h/sem à des tâches répétitives,`,
    irritants.length > 0 ? `notamment ${irritants.join(" et ")}.` : "notamment des emails, devis et reporting.",
    "Sur 12 mois, le potentiel de gain net est de",
    `${formatEur(data.roi.net12m)} pour un investissement estimé à ${formatEur(data.roi.totalInvest)}.`,
  ].join(" ");

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 28 }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>

        {/* Synthèse */}
        <div className="card" style={{ padding: "32px 36px" }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Synthèse</div>
          <h2 className="display" style={{ fontSize: 30, margin: "0 0 20px" }}>Ce que votre audit révèle.</h2>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--text-soft)", margin: "0 0 12px" }}>{syntheseIntro}</p>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--text-soft)", margin: 0 }}>
            {usageScore > 55
              ? "Vos équipes sont plutôt ouvertes à ces outils — c'est un atout."
              : "Vos équipes ont besoin d'un cadre clair pour adopter ces outils efficacement."
            }{" "}{syntheseBody}
          </p>
        </div>

        {/* Top 3 */}
        <div className="card" style={{ padding: "28px 32px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 6 }}>Top 3 automatisations</div>
              <h3 className="display" style={{ fontSize: 24, margin: 0 }}>Par où commencer</h3>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => onNav("automations")}>
              Voir les {data.autos.length} <Icon name="arrowRight" size={12} />
            </button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {top3.map((a, i) => (
              <div key={a.id} style={{
                display: "flex", alignItems: "center", gap: 16, padding: "16px 18px",
                background: i === 0 ? "var(--accent-50)" : "var(--surface-2)",
                border: "1px solid", borderColor: i === 0 ? "var(--accent-100)" : "var(--border)",
                borderRadius: 14,
              }}>
                <div className="mono" style={{
                  width: 30, height: 30, borderRadius: 8,
                  background: i === 0 ? "var(--accent-500)" : "var(--ink-100)",
                  color: i === 0 ? "white" : "var(--text-soft)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, fontWeight: 600,
                }}>{i + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 2 }}>{a.label}</div>
                  <div style={{ fontSize: 12, color: "var(--text-soft)" }}>
                    {a.applicableStaff} collaborateurs · {a.weeklyHoursSaved} h/sem économisées
                  </div>
                </div>
                <span className="chip">{a.type}</span>
                <div style={{ textAlign: "right", minWidth: 80 }}>
                  <div className="display" style={{ fontSize: 20 }}>{formatEur(a.annualGain)}</div>
                  <div style={{ fontSize: 11, color: "var(--text-mute)" }}>/ an</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Points bloquants */}
        <div className="card" style={{ padding: "28px 32px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 6 }}>À traiter en priorité</div>
              <h3 className="display" style={{ fontSize: 24, margin: 0 }}>Vos principaux points bloquants</h3>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => onNav("painpoints")}>
              Tout voir <Icon name="arrowRight" size={12} />
            </button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
            {highPains.map((p, i) => (
              <div key={i} style={{ padding: "18px", background: "var(--danger-50)", border: "1px solid #FBC7C7", borderRadius: 12 }}>
                <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--danger-600)", marginBottom: 10, fontWeight: 600 }}>
                  <Icon name="alert" size={11} /> Critique
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 6, lineHeight: 1.35 }}>{p.title}</div>
                <div style={{ fontSize: 12, color: "var(--text-soft)", lineHeight: 1.5 }}>{p.impact}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Encart agents */}
        {data.agents && data.agents.length > 0 && (
          <AgentsCard data={data} answers={answers} onNav={onNav} />
        )}
      </div>

      {/* Colonne droite — Radar */}
      <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
        <div className="card" style={{ padding: "28px 32px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Profil détaillé</div>
          <h3 className="display" style={{ fontSize: 24, margin: "0 0 20px" }}>Vos 7 dimensions</h3>
          <div style={{ display: "flex", justifyContent: "center", padding: "20px 0" }}>
            <RadarChart data={data.scores} size={340} />
          </div>
        </div>

        <div className="card" style={{ padding: "24px 28px" }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Dimensions — détail</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[...data.scores].sort((a, b) => b.value - a.value).map(s => (
              <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ fontSize: 13, minWidth: 110, color: "var(--text)" }}>{s.label}</div>
                <div style={{ flex: 1, height: 6, background: "var(--ink-100)", borderRadius: 999 }}>
                  <div style={{ width: `${s.value}%`, height: "100%", background: s.color, borderRadius: 999, transition: "width .6s" }} />
                </div>
                <div className="mono" style={{ fontSize: 12, minWidth: 36, textAlign: "right", color: "var(--text)" }}>
                  {Math.round(s.value)}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ENCART AGENTS — v5 : p3 + v8 (idée concrète)
// ─────────────────────────────────────────────────────────────
function AgentsCard({ data, answers, onNav }) {
  const { agents, offer, profile } = data;
  const ctaText    = profile?.cta || "Voir ce qu'on ferait ensemble";
  const agentColors = ["var(--accent-500)", "#8B5CF6", "#10B981"];
  const p3 = getP3(answers);
  const v8 = getV8(answers);

  // Description du premier agent — enrichie avec p3 ou v8
  function agentDesc(agent, i) {
    if (i === 0 && p3) {
      return `Il prend en charge "${p3}" — et plus généralement, il ${agent.focus}.`;
    }
    if (i === 0 && v8) {
      return `Il peut démarrer par "${v8}" — et plus généralement, il ${agent.focus}.`;
    }
    return `Il ${agent.focus}.`;
  }

  // Encart à afficher : p3 prioritaire sur v8
  const highlightText  = p3 || v8;
  const highlightLabel = p3 ? "Votre priorité n°1" : "Votre idée de départ";
  const highlightSub   = p3
    ? "C'est exactement ce type de tâche que prend en charge le premier agent déployé."
    : "C'est un cas d'usage concret — on peut partir de là pour le premier déploiement.";

  return (
    <div className="card" style={{
      padding: "28px 32px",
      background: "linear-gradient(135deg, rgba(0,174,239,0.06) 0%, rgba(8,15,26,0.95) 100%)",
      border: "1px solid rgba(0,174,239,0.2)",
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6, color: "var(--accent-400)" }}>Ce qu'on ferait ensemble</div>
          <h3 className="display" style={{ fontSize: 24, margin: 0 }}>{offer?.name || "Agents recommandés"}</h3>
        </div>
        <span style={{
          fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase",
          color: "var(--accent-400)", background: "rgba(0,174,239,0.1)",
          border: "1px solid rgba(0,174,239,0.2)", borderRadius: 6, padding: "4px 10px",
        }}>Recommandé</span>
      </div>

      {/* Encart verbatim — p3 ou v8 */}
      {highlightText && (
        <div style={{
          padding: "14px 16px", marginBottom: 16,
          background: "rgba(0,174,239,0.08)", border: "1px solid rgba(0,174,239,0.2)",
          borderRadius: 10, display: "flex", alignItems: "flex-start", gap: 10,
        }}>
          <Icon name="sparkles" size={14} color="var(--accent)" style={{ flexShrink: 0, marginTop: 2 }} />
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: "var(--accent-400)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 4 }}>
              {highlightLabel}
            </div>
            <div style={{ fontSize: 13, color: "var(--text)", fontStyle: "italic", lineHeight: 1.5 }}>
              "{highlightText}"
            </div>
            <div style={{ fontSize: 12, color: "var(--text-soft)", marginTop: 4 }}>
              {highlightSub}
            </div>
          </div>
        </div>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 20 }}>
        {agents.map((agent, i) => (
          <div key={agent.id || i} style={{
            display: "flex", alignItems: "flex-start", gap: 14, padding: "16px 18px",
            background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.07)", borderRadius: 12,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10, flexShrink: 0,
              background: agentColors[i] || "var(--accent-500)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <Icon name="sparkles" size={15} color="white" />
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4, color: "var(--text)" }}>{agent.name}</div>
              <div style={{ fontSize: 13, color: "var(--text-soft)", lineHeight: 1.5 }}>
                {agentDesc(agent, i)}
              </div>
            </div>
          </div>
        ))}
      </div>

      <button className="btn btn-accent" style={{ width: "100%" }} onClick={() => onNav && onNav("roi")}>
        <Icon name="arrowRight" size={13} /> {ctaText}
      </button>

      {/* Section outils — statut intégration */}
      {data.integration && data.integration.summary.total > 0 && (
        <ToolsIntegrationBlock integration={data.integration} />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// BLOC INTÉGRATION OUTILS — affiché dans AgentsCard
// ─────────────────────────────────────────────────────────────
function ToolsIntegrationBlock({ integration }) {
  const { byDomain, summary, level } = integration;

  const domainLabels = { rh: "RH & plannings", compta: "Comptabilité", ventes: "Commercial", client: "Relation client" };
  const statusMeta = {
    api:       { label: "API native",          color: "#10B981", icon: "check" },
    connector: { label: "Via connecteur",      color: "#F59E0B", icon: "plug" },
    none:      { label: "Pas d'API connue",    color: "#EF4444", icon: "x" },
    unknown:   { label: "À vérifier",          color: "#64748B", icon: "info" },
  };

  const levelMeta = {
    green:  { label: "Intégration globalement facile",   color: "#10B981", bg: "rgba(16,185,129,0.08)",  border: "rgba(16,185,129,0.2)" },
    orange: { label: "Quelques ajustements nécessaires", color: "#F59E0B", bg: "rgba(245,158,11,0.08)", border: "rgba(245,158,11,0.2)" },
    red:    { label: "Points complexes à anticiper",     color: "#EF4444", bg: "rgba(239,68,68,0.08)",  border: "rgba(239,68,68,0.2)" },
  };

  const lm = levelMeta[level] || levelMeta.orange;

  return (
    <div style={{ marginTop: 20, paddingTop: 20, borderTop: "1px solid rgba(255,255,255,0.07)" }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-mute)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 12 }}>
        Vos outils actuels
      </div>

      {/* Niveau global */}
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        padding: "8px 12px", borderRadius: 8, marginBottom: 12,
        background: lm.bg, border: `1px solid ${lm.border}`,
        fontSize: 12, color: lm.color, fontWeight: 500,
      }}>
        <Icon name={level === "green" ? "check" : level === "red" ? "alert" : "info"} size={13} />
        {lm.label}
      </div>

      {/* Détail par domaine */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {Object.entries(byDomain).map(([domain, info]) => {
          if (!info.raw) return null;
          const meta = statusMeta[info.status] || statusMeta.unknown;
          return (
            <div key={domain} style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "10px 14px",
              background: "rgba(255,255,255,0.02)",
              border: "1px solid rgba(255,255,255,0.06)",
              borderRadius: 10,
            }}>
              <div>
                <div style={{ fontSize: 12, color: "var(--text-mute)", marginBottom: 2 }}>{domainLabels[domain]}</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: "var(--white)" }}>{info.name}</div>
              </div>
              <span style={{
                fontSize: 11, fontWeight: 600,
                color: meta.color,
                background: `${meta.color}18`,
                border: `1px solid ${meta.color}40`,
                borderRadius: 6, padding: "3px 8px",
                whiteSpace: "nowrap",
              }}>
                {meta.label}
              </span>
            </div>
          );
        })}
      </div>

      {/* Note si outils non répertoriés */}
      {summary.complex > 0 && (
        <div style={{ fontSize: 12, color: "var(--text-mute)", marginTop: 10, lineHeight: 1.5 }}>
          ⚠ Un ou plusieurs outils nécessitent une vérification manuelle avant de confirmer la faisabilité de l'intégration.
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// STICKY CTA — v5 : label affiné selon urgence r7 et profil
// ─────────────────────────────────────────────────────────────
function BookingCTA({ onBookCall, data, answers }) {
  const profile    = data?.profile;
  const commercial = data?.commercial || {};

  // Priorité : urgence calendaire > profil dirigeant > défaut
  const ctaLabel =
    commercial.isUrgent                ? "Démarrer maintenant — j'ai une échéance" :
    profile?.id === "urgent"           ? "Parler de votre problème maintenant" :
    profile?.id === "skeptical"        ? "Poser vos questions à un expert" :
    commercial.hasBudget               ? "Cadrer le projet — budget disponible" :
    commercial.hasIdentifiedProcess    ? "Voir comment automatiser ce processus" :
                                         "Prendre rendez-vous";

  const subLabel =
    commercial.isUrgent   ? "Votre échéance approche — 30 min pour prioriser." :
    commercial.hasBudget  ? "Votre budget est alloué — définissons le périmètre." :
                             "30 min offertes pour prioriser votre roadmap.";

  return (
    <div style={{
      position: "sticky", bottom: 0, zIndex: 10,
      borderTop: "1px solid var(--border)", background: "rgba(8,15,26,0.95)",
      backdropFilter: "blur(12px)", padding: "14px 28px",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ display: "flex" }}>
            {["#4F52E5", "#8B5CF6", "#0EA5A3"].map((c, i) => (
              <div key={i} style={{
                width: 32, height: 32, borderRadius: "50%", background: c,
                border: "2px solid var(--bg2)", marginLeft: i === 0 ? 0 : -8,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "white", fontSize: 12, fontWeight: 600,
              }}>{["R", "A", "T"][i]}</div>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Besoin d'un avis humain ?</div>
            <div style={{ fontSize: 12, color: "var(--text-soft)" }}>{subLabel}</div>
          </div>
        </div>
        <button className="btn btn-accent" onClick={onBookCall}>
          <Icon name="calendar" size={13} /> {ctaLabel}
        </button>
      </div>
    </div>
  );
}

window.Report = Report;
