import { useState, useMemo } from "react";

const GLOBAL_CSS = `
  @import url('https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500;600&display=swap');
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body { background: #060910; }
  ::-webkit-scrollbar { width: 5px; }
  ::-webkit-scrollbar-track { background: #0c1220; }
  ::-webkit-scrollbar-thumb { background: #1e3a5f; border-radius: 99px; }
  input[type=range] { -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer; }

  .num-transition {
    transition: color 0.35s ease, opacity 0.25s ease;
  }
  .bar-fill {
    transition: width 0.5s cubic-bezier(0.4,0,0.2,1), background 0.35s ease;
  }
  .card-glow-on {
    box-shadow: 0 0 0 1.5px rgba(16,185,129,0.35), 0 4px 24px rgba(16,185,129,0.12);
    transition: box-shadow 0.4s ease;
  }
  .card-glow-off {
    box-shadow: none;
    transition: box-shadow 0.4s ease;
  }
`;

// ─── ROLES ────────────────────────────────────────────────────────────────────
const ROLES = [
  { id: "copywriter", label: "Copywriter / Storyteller",   icon: "✍️", color: "#8b5cf6", hoursPerWeek: 35 },
  { id: "seo",        label: "SEO Manager",                icon: "📈", color: "#3b82f6", hoursPerWeek: 35 },
  { id: "graphiste",  label: "Graphiste / Motion",         icon: "🖼️", color: "#ec4899", hoursPerWeek: 35 },
  { id: "cm",         label: "Community Manager",          icon: "📱", color: "#f59e0b", hoursPerWeek: 35 },
  { id: "publisher",  label: "Intégrateur / Publisher",    icon: "🌐", color: "#10b981", hoursPerWeek: 35 },
  { id: "chef",       label: "Chef de projet / Validation",icon: "✅", color: "#64748b", hoursPerWeek: 35 },
];

// ─── CONTENT TYPES ────────────────────────────────────────────────────────────
const CONTENT_TYPES = [
  {
    id: "blog", label: "Article de blog", icon: "✍️", avgPrice: 280,
    phases: {
      production: {
        brief:     { label: "Brief & recherche",            h: 0.75, role: "copywriter" },
        redaction: { label: "Rédaction",                    h: 2.00, role: "copywriter" },
        images:    { label: "Recherche visuels",             h: 0.50, role: "graphiste"  },
        seo:       { label: "Optimisation SEO",              h: 0.25, role: "seo"        },
      },
      validation: {
        relecture: { label: "Relecture interne",             h: 0.50, role: "chef"       },
        retours:   { label: "Intégration retours client",    h: 0.50, role: "chef"       },
        navette:   { label: "Navettes de validation",        h: 0.25, role: "chef"       },
      },
      diffusion: {
        cms:       { label: "Mise en forme CMS",             h: 0.25, role: "publisher"  },
        social:    { label: "Déclinaison réseaux",           h: 0.50, role: "cm"         },
        newsletter:{ label: "Adaptation newsletter",         h: 0.25, role: "cm"         },
        scheduling:{ label: "Planification & publish",       h: 0.25, role: "cm"         },
      },
    },
  },
  {
    id: "newsletter", label: "Newsletter", icon: "📨", avgPrice: 180,
    phases: {
      production: {
        brief:     { label: "Brief & thème",                 h: 0.25, role: "copywriter" },
        redaction: { label: "Rédaction",                     h: 1.25, role: "copywriter" },
        images:    { label: "Visuels & mise en page",        h: 0.50, role: "graphiste"  },
      },
      validation: {
        relecture: { label: "Relecture interne",             h: 0.25, role: "chef"       },
        retours:   { label: "Retours client",                h: 0.25, role: "chef"       },
        test:      { label: "Test envoi & prévisualisation", h: 0.25, role: "publisher"  },
      },
      diffusion: {
        segmentation:{ label: "Segmentation liste",          h: 0.25, role: "seo"        },
        scheduling:  { label: "Paramétrage & envoi",         h: 0.25, role: "cm"         },
        perf:        { label: "Suivi performance",           h: 0.25, role: "seo"        },
      },
    },
  },
  {
    id: "social", label: "Post réseaux sociaux", icon: "📱", avgPrice: 40,
    phases: {
      production: {
        redaction: { label: "Rédaction du post",             h: 0.25, role: "cm"         },
        visuel:    { label: "Création du visuel",            h: 0.25, role: "graphiste"  },
        hashtags:  { label: "Hashtags / CTA",                h: 0.10, role: "cm"         },
      },
      validation: {
        relecture: { label: "Validation interne",            h: 0.10, role: "chef"       },
        retours:   { label: "Retours client",                h: 0.10, role: "chef"       },
      },
      diffusion: {
        adaptation:{ label: "Adaptation par réseau",         h: 0.25, role: "cm"         },
        scheduling:{ label: "Planification",                 h: 0.10, role: "cm"         },
      },
    },
  },
  {
    id: "site", label: "Page web / site", icon: "🌐", avgPrice: 450,
    phases: {
      production: {
        brief:     { label: "Brief éditorial & architecture", h: 1.00, role: "copywriter" },
        redaction: { label: "Rédaction copywriting",          h: 2.50, role: "copywriter" },
        images:    { label: "Sélection / création visuels",   h: 0.75, role: "graphiste"  },
        seo:       { label: "Balises & méta-données SEO",     h: 0.50, role: "seo"        },
      },
      validation: {
        relecture: { label: "Relecture & cohérence marque",   h: 0.75, role: "chef"       },
        retours:   { label: "Retours client (×2 navettes)",   h: 1.00, role: "chef"       },
      },
      diffusion: {
        integration:{ label: "Intégration CMS / page builder",h: 0.50, role: "publisher" },
        social:     { label: "Extraits réseaux & ads",         h: 0.50, role: "cm"        },
        seo_final:  { label: "Indexation & suivi SEO",         h: 0.25, role: "seo"       },
      },
    },
  },
  {
    id: "other", label: "Autre contenu", icon: "📄", avgPrice: 150,
    phases: {
      production: {
        brief:     { label: "Brief",        h: 0.25, role: "copywriter" },
        redaction: { label: "Rédaction",    h: 1.25, role: "copywriter" },
        images:    { label: "Visuels",      h: 0.25, role: "graphiste"  },
      },
      validation: {
        relecture: { label: "Relecture",    h: 0.25, role: "chef"       },
        retours:   { label: "Retours client",h: 0.25, role: "chef"      },
      },
      diffusion: {
        formatting:{ label: "Mise en forme",h: 0.25, role: "publisher"  },
        scheduling:{ label: "Publication",  h: 0.25, role: "cm"         },
      },
    },
  },
];

const LEVERS = {
  production: {
    brief:      { gain: 0.70, label: "Alignement marque automatique", color: "#3b82f6", icon: "🎯" },
    redaction:  { gain: 0.80, label: "Rédaction IA brand-safe",       color: "#8b5cf6", icon: "⚡" },
    images:     { gain: 0.85, label: "Génération d'images intégrée",  color: "#ec4899", icon: "🖼️" },
    seo:        { gain: 0.75, label: "SEO automatisé",                 color: "#10b981", icon: "📈" },
    hashtags:   { gain: 0.80, label: "Suggestions IA",                 color: "#3b82f6", icon: "⚡" },
    visuel:     { gain: 0.85, label: "Génération d'images intégrée",  color: "#ec4899", icon: "🖼️" },
  },
  validation: {
    relecture:  { gain: 0.60, label: "Rédaction parfaite immédiate",  color: "#8b5cf6", icon: "✅" },
    retours:    { gain: 0.65, label: "Moins de navettes client",       color: "#f59e0b", icon: "🔁" },
    navette:    { gain: 0.70, label: "Validation facilitée",           color: "#f59e0b", icon: "🔁" },
    test:       { gain: 0.40, label: "Prévisualisation intégrée",     color: "#3b82f6", icon: "👁️" },
  },
  diffusion: {
    cms:         { gain: 0.70, label: "Formatage automatique",         color: "#10b981", icon: "📤" },
    formatting:  { gain: 0.70, label: "Formatage automatique",         color: "#10b981", icon: "📤" },
    social:      { gain: 0.90, label: "Déclinaison multicanal auto",   color: "#ec4899", icon: "📡" },
    newsletter:  { gain: 0.90, label: "Déclinaison multicanal auto",   color: "#ec4899", icon: "📡" },
    scheduling:  { gain: 0.50, label: "Planification assistée",        color: "#3b82f6", icon: "📅" },
    adaptation:  { gain: 0.90, label: "Déclinaison multicanal auto",   color: "#ec4899", icon: "📡" },
    perf:        { gain: 0.30, label: "Tableaux de bord intégrés",    color: "#3b82f6", icon: "📊" },
    segmentation:{ gain: 0.50, label: "Ciblage assisté",              color: "#f59e0b", icon: "🎯" },
    integration: { gain: 0.60, label: "Export structuré",             color: "#10b981", icon: "📤" },
    seo_final:   { gain: 0.70, label: "SEO automatisé",                color: "#10b981", icon: "📈" },
  },
};

const PHASE_META = {
  production: { label: "Production", color: "#8b5cf6", bg: "rgba(139,92,246,0.08)", border: "rgba(139,92,246,0.2)" },
  validation: { label: "Validation", color: "#f59e0b", bg: "rgba(245,158,11,0.08)", border: "rgba(245,158,11,0.2)" },
  diffusion:  { label: "Diffusion",  color: "#10b981", bg: "rgba(16,185,129,0.08)", border: "rgba(16,185,129,0.2)" },
};

// Forfaits clients SaaS (achetés par les clients via l'agence)
const CLIENT_PLANS = [
  {
    id: "basic",     label: "Basic",     price: 29,  color: "#3b82f6",
    desc: "Accès essentiel · client autonome sur les bases",
    autonomy: 0.40, // fraction du travail contenu pris en charge par le client
    features: ["Rédaction IA", "3 canaux", "50 crédits/mois"],
  },
  {
    id: "essentiel", label: "Essentiel", price: 79,  color: "#8b5cf6",
    desc: "Autonomie avancée · visuels et multicanal inclus",
    autonomy: 0.65,
    features: ["Tout Basic", "Visuels IA", "Déclinaison multicanal", "150 crédits/mois"],
  },
  {
    id: "pro",       label: "Pro",       price: 129, color: "#10b981",
    desc: "Autonomie complète · brand kit + images illimitées",
    autonomy: 0.85,
    features: ["Tout Essentiel", "Brand Kit complet", "Images illimitées", "400 crédits/mois"],
  },
];

const TDC_COMM           = 0.20;   // commission TDC sur revenus SaaS
const AGENCY_MARGIN_SAAS = 0.30;   // marge agence sur revente licences
const BRAND_BONUS        = 0.12;
const SUB_COST           = 199;    // abonnement agence mode prestation
const WEEKS_PER_MONTH= 4.33;
const BUFFER         = 0.80;

const fmt  = (n) => new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(n);
const fmtH = (h) => h === 0 ? "0h" : h < 1 ? `${Math.round(h * 60)}min` : `${h % 1 === 0 ? h : h.toFixed(1)}h`;

function taskGain(phase, key, on) { return on ? (LEVERS[phase]?.[key]?.gain ?? 0) : 0; }
function phaseTotal(ct, phase)       { return Object.values(ct.phases[phase]).reduce((s, t) => s + t.h, 0); }
function phaseTotalWith(ct, phase, on) {
  return Object.entries(ct.phases[phase]).reduce((s, [key, t]) => {
    return s + t.h * (1 - taskGain(phase, key, on));
  }, 0);
}
function roleHoursForContent(ct, on) {
  const load = {};
  ROLES.forEach(r => { load[r.id] = 0; });
  ["production","validation","diffusion"].forEach(phase => {
    Object.entries(ct.phases[phase]).forEach(([key, task]) => {
      const g = taskGain(phase, key, on);
      load[task.role] = (load[task.role] || 0) + task.h * (1 - g);
    });
  });
  return load;
}

// ─── TOGGLE COMPONENT ─────────────────────────────────────────────────────────
function ContentsToggle({ on, setOn }) {
  return (
    <button
      onClick={() => setOn(v => !v)}
      style={{
        display: "flex", alignItems: "center", gap: "12px",
        padding: "10px 18px 10px 14px",
        borderRadius: "99px", border: "none", cursor: "pointer",
        background: on
          ? "linear-gradient(135deg, rgba(16,185,129,0.2), rgba(16,185,129,0.08))"
          : "rgba(255,255,255,0.04)",
        boxShadow: on ? "0 0 0 1.5px rgba(16,185,129,0.5), 0 4px 20px rgba(16,185,129,0.2)" : "0 0 0 1px #1a2744",
        transition: "all 0.35s cubic-bezier(0.4,0,0.2,1)",
      }}
    >
      {/* Switch track */}
      <div style={{
        width: "44px", height: "24px", borderRadius: "99px",
        background: on ? "#10b981" : "#1a2744",
        position: "relative", flexShrink: 0,
        transition: "background 0.35s ease",
        boxShadow: on ? "0 0 10px rgba(16,185,129,0.5)" : "none",
      }}>
        <div style={{
          position: "absolute", top: "3px",
          left: on ? "23px" : "3px",
          width: "18px", height: "18px", borderRadius: "50%",
          background: "#fff",
          transition: "left 0.3s cubic-bezier(0.4,0,0.2,1)",
          boxShadow: "0 1px 4px rgba(0,0,0,0.3)",
        }} />
      </div>
      {/* Label */}
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
          <span style={{ fontSize: "13px", fontWeight: "700", color: on ? "#10b981" : "#64748b", transition: "color 0.3s" }}>
            Contentz {on ? "activé" : "désactivé"}
          </span>
          {on && (
            <span style={{ fontSize: "10px", background: "rgba(16,185,129,0.15)", border: "1px solid rgba(16,185,129,0.3)", color: "#10b981", borderRadius: "99px", padding: "1px 7px", fontWeight: "700" }}>
              ON
            </span>
          )}
        </div>
        <div style={{ fontSize: "10px", color: on ? "rgba(16,185,129,0.7)" : "#334155", marginTop: "1px", transition: "color 0.3s" }}>
          {on ? "Gains actifs · tous les leviers en action" : "Mode référence · pas de levier activé"}
        </div>
      </div>
    </button>
  );
}

// ─── ANIMATED NUMBER ──────────────────────────────────────────────────────────
function Num({ value, color, size = "14px", bold = true, mono = true }) {
  return (
    <span className="num-transition" style={{
      fontFamily: mono ? "'IBM Plex Mono', monospace" : "inherit",
      fontSize: size, fontWeight: bold ? "800" : "400", color,
      transition: "color 0.35s ease",
    }}>{value}</span>
  );
}

// ─── PROGRESS BAR ─────────────────────────────────────────────────────────────
function Bar({ pct, color, height = "6px", bg = "#1a2744" }) {
  return (
    <div style={{ height, background: bg, borderRadius: "99px", overflow: "hidden" }}>
      <div className="bar-fill" style={{
        width: `${Math.min(100, Math.max(0, pct))}%`,
        height: "100%", background: color, borderRadius: "99px",
      }} />
    </div>
  );
}

// ─── SMALL UI ─────────────────────────────────────────────────────────────────
function Pill({ color, children }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: "3px", padding: "2px 7px", borderRadius: "99px", background: color + "22", border: `1px solid ${color}44`, fontSize: "10px", color, fontWeight: "600", whiteSpace: "nowrap", lineHeight: 1.6 }}>{children}</span>
  );
}

function Slider({ label, value, min, max, step = 1, onChange, suffix = "" }) {
  const p = ((value - min) / (max - min)) * 100;
  return (
    <div style={{ marginBottom: "16px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "6px" }}>
        <span style={{ fontSize: "12px", color: "#64748b" }}>{label}</span>
        <span style={{ fontSize: "13px", fontWeight: "600", color: "#e2e8f0", fontFamily: "'IBM Plex Mono', monospace" }}>{value}{suffix}</span>
      </div>
      <div style={{ position: "relative", height: "4px", background: "#1a2744", borderRadius: "99px" }}>
        <div style={{ position: "absolute", height: "100%", left: 0, width: `${p}%`, background: "linear-gradient(90deg, #1d4ed8, #7c3aed)", borderRadius: "99px" }} />
        <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))}
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer", margin: 0 }} />
      </div>
    </div>
  );
}

function Counter({ type, value, onChange, on }) {
  // Temps unitaire sans et avec Contentz
  const hWithout = ["production","validation","diffusion"].reduce((s, p) => s + phaseTotal(type, p), 0);
  const hWith    = ["production","validation","diffusion"].reduce((s, p) => s + phaseTotalWith(type, p, true), 0);
  const pctGain  = hWithout > 0 ? Math.round((hWithout - hWith) / hWithout * 100) : 0;

  return (
    <div style={{ background: "#060910", borderRadius: "10px", border: "1px solid #1a2744", marginBottom: "7px", overflow: "hidden" }}>
      {/* Ligne principale */}
      <div style={{ display: "flex", alignItems: "center", gap: "10px", padding: "9px 13px" }}>
        <span style={{ fontSize: "14px" }}>{type.icon}</span>
        <span style={{ flex: 1, fontSize: "12px", color: "#94a3b8" }}>{type.label}</span>
        <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
          <button onClick={() => onChange(Math.max(0, value - 1))} style={{ width: "24px", height: "24px", borderRadius: "6px", background: "#1a2744", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: "14px" }}>−</button>
          <span style={{ width: "24px", textAlign: "center", fontWeight: "700", color: "#e2e8f0", fontFamily: "'IBM Plex Mono', monospace", fontSize: "13px" }}>{value}</span>
          <button onClick={() => onChange(value + 1)} style={{ width: "24px", height: "24px", borderRadius: "6px", background: "#1a2744", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: "14px" }}>+</button>
        </div>
      </div>
      {/* Ligne temps */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "5px 13px 7px",
        borderTop: "1px solid rgba(255,255,255,0.04)",
        gap: "6px"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
          <span style={{ fontSize: "9px", color: "#334155", textTransform: "uppercase", letterSpacing: "0.06em" }}>Durée</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          {/* Sans Contentz */}
          <div style={{ display: "flex", alignItems: "center", gap: "3px" }}>
            <span style={{ fontSize: "9px", color: "#475569" }}>sans</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "11px", color: on ? "#475569" : "#94a3b8", fontWeight: "600",
              textDecoration: on ? "line-through" : "none" }}>
              {fmtH(hWithout)}
            </span>
          </div>
          {/* Flèche */}
          <span style={{ fontSize: "9px", color: "#334155" }}>→</span>
          {/* Avec Contentz */}
          <div style={{ display: "flex", alignItems: "center", gap: "3px" }}>
            <span style={{ fontSize: "9px", color: on ? "#10b981" : "#334155" }}>avec</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "11px", color: on ? "#10b981" : "#334155", fontWeight: "700" }}>
              {fmtH(hWith)}
            </span>
          </div>
          {/* Badge gain */}
          <span style={{
            fontSize: "9px", padding: "1px 5px", borderRadius: "99px",
            background: on ? "rgba(16,185,129,0.15)" : "rgba(255,255,255,0.04)",
            border: `1px solid ${on ? "rgba(16,185,129,0.3)" : "#1a2744"}`,
            color: on ? "#10b981" : "#334155", fontWeight: "700",
            transition: "all 0.3s"
          }}>
            −{pctGain}%
          </span>
        </div>
      </div>
    </div>
  );
}

// ─── CONTENT CARD (accordéon) ─────────────────────────────────────────────────
function ContentCard({ ct, qty, clients, hourlyRate, on }) {
  const [open, setOpen] = useState(false);
  if (qty === 0) return null;
  const total = qty * clients;

  const hUnit   = (active) => ["production","validation","diffusion"].reduce((s, p) => s + phaseTotalWith(ct, p, active), 0);
  const hU0     = hUnit(false);
  const hUOn    = hUnit(on);
  const costU0  = hU0 * hourlyRate;
  const costUOn = hUOn * hourlyRate;
  const marginU0  = ct.avgPrice - costU0;
  const marginUOn = ct.avgPrice - costUOn;

  const hTot0  = hU0  * total;
  const hTotOn = hUOn * total;
  const hSaved = hTot0 - hTotOn;
  const pctSav = hTot0 > 0 ? (hTot0 - hTotOn) / hTot0 : 0;

  const phases = ["production","validation","diffusion"].map(p => ({
    p, meta: PHASE_META[p],
    hB: phaseTotal(ct, p) * total,
    hA: phaseTotalWith(ct, p, on) * total,
  }));

  return (
    <div className={on ? "card-glow-on" : "card-glow-off"}
      style={{ background: "#0a1428", border: `1px solid ${on ? "rgba(16,185,129,0.25)" : "#1a2744"}`, borderRadius: "14px", overflow: "hidden", marginBottom: "10px", transition: "border-color 0.35s" }}>
      <button onClick={() => setOpen(!open)} style={{ width: "100%", display: "flex", alignItems: "center", gap: "12px", padding: "13px 18px", background: "transparent", border: "none", cursor: "pointer", textAlign: "left" }}>
        <span style={{ fontSize: "17px" }}>{ct.icon}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: "13px", fontWeight: "700", color: "#e2e8f0" }}>{ct.label}</div>
          <div style={{ fontSize: "11px", color: "#475569" }}>{qty}/client · {total} contenus/mois</div>
        </div>

        {/* Coût unitaire badge — side-by-side */}
        <div style={{ display: "flex", gap: "8px", alignItems: "center", flexShrink: 0, padding: "6px 10px", borderRadius: "10px", background: "rgba(0,0,0,0.3)", border: "1px solid #1a2744" }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: "9px", color: "#475569", marginBottom: "2px", textTransform: "uppercase" }}>Coût unit.</div>
            <Num value={fmt(on ? costUOn : costU0)} color={on ? "#10b981" : "#64748b"} size="13px" />
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: "9px", color: "#475569", marginBottom: "2px", textTransform: "uppercase" }}>Marge</div>
            <Num value={`${Math.max(0, Math.round((on ? marginUOn : marginU0) / ct.avgPrice * 100))}%`} color={on ? "#10b981" : "#f59e0b"} size="13px" />
          </div>
          {on && (
            <div style={{ textAlign: "center", borderLeft: "1px solid #1a2744", paddingLeft: "8px" }}>
              <div style={{ fontSize: "9px", color: "#10b981", marginBottom: "2px", textTransform: "uppercase" }}>Économie</div>
              <Num value={fmt(costU0 - costUOn)} color="#10b981" size="13px" />
            </div>
          )}
        </div>

        {/* Mini phases */}
        <div style={{ display: "flex", gap: "5px" }}>
          {phases.map(({ p, meta, hB, hA }) => (
            <div key={p} style={{ padding: "4px 7px", borderRadius: "8px", background: meta.bg, border: `1px solid ${meta.border}`, textAlign: "center" }}>
              <div style={{ fontSize: "9px", color: meta.color, fontWeight: "700", textTransform: "uppercase", marginBottom: "1px" }}>{p.slice(0,3)}.</div>
              <div style={{ fontSize: "9px", fontFamily: "'IBM Plex Mono', monospace", color: "#64748b" }}>{fmtH(hB)}</div>
              {on && <div style={{ fontSize: "9px", fontFamily: "'IBM Plex Mono', monospace", color: meta.color, fontWeight: "700" }}>→{fmtH(hA)}</div>}
            </div>
          ))}
        </div>

        {/* Global gain */}
        <div style={{ textAlign: "right", flexShrink: 0, marginLeft: "6px", minWidth: "80px" }}>
          {on ? (
            <>
              <Num value={`−${fmtH(hSaved)}`} color="#10b981" size="16px" />
              <div style={{ fontSize: "11px", color: "#475569", marginTop: "2px" }}>{Math.round(pctSav * 100)}% du temps</div>
              <div style={{ fontSize: "11px", color: "#10b981" }}>{fmt(hSaved * hourlyRate)}</div>
            </>
          ) : (
            <>
              <Num value={fmtH(hTot0)} color="#64748b" size="16px" />
              <div style={{ fontSize: "11px", color: "#475569", marginTop: "2px" }}>heures/mois</div>
              <div style={{ fontSize: "11px", color: "#475569" }}>{fmt(hTot0 * hourlyRate)}</div>
            </>
          )}
        </div>
        <span style={{ color: "#334155", fontSize: "11px", marginLeft: "4px" }}>{open ? "▲" : "▼"}</span>
      </button>

      {open && (
        <div style={{ padding: "0 18px 18px" }}>

          {/* Bloc coût unitaire comparatif */}
          <div style={{ background: "#060910", border: "1px solid #1a2744", borderRadius: "12px", padding: "14px", marginBottom: "14px" }}>
            <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: "12px" }}>
              Coût de revient · par contenu unitaire
            </div>
            {/* Tableau phases */}
            <div style={{ display: "grid", gridTemplateColumns: "90px 1fr 70px 70px", gap: "6px", marginBottom: "10px" }}>
              <div style={{ fontSize: "10px", color: "#334155", paddingBottom: "4px", borderBottom: "1px solid #1a2744" }}>Phase</div>
              <div style={{ borderBottom: "1px solid #1a2744" }} />
              <div style={{ fontSize: "10px", color: "#475569", textAlign: "right", paddingBottom: "4px", borderBottom: "1px solid #1a2744" }}>Heures</div>
              <div style={{ fontSize: "10px", color: "#475569", textAlign: "right", paddingBottom: "4px", borderBottom: "1px solid #1a2744" }}>Coût</div>

              {["production","validation","diffusion"].map(p => {
                const meta = PHASE_META[p];
                const hRef = phaseTotal(ct, p);
                const hNow = phaseTotalWith(ct, p, on);
                const saved = hRef - hNow;
                return [
                  <div key={`${p}l`} style={{ fontSize: "11px", color: meta.color, fontWeight: "600", paddingTop: "5px" }}>{meta.label}</div>,
                  <div key={`${p}b`} style={{ paddingTop: "7px" }}>
                    <Bar pct={(hNow/hRef)*100} color={meta.color} height="4px" />
                    {on && saved > 0 && <div style={{ fontSize: "10px", color: meta.color, marginTop: "2px" }}>−{fmtH(saved)} ({Math.round((saved/hRef)*100)}%)</div>}
                  </div>,
                  <div key={`${p}h`} style={{ textAlign: "right", paddingTop: "5px" }}>
                    {on && <div style={{ fontSize: "10px", color: "#475569", textDecoration: "line-through", fontFamily: "'IBM Plex Mono', monospace" }}>{fmtH(hRef)}</div>}
                    <Num value={fmtH(hNow)} color={on ? "#e2e8f0" : "#94a3b8"} size="11px" bold={false} />
                  </div>,
                  <div key={`${p}c`} style={{ textAlign: "right", paddingTop: "5px" }}>
                    {on && <div style={{ fontSize: "10px", color: "#475569", textDecoration: "line-through", fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(hRef * hourlyRate)}</div>}
                    <Num value={fmt(hNow * hourlyRate)} color={on ? "#e2e8f0" : "#94a3b8"} size="11px" bold={false} />
                  </div>,
                ];
              })}
            </div>

            {/* Synthèse 3 cases */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "8px" }}>
              <div style={{ background: "#0a1428", borderRadius: "10px", padding: "10px", textAlign: "center" }}>
                <div style={{ fontSize: "10px", color: "#334155", textTransform: "uppercase", marginBottom: "5px" }}>Coût de revient</div>
                {on && <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "10px", color: "#475569", textDecoration: "line-through" }}>{fmt(costU0)}</div>}
                <Num value={fmt(on ? costUOn : costU0)} color={on ? "#10b981" : "#e2e8f0"} size="15px" />
                {on && <div style={{ fontSize: "10px", color: "#10b981", marginTop: "3px" }}>−{fmt(costU0 - costUOn)}</div>}
              </div>
              <div style={{ background: "#0a1428", borderRadius: "10px", padding: "10px", textAlign: "center" }}>
                <div style={{ fontSize: "10px", color: "#334155", textTransform: "uppercase", marginBottom: "5px" }}>Marge brute</div>
                {on && <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "10px", color: "#475569" }}>sans : {fmt(Math.max(0, marginU0))}</div>}
                <Num value={fmt(Math.max(0, on ? marginUOn : marginU0))} color="#f59e0b" size="15px" />
                <div style={{ fontSize: "10px", color: "#f59e0b", marginTop: "3px" }}>{Math.max(0, Math.round((on ? marginUOn : marginU0) / ct.avgPrice * 100))}% du prix</div>
              </div>
              <div style={{ background: on ? "rgba(16,185,129,0.08)" : "#0a1428", border: on ? "1px solid rgba(16,185,129,0.2)" : "1px solid transparent", borderRadius: "10px", padding: "10px", textAlign: "center", transition: "all 0.35s" }}>
                <div style={{ fontSize: "10px", color: on ? "#10b981" : "#334155", textTransform: "uppercase", marginBottom: "5px" }}>Gain de marge</div>
                <Num value={on ? `+${fmt(Math.max(0, marginUOn) - Math.max(0, marginU0))}` : "—"} color={on ? "#10b981" : "#334155"} size="15px" />
                <div style={{ fontSize: "10px", color: "#475569", marginTop: "3px" }}>Prix de vente : {fmt(ct.avgPrice)}</div>
              </div>
            </div>
          </div>

          {/* Tâches par phase */}
          {["production","validation","diffusion"].map(phase => {
            const meta  = PHASE_META[phase];
            const tasks = ct.phases[phase];
            const hBef  = phaseTotal(ct, phase) * total;
            const hAft  = phaseTotalWith(ct, phase, on) * total;
            const saved = hBef - hAft;
            return (
              <div key={phase} style={{ background: meta.bg, border: `1px solid ${meta.border}`, borderRadius: "12px", padding: "14px", marginBottom: "10px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "10px" }}>
                  <span style={{ fontSize: "11px", fontWeight: "700", color: meta.color, textTransform: "uppercase", letterSpacing: "0.08em" }}>{meta.label}</span>
                  <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
                    <span style={{ fontSize: "11px", color: "#475569", fontFamily: "'IBM Plex Mono', monospace" }}>total : {fmtH(hBef)}</span>
                    {on && saved > 0 && <span style={{ fontSize: "12px", fontWeight: "700", color: meta.color, fontFamily: "'IBM Plex Mono', monospace" }}>→ {fmtH(hAft)} (−{fmtH(saved)})</span>}
                  </div>
                </div>
                {Object.entries(tasks).map(([key, task], i, arr) => {
                  const role  = ROLES.find(r => r.id === task.role);
                  const lever = LEVERS[phase]?.[key];
                  const g     = taskGain(phase, key, on);
                  const hB    = task.h * total;
                  const hA    = hB * (1 - g);
                  return (
                    <div key={key} style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: "10px", alignItems: "center", paddingBottom: i < arr.length-1 ? "9px" : 0, marginBottom: i < arr.length-1 ? "9px" : 0, borderBottom: i < arr.length-1 ? "1px solid rgba(255,255,255,0.04)" : "none" }}>
                      <div>
                        <div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "4px" }}>
                          <span style={{ fontSize: "11px", color: "#94a3b8" }}>{task.label}</span>
                          {role && <Pill color={role.color}>{role.icon} {role.label}</Pill>}
                        </div>
                        {on && lever ? <Pill color={lever.color}>{lever.icon} {lever.label}</Pill> : !on && <Pill color="#334155">Aucun levier actif</Pill>}
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: "6px", justifyContent: "flex-end", marginBottom: "4px" }}>
                          <Bar pct={(1 - g) * 100} color={on && lever ? meta.color : "#334155"} height="4px" />
                          <span style={{ fontSize: "11px", fontFamily: "'IBM Plex Mono', monospace", color: on && g > 0 ? meta.color : "#334155", minWidth: "30px" }}>
                            {on && g > 0 ? `−${Math.round(g * 100)}%` : "—"}
                          </span>
                        </div>
                        <div style={{ fontSize: "11px", color: "#475569", fontFamily: "'IBM Plex Mono', monospace" }}>
                          {fmtH(hB)}
                          {on && hB - hA > 0 && <> → <span style={{ color: "#e2e8f0" }}>{fmtH(hA)}</span></>}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── TEAM CAPACITY ────────────────────────────────────────────────────────────
function TeamCapacity({ teamSizes, volumes, clients, hourlyRate, avgRevenuePerClient, on }) {
  const roleLoad = useMemo(() => {
    const load = {};
    ROLES.forEach(r => { load[r.id] = 0; });
    CONTENT_TYPES.forEach(ct => {
      const qty = volumes[ct.id] || 0;
      if (!qty) return;
      const total = qty * clients;
      const rl = roleHoursForContent(ct, on);
      ROLES.forEach(r => { load[r.id] += (rl[r.id] || 0) * total; });
    });
    return load;
  }, [volumes, clients, on]);

  const roleCap = (id) => {
    const n = teamSizes[id] || 0;
    const r = ROLES.find(x => x.id === id);
    return n * r.hoursPerWeek * WEEKS_PER_MONTH * BUFFER;
  };

  // Sans Contentz (toujours calculé pour comparer)
  const roleLoadRef = useMemo(() => {
    const load = {};
    ROLES.forEach(r => { load[r.id] = 0; });
    CONTENT_TYPES.forEach(ct => {
      const qty = volumes[ct.id] || 0;
      if (!qty) return;
      const total = qty * clients;
      const rl = roleHoursForContent(ct, false);
      ROLES.forEach(r => { load[r.id] += (rl[r.id] || 0) * total; });
    });
    return load;
  }, [volumes, clients]);

  const bottleneck = ROLES.reduce((worst, r) => {
    const cap = roleCap(r.id); if (cap === 0) return worst;
    const ratio = roleLoad[r.id] / cap;
    return ratio > worst.ratio ? { id: r.id, ratio } : worst;
  }, { id: null, ratio: 0 });

  const additionalClients = (() => {
    const vals = ROLES
      .filter(r => (teamSizes[r.id] || 0) > 0)
      .map(r => {
        const cap    = roleCap(r.id);
        const remain = cap - roleLoad[r.id];
        const perCli = roleLoad[r.id] / (clients || 1);
        return perCli > 0 ? Math.floor(remain / perCli) : 999;
      });
    return vals.length ? Math.max(0, Math.min(...vals)) : 0;
  })();

  const potentialCA = additionalClients * avgRevenuePerClient;
  const barColor    = (r) => r > 1 ? "#ef4444" : r > 0.85 ? "#f59e0b" : "#10b981";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>

      {/* Tableau */}
      <div style={{ background: "#0a1428", border: `1px solid ${on ? "rgba(16,185,129,0.25)" : "#1a2744"}`, borderRadius: "16px", overflow: "hidden", transition: "border-color 0.35s" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid #1a2744" }}>
          <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "3px" }}>
            Charge équipe · {on ? "Avec Contentz activé" : "Sans Contentz"}
          </div>
          <div style={{ fontSize: "12px", color: "#475569" }}>{clients} clients · capacité utilisable {Math.round(BUFFER * 100)}% · {WEEKS_PER_MONTH.toFixed(1)} sem/mois</div>
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "#060910" }}>
                {["Rôle","ETP","Cap. mensuelle","Charge","Taux de charge","Libéré vs réf.","Clients +"].map((h, i) => (
                  <th key={i} style={{ padding: "9px 12px", textAlign: i < 2 ? "left" : "right", fontSize: "10px", color: "#475569", fontWeight: "600", textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {ROLES.map((role, idx) => {
                const n       = teamSizes[role.id] || 0;
                const cap     = roleCap(role.id);
                const load    = roleLoad[role.id] || 0;
                const loadRef = roleLoadRef[role.id] || 0;
                const ratio   = cap > 0 ? load / cap : 0;
                const freed   = loadRef - load;
                const loadPerCli = load / (clients || 1);
                const remain  = cap - load;
                const addCli  = n > 0 && loadPerCli > 0 ? Math.max(0, Math.floor(remain / loadPerCli)) : 0;
                const isOver  = ratio > 1;

                return (
                  <tr key={role.id} style={{ borderBottom: "1px solid #0f1c30", background: idx % 2 === 0 ? "transparent" : "rgba(255,255,255,0.01)" }}>
                    <td style={{ padding: "12px 16px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                        <span style={{ fontSize: "15px" }}>{role.icon}</span>
                        <div>
                          <div style={{ fontSize: "12px", fontWeight: "600", color: n > 0 ? "#e2e8f0" : "#475569" }}>{role.label}</div>
                          <div style={{ fontSize: "10px", color: "#334155" }}>{role.hoursPerWeek}h/sem</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: "12px", textAlign: "right" }}>
                      <Num value={n > 0 ? n : "—"} color={n > 0 ? "#e2e8f0" : "#334155"} size="13px" />
                    </td>
                    <td style={{ padding: "12px", textAlign: "right" }}>
                      <Num value={n > 0 ? fmtH(cap) : "—"} color="#64748b" size="12px" bold={false} />
                    </td>
                    <td style={{ padding: "12px", textAlign: "right" }}>
                      <Num value={n > 0 ? fmtH(load) : "—"} color={n > 0 ? (isOver ? "#ef4444" : on ? "#10b981" : "#94a3b8") : "#334155"} size="12px" />
                    </td>
                    <td style={{ padding: "12px 16px", minWidth: "140px" }}>
                      {n > 0 ? (
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                            <div style={{ flex: 1 }}>
                              <Bar pct={ratio * 100} color={barColor(ratio)} height="6px" />
                            </div>
                            <Num value={`${Math.round(ratio * 100)}%`} color={barColor(ratio)} size="11px" />
                          </div>
                          {isOver && <div style={{ fontSize: "10px", color: "#ef4444", marginTop: "2px" }}>⚠ Surcharge</div>}
                        </div>
                      ) : <span style={{ fontSize: "11px", color: "#334155" }}>—</span>}
                    </td>
                    <td style={{ padding: "12px", textAlign: "right" }}>
                      {on && n > 0 && freed > 0
                        ? <Num value={`−${fmtH(freed)}`} color="#10b981" size="12px" />
                        : <span style={{ fontSize: "11px", color: "#334155" }}>—</span>}
                    </td>
                    <td style={{ padding: "12px 16px", textAlign: "right" }}>
                      {n > 0
                        ? <Num value={addCli > 0 ? `+${addCli}` : "complet"} color={addCli > 0 ? "#3b82f6" : "#334155"} size="13px" />
                        : <span style={{ fontSize: "11px", color: "#334155" }}>—</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* 3 cards */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "14px" }}>
        {/* Goulot */}
        <div style={{ background: bottleneck.ratio > 1 ? "rgba(239,68,68,0.07)" : "rgba(16,185,129,0.07)", border: `1px solid ${bottleneck.ratio > 1 ? "rgba(239,68,68,0.2)" : "rgba(16,185,129,0.2)"}`, borderRadius: "14px", padding: "16px", transition: "all 0.35s" }}>
          <div style={{ fontSize: "11px", color: bottleneck.ratio > 1 ? "#ef4444" : "#10b981", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: "10px" }}>
            {bottleneck.ratio > 1 ? "⚠ Surcharge" : "✅ Équipe OK"}
          </div>
          {bottleneck.id ? (
            <>
              <div style={{ fontSize: "12px", color: "#94a3b8", marginBottom: "6px" }}>Rôle le plus chargé</div>
              <div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" }}>
                <span style={{ fontSize: "18px" }}>{ROLES.find(r => r.id === bottleneck.id)?.icon}</span>
                <span style={{ fontSize: "12px", fontWeight: "700", color: "#e2e8f0" }}>{ROLES.find(r => r.id === bottleneck.id)?.label}</span>
              </div>
              <Num value={`${Math.round(bottleneck.ratio * 100)}%`} color={barColor(bottleneck.ratio)} size="22px" />
              <div style={{ fontSize: "11px", color: "#475569", marginTop: "4px" }}>de la capacité utilisée</div>
            </>
          ) : <div style={{ fontSize: "12px", color: "#334155" }}>Configurez l'équipe</div>}
        </div>

        {/* Heures libérées si on */}
        <div style={{ background: on ? "rgba(16,185,129,0.07)" : "rgba(255,255,255,0.02)", border: `1px solid ${on ? "rgba(16,185,129,0.2)" : "#1a2744"}`, borderRadius: "14px", padding: "16px", transition: "all 0.35s" }}>
          <div style={{ fontSize: "11px", color: on ? "#10b981" : "#475569", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: "10px" }}>
            ⏱ Heures équipe libérées
          </div>
          {ROLES.filter(r => (teamSizes[r.id] || 0) > 0).map(r => {
            const freed = (roleLoadRef[r.id] || 0) - (roleLoad[r.id] || 0);
            return (
              <div key={r.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "7px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                  <span style={{ fontSize: "13px" }}>{r.icon}</span>
                  <span style={{ fontSize: "11px", color: "#94a3b8" }}>{r.label.split("/")[0].trim()}</span>
                </div>
                <Num value={on && freed > 0 ? `−${fmtH(freed)}` : fmtH(roleLoad[r.id])} color={on && freed > 0 ? "#10b981" : "#64748b"} size="12px" />
              </div>
            );
          })}
        </div>

        {/* Potentiel */}
        <div style={{ background: "linear-gradient(135deg, rgba(29,78,216,0.15), rgba(124,58,237,0.15))", border: "1px solid rgba(99,102,241,0.3)", borderRadius: "14px", padding: "16px" }}>
          <div style={{ fontSize: "11px", color: "#818cf8", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: "10px" }}>🚀 Potentiel</div>
          <div style={{ fontSize: "12px", color: "#94a3b8", marginBottom: "6px" }}>Clients supplémentaires</div>
          <Num value={on ? `+${additionalClients}` : "—"} color={on ? "#818cf8" : "#334155"} size="28px" />
          <div style={{ fontSize: "11px", color: "#475569", marginTop: "4px", marginBottom: "12px" }}>avec la même équipe</div>
          <div style={{ borderTop: "1px solid rgba(99,102,241,0.2)", paddingTop: "10px" }}>
            <div style={{ fontSize: "11px", color: "#94a3b8", marginBottom: "4px" }}>CA additionnel / mois</div>
            <Num value={on ? fmt(potentialCA) : "—"} color={on ? "#a855f7" : "#334155"} size="20px" />
            {on && potentialCA > 0 && <div style={{ fontSize: "10px", color: "#475569", marginTop: "3px" }}>{fmt(potentialCA * 12)} / an</div>}
          </div>
        </div>
      </div>

      {/* Narratif */}
      {on && additionalClients > 0 && (
        <div style={{ background: "rgba(99,102,241,0.06)", border: "1px solid rgba(99,102,241,0.18)", borderRadius: "14px", padding: "16px 20px" }}>
          <div style={{ fontSize: "13px", color: "#e2e8f0", lineHeight: 1.7 }}>
            💡 <strong style={{ color: "#a855f7" }}>Ce que Contentz rend possible :</strong>{" "}
            avec la même équipe, vous pouvez absorber{" "}
            <strong style={{ color: "#818cf8" }}>{additionalClients} client{additionalClients > 1 ? "s" : ""} supplémentaire{additionalClients > 1 ? "s" : ""}</strong> sans recruter —
            soit <strong style={{ color: "#10b981" }}>{fmt(potentialCA)}/mois</strong> de CA additionnel,{" "}
            <strong style={{ color: "#10b981" }}>{fmt(potentialCA * 12)}/an</strong>,{" "}
            uniquement grâce aux heures libérées sur la production, la validation et la diffusion.
          </div>
        </div>
      )}
      {!on && (
        <div style={{ background: "rgba(239,68,68,0.04)", border: "1px solid rgba(239,68,68,0.15)", borderRadius: "14px", padding: "14px 20px", textAlign: "center" }}>
          <div style={{ fontSize: "12px", color: "#64748b" }}>
            👆 Activez Contentz pour voir combien de clients supplémentaires votre équipe peut absorber
          </div>
        </div>
      )}
    </div>
  );
}

// ─── MAIN ─────────────────────────────────────────────────────────────────────
export default function App() {
  const [on,             setOn]            = useState(false);
  const [activeTab,      setActiveTab]     = useState("simulator");
  const [mode,           setMode]          = useState("agency");
  const [contentClients, setContentClients]= useState(10);
  const [hourlyRate,     setHourlyRate]    = useState(75);
  const [volumes,        setVolumes]       = useState({ blog: 4, newsletter: 4, social: 20, site: 1, other: 2 });
  // SaaS : nombre de clients ayant souscrit un forfait (pas forcément tous)
  const [saasClients, setSaasClients] = useState(6); // nb clients sur un forfait SaaS
  // SaaS plan split state (% parmi les clients SaaS, somme = 100)
  const [planSplit, setPlanSplit] = useState({ basic: 25, essentiel: 25, pro: 50 });
  const [teamSizes,      setTeamSizes]     = useState({ copywriter: 1, seo: 1, graphiste: 1, cm: 1, publisher: 1, chef: 1 });

  const updVol  = (id, v) => setVolumes(p  => ({ ...p, [id]: Math.max(0, v) }));
  const updTeam = (id, v) => setTeamSizes(p => ({ ...p, [id]: Math.max(0, v) }));
  const updSplit = (id, val) => {
    setPlanSplit(prev => {
      const others = CLIENT_PLANS.filter(p => p.id !== id);
      const clamped = Math.max(0, Math.min(100, val));
      const remaining = 100 - clamped;
      const otherTotal = others.reduce((s, p) => s + (prev[p.id] || 0), 0);
      const updated = { ...prev, [id]: clamped };
      if (otherTotal > 0) {
        others.forEach(p => { updated[p.id] = Math.round((prev[p.id] || 0) / otherTotal * remaining); });
      } else {
        const each = Math.floor(remaining / others.length);
        others.forEach(p => { updated[p.id] = each; });
      }
      return updated;
    });
  };

  const avgRevenuePerClient = useMemo(() =>
    CONTENT_TYPES.reduce((s, ct) => s + (volumes[ct.id] || 0) * ct.avgPrice, 0)
  , [volumes]);

  // Totaux globaux selon toggle
  const { hTot, moneyTime, moneyBrand } = useMemo(() => {
    let hT = 0;
    CONTENT_TYPES.forEach(ct => {
      const tot = (volumes[ct.id] || 0) * contentClients;
      ["production","validation","diffusion"].forEach(p => { hT += phaseTotalWith(ct, p, on) * tot; });
    });
    const hRef = (() => {
      let r = 0;
      CONTENT_TYPES.forEach(ct => {
        const tot = (volumes[ct.id] || 0) * contentClients;
        ["production","validation","diffusion"].forEach(p => { r += phaseTotal(ct, p) * tot; });
      });
      return r;
    })();
    const totalRev = CONTENT_TYPES.reduce((s, ct) => s + (volumes[ct.id] || 0) * ct.avgPrice * contentClients, 0);
    return { hTot: hT, hRef, moneyTime: (hRef - hT) * hourlyRate, moneyBrand: on ? totalRev * BRAND_BONUS : 0 };
  }, [volumes, contentClients, hourlyRate, on]);

  const hRef = useMemo(() => {
    let r = 0;
    CONTENT_TYPES.forEach(ct => {
      const tot = (volumes[ct.id] || 0) * contentClients;
      ["production","validation","diffusion"].forEach(p => { r += phaseTotal(ct, p) * tot; });
    });
    return r;
  }, [volumes, contentClients]);

  const hSaved    = hRef - hTot;
  const pctSav    = hRef > 0 ? hSaved / hRef : 0;
  const agencyNet = moneyTime + moneyBrand - (on ? SUB_COST : 0);

  // ── Calculs SaaS multi-forfaits ──
  // Logique : un client SaaS est autonome avec Contentz → l'agence ne produit PLUS son contenu.
  // Temps libéré = charge totale de ces clients (hRefPerClient × nSaas).
  // L'agence garde ces clients en portefeuille mais la production est supprimée.
  // (On peut prévoir un temps de conseil marginal, ici non factorisé — il reste dans la marge.)

  const saasMemo = useMemo(() => {
    const nSaas    = Math.min(saasClients, contentClients);
    const nNonSaas = contentClients - nSaas;

    // Répartition par forfait (parmi les nSaas clients)
    const planClients = CLIENT_PLANS.map(p => ({
      ...p, n: Math.round(nSaas * (planSplit[p.id] || 0) / 100),
    }));
    const mrrByPlan = planClients.map(p => ({ ...p, mrr: p.n * p.price }));
    const totalMrr  = mrrByPlan.reduce((s, p) => s + p.mrr, 0);

    const tdcLicense = totalMrr * TDC_COMM;
    const agencyLic  = totalMrr * AGENCY_MARGIN_SAAS;

    // Charge par client (basée sur hRef qui inclut déjà tous les clients)
    const hRefPerClient = contentClients > 0 ? hRef / contentClients : 0;

    // Clients SaaS : leur production est intégralement supprimée de la charge agence
    const hRefSaas     = hRefPerClient * nSaas;    // ce qui était produit pour eux
    const hRefNonSaas  = hRefPerClient * nNonSaas; // ce qui reste (prestation normale)

    // Temps libéré = 100% de la charge de production des clients SaaS
    const hTeamSaved    = hRefSaas;
    const moneyTeamSaved = hTeamSaved * hourlyRate;

    // Charge totale agence en mode SaaS = uniquement les clients non-SaaS
    const hTotalSaasMode = hRefNonSaas;
    const hSavedSaasMode = hRef - hTotalSaasMode; // = hRefSaas

    // Crédits additionnels (20% du MRR)
    const extraCredits  = totalMrr * 0.20;
    const tdcCredits    = extraCredits * TDC_COMM;
    const agencyCredits = extraCredits * AGENCY_MARGIN_SAAS;

    return {
      nSaas, nNonSaas, planClients, mrrByPlan, totalMrr,
      tdcLicense, agencyLic,
      hRefPerClient, hRefSaas, hRefNonSaas,
      hTeamSaved, hTotalSaasMode, hSavedSaasMode,
      moneyTeamSaved,
      extraCredits, tdcCredits, agencyCredits,
      tdcTotal:    tdcLicense  + tdcCredits,
      agencyTotal: agencyLic   + agencyCredits,
    };
  }, [saasClients, contentClients, planSplit, hRef, hourlyRate]);

  const globalPhases = ["production","validation","diffusion"].map(ph => {
    let hB = 0, hA = 0;
    CONTENT_TYPES.forEach(ct => {
      const tot = (volumes[ct.id] || 0) * contentClients;
      hB += phaseTotal(ct, ph) * tot;
      hA += phaseTotalWith(ct, ph, on) * tot;
    });
    return { ph, meta: PHASE_META[ph], hB, hA, saved: hB - hA };
  });

  const TABS = [
    { id: "simulator", label: "📊 Simulateur",        sub: "Contenus & ROI" },
    { id: "team",      label: "👥 Équipe & Capacité", sub: "Charge & potentiel" },
  ];

  return (
    <>
      <style>{GLOBAL_CSS}</style>
      <div style={{ minHeight: "100vh", background: "#060910", fontFamily: "'IBM Plex Sans', sans-serif", color: "#e2e8f0", padding: "20px 14px" }}>
        <div style={{ maxWidth: "1260px", margin: "0 auto" }}>

          {/* ── HEADER ── */}
          <div style={{ textAlign: "center", marginBottom: "24px" }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: "6px", background: "rgba(29,78,216,0.12)", border: "1px solid rgba(29,78,216,0.25)", borderRadius: "99px", padding: "5px 14px", marginBottom: "10px" }}>
              <span style={{ width: "5px", height: "5px", borderRadius: "50%", background: "#3b82f6", display: "inline-block" }} />
              <span style={{ fontSize: "10px", color: "#60a5fa", letterSpacing: "0.1em", textTransform: "uppercase" }}>Simulateur ROI · Agences</span>
            </div>
            <h1 style={{ fontFamily: "'Syne', sans-serif", fontSize: "clamp(20px, 3.5vw, 38px)", fontWeight: "800", color: "#fff", lineHeight: 1.1, marginBottom: "8px" }}>
              Ce que Contentz libère,<br />
              <span style={{ background: "linear-gradient(90deg, #3b82f6, #7c3aed)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>tâche par tâche · rôle par rôle</span>
            </h1>
            <p style={{ color: "#475569", fontSize: "13px" }}>Activez le toggle pour voir l'impact en temps réel sur chaque chiffre</p>
          </div>

          {/* ── TOGGLE BARRE STICKY ── */}
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "center",
            background: on ? "rgba(16,185,129,0.06)" : "rgba(255,255,255,0.02)",
            border: `1px solid ${on ? "rgba(16,185,129,0.3)" : "#1a2744"}`,
            borderRadius: "16px", padding: "12px 18px", marginBottom: "20px",
            transition: "all 0.35s",
            flexWrap: "wrap", gap: "12px"
          }}>
            <ContentsToggle on={on} setOn={setOn} />

            {/* Résumé flash */}
            {on ? (
              <div style={{ display: "flex", gap: "20px", flexWrap: "wrap" }}>
                {[
                  { l: "Heures libérées", v: fmtH(hSaved), c: "#10b981" },
                  { l: "Gain temps (€)",  v: fmt(moneyTime), c: "#10b981" },
                  { l: "Bonus marque",    v: fmt(moneyBrand), c: "#8b5cf6" },
                  { l: "Gain net/mois",   v: fmt(agencyNet), c: "#3b82f6" },
                ].map(k => (
                  <div key={k.l} style={{ textAlign: "center" }}>
                    <div style={{ fontSize: "10px", color: "#475569", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: "3px" }}>{k.l}</div>
                    <Num value={k.v} color={k.c} size="15px" />
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ fontSize: "12px", color: "#334155" }}>
                Activez Contentz pour voir l'impact sur tous les chiffres →
              </div>
            )}

            {/* Mode + Tabs */}
            <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
              <div style={{ display: "flex", background: "#0a1428", borderRadius: "10px", padding: "3px", border: "1px solid #1a2744" }}>
                {[{ id: "agency", label: "🏢 Prestation" }, { id: "saas", label: "🔑 SaaS" }].map(m => (
                  <button key={m.id} onClick={() => setMode(m.id)} style={{ padding: "7px 12px", borderRadius: "8px", border: "none", cursor: "pointer", background: mode === m.id ? "linear-gradient(135deg, #1d4ed8, #7c3aed)" : "transparent" }}>
                    <span style={{ fontSize: "11px", fontWeight: "700", color: mode === m.id ? "#fff" : "#475569" }}>{m.label}</span>
                  </button>
                ))}
              </div>
              <div style={{ display: "flex", background: "#0a1428", borderRadius: "10px", padding: "3px", border: "1px solid #1a2744" }}>
                {TABS.map(t => (
                  <button key={t.id} onClick={() => setActiveTab(t.id)} style={{ padding: "7px 12px", borderRadius: "8px", border: "none", cursor: "pointer", background: activeTab === t.id ? "#1a2744" : "transparent" }}>
                    <span style={{ fontSize: "11px", fontWeight: "700", color: activeTab === t.id ? "#e2e8f0" : "#475569" }}>{t.label}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* ── MAIN GRID ── */}
          <div style={{ display: "grid", gridTemplateColumns: "280px 1fr", gap: "18px", alignItems: "start" }}>

            {/* SIDEBAR */}
            <div style={{ display: "flex", flexDirection: "column", gap: "13px" }}>
              <div style={{ background: "#0a1428", border: "1px solid #1a2744", borderRadius: "14px", padding: "16px" }}>
                <div style={{ fontSize: "11px", fontWeight: "700", color: "#3b82f6", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "12px" }}>Paramètres</div>
                <Slider label="Clients avec production de contenu" value={contentClients} min={1} max={150} onChange={setContentClients} />
                <Slider label="Taux horaire moyen" value={hourlyRate} min={30} max={200} step={5} onChange={setHourlyRate} suffix=" €/h" />
              </div>

              <div style={{ background: "#0a1428", border: "1px solid #1a2744", borderRadius: "14px", padding: "16px" }}>
                <div style={{ fontSize: "11px", fontWeight: "700", color: "#3b82f6", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "4px" }}>Contenus / client / mois</div>
                <div style={{ fontSize: "11px", color: "#334155", marginBottom: "10px" }}>CA/client : <strong style={{ color: "#94a3b8" }}>{fmt(avgRevenuePerClient)}</strong></div>
                {CONTENT_TYPES.map(ct => <Counter key={ct.id} type={ct} value={volumes[ct.id] || 0} onChange={v => updVol(ct.id, v)} on={on} />)}
              </div>

              <div style={{ background: "#0a1428", border: "1px solid #1a2744", borderRadius: "14px", padding: "16px" }}>
                <div style={{ fontSize: "11px", fontWeight: "700", color: "#f59e0b", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "4px" }}>Équipe</div>
                <div style={{ fontSize: "11px", color: "#334155", marginBottom: "10px" }}>Nombre de personnes par rôle</div>
                {ROLES.map(role => (
                  <div key={role.id} style={{ display: "flex", alignItems: "center", gap: "8px", padding: "8px 12px", background: "#060910", borderRadius: "10px", border: "1px solid #1a2744", marginBottom: "6px" }}>
                    <span style={{ fontSize: "14px" }}>{role.icon}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: "11px", color: "#94a3b8", lineHeight: 1.2 }}>{role.label}</div>
                      <div style={{ fontSize: "10px", color: "#334155" }}>{role.hoursPerWeek}h/sem</div>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
                      <button onClick={() => updTeam(role.id, Math.max(0, Math.round(((teamSizes[role.id] || 0) - 0.5) * 10) / 10))} style={{ width: "22px", height: "22px", borderRadius: "6px", background: "#1a2744", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: "13px" }}>−</button>
                      <span style={{ width: "32px", textAlign: "center", fontWeight: "700", color: role.color, fontFamily: "'IBM Plex Mono', monospace", fontSize: "13px" }}>{teamSizes[role.id] || 0}</span>
                      <button onClick={() => updTeam(role.id, Math.round(((teamSizes[role.id] || 0) + 0.5) * 10) / 10)} style={{ width: "22px", height: "22px", borderRadius: "6px", background: "#1a2744", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: "13px" }}>+</button>
                    </div>
                  </div>
                ))}
              </div>

              {mode === "saas" && (
                <div style={{ background: "#0a1428", border: "1px solid #1a2744", borderRadius: "14px", padding: "16px" }}>
                  <div style={{ fontSize: "11px", fontWeight: "700", color: "#8b5cf6", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "12px" }}>Forfaits clients SaaS</div>

                  {/* Slider : combien de clients ont souscrit */}
                  <div style={{ marginBottom: "16px", padding: "12px", background: "#060910", borderRadius: "10px", border: "1px solid #1a2744" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "6px" }}>
                      <span style={{ fontSize: "12px", color: "#64748b" }}>Clients ayant souscrit un forfait</span>
                      <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "13px", fontWeight: "700", color: "#8b5cf6" }}>{saasClients} / {contentClients}</span>
                    </div>
                    <div style={{ position: "relative", height: "4px", background: "#1a2744", borderRadius: "99px", marginBottom: "6px" }}>
                      <div style={{ position: "absolute", height: "100%", left: 0, width: `${contentClients > 0 ? (saasClients / contentClients) * 100 : 0}%`, background: "linear-gradient(90deg, #1d4ed8, #8b5cf6)", borderRadius: "99px" }} />
                      <input type="range" min={0} max={contentClients} step={1} value={saasClients}
                        onChange={e => setSaasClients(Number(e.target.value))}
                        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer", margin: 0 }} />
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "10px", color: "#334155" }}>
                      <span>{saasMemo.nNonSaas} client{saasMemo.nNonSaas !== 1 ? "s" : ""} en prestation normale</span>
                      <span style={{ color: "#8b5cf6" }}>{saasMemo.nSaas} en SaaS autonome</span>
                    </div>
                  </div>

                  <div style={{ fontSize: "11px", color: "#334155", marginBottom: "12px" }}>
                    Répartition des <strong style={{ color: "#94a3b8" }}>{saasMemo.nSaas}</strong> clients SaaS par forfait
                  </div>
                  {CLIENT_PLANS.map(p => {
                    const pct = planSplit[p.id] || 0;
                    const pc  = saasMemo.planClients.find(x => x.id === p.id);
                    const n   = pc ? pc.n : 0;
                    return (
                      <div key={p.id} style={{ background: "#060910", border: `1px solid ${p.color}33`, borderRadius: "12px", padding: "12px", marginBottom: "10px" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "8px" }}>
                          <div>
                            <div style={{ fontWeight: "700", fontSize: "13px", color: p.color }}>{p.label} · {p.price}€/m</div>
                            <div style={{ fontSize: "10px", color: "#475569", marginTop: "1px" }}>{p.desc}</div>
                          </div>
                          <div style={{ textAlign: "right" }}>
                            <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "15px", fontWeight: "800", color: p.color }}>{pct}%</div>
                            <div style={{ fontSize: "10px", color: "#475569" }}>{n} client{n > 1 ? "s" : ""}</div>
                          </div>
                        </div>
                        {/* Autonomie fixe 80% Contentz */}
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: "10px", color: "#475569", marginBottom: "4px" }}>
                          <span>Autonomie client avec Contentz</span>
                          <span style={{ color: "#10b981", fontWeight: "700" }}>80%</span>
                        </div>
                        <div style={{ height: "4px", background: "#1a2744", borderRadius: "99px", marginBottom: "10px" }}>
                          <div style={{ width: "80%", height: "100%", background: "#10b981", borderRadius: "99px" }} />
                        </div>
                        {/* Slider % clients */}
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: "10px", color: "#475569", marginBottom: "4px" }}>
                          <span>% de vos clients</span>
                          <span>{pct}%</span>
                        </div>
                        <div style={{ position: "relative", height: "4px", background: "#1a2744", borderRadius: "99px" }}>
                          <div style={{ position: "absolute", height: "100%", left: 0, width: `${pct}%`, background: `linear-gradient(90deg, #1d4ed8, ${p.color})`, borderRadius: "99px" }} />
                          <input type="range" min={0} max={100} step={5} value={pct}
                            onChange={e => updSplit(p.id, Number(e.target.value))}
                            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer", margin: 0 }} />
                        </div>
                        <div style={{ marginTop: "8px", display: "flex", gap: "4px", flexWrap: "wrap" }}>
                          {p.features.map(f => (
                            <span key={f} style={{ fontSize: "9px", padding: "1px 6px", borderRadius: "99px", background: p.color + "15", border: `1px solid ${p.color}30`, color: p.color }}>{f}</span>
                          ))}
                        </div>
                      </div>
                    );
                  })}
                  {/* Résumé répartition */}
                  <div style={{ padding: "10px 12px", background: "#060910", borderRadius: "10px", border: "1px solid #1a2744" }}>
                    <div style={{ display: "flex", height: "8px", borderRadius: "99px", overflow: "hidden", marginBottom: "8px" }}>
                      {CLIENT_PLANS.map(p => (
                        <div key={p.id} className="bar-fill" style={{ width: `${planSplit[p.id] || 0}%`, background: p.color }} />
                      ))}
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "10px" }}>
                      {CLIENT_PLANS.map(p => (
                        <div key={p.id} style={{ textAlign: "center" }}>
                          <div style={{ color: p.color, fontWeight: "700" }}>{p.label}</div>
                          <div style={{ color: "#475569" }}>{planSplit[p.id] || 0}%</div>
                        </div>
                      ))}
                      <div style={{ textAlign: "center" }}>
                        <div style={{ color: "#8b5cf6", fontWeight: "700" }}>Autonomie moy.</div>
                        <div style={{ color: "#8b5cf6" }}>80%</div>
                      </div>
                    </div>
                  </div>
                  {/* Commission TDC */}
                  <div style={{ marginTop: "10px", padding: "10px 12px", background: "#060910", borderRadius: "10px", border: "1px solid #1a2744", fontSize: "11px" }}>
                    <div style={{ color: "#334155", marginBottom: "5px" }}>Reversement sur licences & crédits</div>
                    <div style={{ display: "flex", justifyContent: "space-between" }}>
                      <span style={{ color: "#64748b" }}>Marge agence</span>
                      <span style={{ color: "#3b82f6", fontWeight: "700" }}>30%</span>
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", marginTop: "3px" }}>
                      <span style={{ color: "#64748b" }}>Commission TDC</span>
                      <span style={{ color: "#8b5cf6", fontWeight: "700" }}>20%</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* CONTENT */}
            <div>

              {/* ─── SIMULATEUR ─── */}
              {activeTab === "simulator" && (
                <>
                  {/* Synthèse globale */}
                  <div style={{ background: "linear-gradient(135deg, #0d1f3c, #13102b)", border: `1px solid ${on ? "rgba(16,185,129,0.25)" : "#1a2744"}`, borderRadius: "16px", padding: "20px", marginBottom: "16px", transition: "border-color 0.35s" }}>
                    <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "12px" }}>
                      Vue globale · {on ? "Avec Contentz" : "Sans Contentz"}
                    </div>

                    {/* Barre principale */}
                    <div style={{ marginBottom: "14px" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", color: "#475569", marginBottom: "6px" }}>
                        <span>Référence : <strong style={{ color: "#94a3b8", fontFamily: "'IBM Plex Mono',monospace" }}>{fmtH(hRef)}</strong></span>
                        <span>Actuel : <Num value={fmtH(hTot)} color={on ? "#10b981" : "#94a3b8"} size="12px" /></span>
                      </div>
                      <div style={{ height: "10px", background: "#1a2744", borderRadius: "99px", overflow: "hidden" }}>
                        <div className="bar-fill" style={{ width: `${on ? (1 - pctSav) * 100 : 100}%`, background: on ? "linear-gradient(90deg, #1d4ed8, #10b981)" : "linear-gradient(90deg, #1d4ed8, #7c3aed)", height: "100%", borderRadius: "99px" }} />
                      </div>
                      {on && <div style={{ textAlign: "right", fontSize: "12px", color: "#10b981", marginTop: "4px", fontWeight: "700" }}>{Math.round(pctSav * 100)}% libéré · {fmtH(hSaved)}/mois</div>}
                    </div>

                    {/* 3 phases */}
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px", marginBottom: "14px" }}>
                      {globalPhases.map(({ ph, meta, hB, hA, saved }) => (
                        <div key={ph} style={{ background: meta.bg, border: `1px solid ${meta.border}`, borderRadius: "12px", padding: "12px", textAlign: "center" }}>
                          <div style={{ fontSize: "11px", color: meta.color, fontWeight: "700", textTransform: "uppercase", marginBottom: "5px" }}>{meta.label}</div>
                          <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "11px", color: "#475569", marginBottom: "2px" }}>
                            {on ? <>{fmtH(hB)} → </>: ""}<Num value={fmtH(hA)} color={on ? meta.color : "#94a3b8"} size="11px" bold={false} />
                          </div>
                          <Num value={on ? `−${fmtH(saved)}` : fmtH(hA)} color={on ? meta.color : "#64748b"} size="17px" />
                          {on && <div style={{ fontSize: "11px", color: "#475569", marginTop: "2px" }}>{hB > 0 ? Math.round((saved / hB) * 100) : 0}% gagné</div>}
                        </div>
                      ))}
                    </div>

                    {/* KPIs */}
                    {mode === "agency" ? (
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: "10px" }}>
                        {[
                          { l: "Heures libérées",      v: on ? fmtH(hSaved) : "—",       c: on ? "#10b981" : "#334155" },
                          { l: "Valeur du temps",      v: on ? fmt(moneyTime) : "—",      c: on ? "#10b981" : "#334155" },
                          { l: "Bonus qualité marque", v: on ? fmt(moneyBrand) : "—",     c: on ? "#8b5cf6" : "#334155" },
                          { l: "Gain net mensuel",     v: on ? fmt(agencyNet) : "—",      c: on ? "#3b82f6" : "#334155", big: true },
                        ].map(k => (
                          <div key={k.l} style={{ background: "#060910", borderRadius: "10px", padding: "12px", textAlign: "center" }}>
                            <div style={{ fontSize: "10px", color: "#334155", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "4px" }}>{k.l}</div>
                            <Num value={k.v} color={k.c} size={k.big ? "17px" : "14px"} />
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: "10px" }}>
                        {[
                          { l: "MRR licences",           v: on ? fmt(saasMemo.totalMrr) : "—",            c: "#64748b" },
                          { l: "Marge agence/mois",      v: on ? fmt(saasMemo.agencyTotal) : "—",          c: on ? "#3b82f6" : "#334155" },
                          { l: "Temps libéré équipe",    v: on ? fmt(saasMemo.moneyTeamSaved) : "—",       c: on ? "#10b981" : "#334155" },
                          { l: "Revenu total agence/m",  v: on ? fmt(saasMemo.agencyTotal + saasMemo.moneyTeamSaved) : "—", c: on ? "#a855f7" : "#334155", big: true },
                        ].map(k => (
                          <div key={k.l} style={{ background: "#060910", borderRadius: "10px", padding: "12px", textAlign: "center" }}>
                            <div style={{ fontSize: "10px", color: "#334155", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "4px" }}>{k.l}</div>
                            <Num value={k.v} color={k.c} size={k.big ? "17px" : "14px"} />
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  {/* Accordéons */}
                  <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "10px" }}>
                    Détail par type de contenu · cliquer pour déplier
                  </div>
                  {CONTENT_TYPES.map(ct => <ContentCard key={ct.id} ct={ct} qty={volumes[ct.id] || 0} clients={contentClients} hourlyRate={hourlyRate} on={on} />)}

                  {/* Bilan Prestation */}
                  {mode === "agency" && on && (
                    <div style={{ background: "#0a1428", border: "1px solid rgba(16,185,129,0.25)", borderRadius: "14px", padding: "20px", marginTop: "14px" }}>
                      <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "12px" }}>Bilan mensuel · prestation interne</div>
                      {[
                        { l: "⏱ Économie de temps (heures × taux horaire)", v: moneyTime,   c: "#10b981", plus: true },
                        { l: "🎯 Bonus qualité — alignement marque (+12%)",  v: moneyBrand, c: "#8b5cf6", plus: true },
                        { l: "📋 Abonnement Contentz agence",                v: -SUB_COST,  c: "#ef4444", plus: false },
                      ].map(r => (
                        <div key={r.l} style={{ display: "flex", justifyContent: "space-between", padding: "10px 13px", background: "#060910", borderRadius: "10px", marginBottom: "6px" }}>
                          <span style={{ fontSize: "12px", color: "#94a3b8" }}>{r.l}</span>
                          <Num value={`${r.plus ? "+" : ""}${fmt(r.v)}`} color={r.c} size="13px" />
                        </div>
                      ))}
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 18px", marginTop: "6px", background: "linear-gradient(135deg, #1d4ed8, #7c3aed)", borderRadius: "12px", boxShadow: "0 6px 24px rgba(29,78,216,0.35)" }}>
                        <span style={{ fontSize: "14px", fontWeight: "700", color: "rgba(255,255,255,0.85)" }}>Gain net mensuel</span>
                        <div style={{ textAlign: "right" }}>
                          <Num value={fmt(agencyNet)} color="#fff" size="22px" />
                          <div style={{ fontSize: "11px", color: "rgba(255,255,255,0.5)", marginTop: "2px" }}>ROI ×{((agencyNet + SUB_COST) / SUB_COST).toFixed(1)} · payback immédiat</div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* ── BILAN SAAS COMPLET ── */}
                  {mode === "saas" && (
                    <div style={{ marginTop: "14px", display: "flex", flexDirection: "column", gap: "14px" }}>

                      {/* Répartition par forfait */}
                      <div style={{ background: "#0a1428", border: `1px solid ${on ? "rgba(139,92,246,0.3)" : "#1a2744"}`, borderRadius: "14px", padding: "20px", transition: "border-color .35s" }}>
                        <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "14px" }}>
                          🔑 Revenus licences · par forfait
                        </div>
                        {/* Barre stacked */}
                        <div style={{ marginBottom: "14px" }}>
                          <div style={{ height: "16px", borderRadius: "99px", overflow: "hidden", display: "flex" }}>
                            {CLIENT_PLANS.map(p => (
                              <div key={p.id} className="bar-fill" style={{ width: `${planSplit[p.id] || 0}%`, background: p.color, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "9px", fontWeight: "700", color: "#fff" }}>
                                {(planSplit[p.id] || 0) > 10 ? p.label : ""}
                              </div>
                            ))}
                          </div>
                        </div>
                        {/* Tableau forfaits */}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px", marginBottom: "14px" }}>
                          {saasMemo.mrrByPlan.map(p => (
                            <div key={p.id} style={{ background: "#060910", border: `1px solid ${p.color}25`, borderRadius: "12px", padding: "12px" }}>
                              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                                <span style={{ fontSize: "12px", fontWeight: "700", color: p.color }}>{p.label}</span>
                                <span style={{ fontSize: "11px", color: "#475569" }}>{p.price}€/m</span>
                              </div>
                              <div style={{ fontSize: "11px", color: "#475569", marginBottom: "4px" }}>{p.n} client{p.n > 1 ? "s" : ""} · {planSplit[p.id] || 0}%</div>
                              <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: "16px", fontWeight: "800", color: on ? p.color : "#334155" }}>
                                {on ? fmt(p.mrr) : "—"}
                              </div>
                              <div style={{ fontSize: "10px", color: "#10b981", marginTop: "4px", fontWeight: "600" }}>Autonomie : 80%</div>
                              <div style={{ height: "3px", background: "#1a2744", borderRadius: "99px", marginTop: "5px" }}>
                                <div style={{ width: "80%", height: "100%", background: "#10b981", borderRadius: "99px" }} />
                              </div>
                            </div>
                          ))}
                        </div>
                        {/* Ligne revenus licences */}
                        {[
                          { l: "💼 Marge agence · licences (30%)",   v: saasMemo.agencyLic,      c: "#3b82f6" },
                          { l: "💼 Marge agence · crédits (30%)",    v: saasMemo.agencyCredits,  c: "#3b82f6" },
                          { l: "⚡ Commission TDC · licences (20%)", v: saasMemo.tdcLicense,     c: "#8b5cf6" },
                          { l: "⚡ Commission TDC · crédits (20%)",  v: saasMemo.tdcCredits,     c: "#8b5cf6" },
                        ].map(r => (
                          <div key={r.l} style={{ display: "flex", justifyContent: "space-between", padding: "9px 13px", background: "#060910", borderRadius: "10px", marginBottom: "6px" }}>
                            <span style={{ fontSize: "12px", color: "#94a3b8" }}>{r.l}</span>
                            <Num value={on ? fmt(r.v) : "—"} color={on ? r.c : "#334155"} size="13px" />
                          </div>
                        ))}
                      </div>

                      {/* Temps libéré équipe — logique autonomie complète */}
                      <div style={{ background: "#0a1428", border: `1px solid ${on ? "rgba(16,185,129,0.3)" : "#1a2744"}`, borderRadius: "14px", padding: "20px", transition: "border-color .35s" }}>
                        <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "10px" }}>
                          ⏱ Charge libérée · clients autonomes
                        </div>
                        <div style={{ fontSize: "12px", color: "#64748b", marginBottom: "14px", lineHeight: 1.6, padding: "10px 12px", background: "#060910", borderRadius: "10px", border: "1px solid #1a2744" }}>
                          Un client avec un forfait Contentz est <strong style={{ color: "#10b981" }}>autonome</strong> : il produit lui-même ses contenus.
                          Il ne compte plus dans la charge de production de l'équipe agence.
                          Le temps libéré = la totalité du travail qui lui était consacré.
                        </div>

                        {/* Vue avant/après */}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px", marginBottom: "14px" }}>
                          {[
                            { l: "Charge totale prestation", v: fmtH(hRef),                                           c: "#64748b",  sub: `${contentClients} clients` },
                            { l: "Clients SaaS supprimés",   v: on ? `−${fmtH(saasMemo.hTeamSaved)}` : "—",           c: "#10b981",  sub: `${saasMemo.nSaas} client${saasMemo.nSaas !== 1 ? "s" : ""} autonomes` },
                            { l: "Charge agence restante",   v: on ? fmtH(saasMemo.hTotalSaasMode) : fmtH(hRef),      c: on ? "#10b981" : "#94a3b8", sub: `${saasMemo.nNonSaas} clients prestation` },
                          ].map(k => (
                            <div key={k.l} style={{ background: "#060910", borderRadius: "10px", padding: "12px", textAlign: "center" }}>
                              <div style={{ fontSize: "10px", color: "#334155", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "5px" }}>{k.l}</div>
                              <Num value={k.v} color={k.c} size="16px" />
                              <div style={{ fontSize: "10px", color: "#475569", marginTop: "3px" }}>{k.sub}</div>
                            </div>
                          ))}
                        </div>

                        {/* Barre de charge */}
                        <div style={{ marginBottom: "12px" }}>
                          <div style={{ display: "flex", justifyContent: "space-between", fontSize: "11px", color: "#475569", marginBottom: "5px" }}>
                            <span>Charge de référence : <strong style={{ color: "#94a3b8" }}>{fmtH(hRef)}</strong> ({contentClients} clients)</span>
                            {on && <span style={{ color: "#10b981" }}>−{fmtH(saasMemo.hTeamSaved)} supprimées</span>}
                          </div>
                          <div style={{ height: "12px", background: "#1a2744", borderRadius: "99px", overflow: "hidden", display: "flex" }}>
                            <div className="bar-fill" style={{
                              width: on && hRef > 0 ? `${(saasMemo.hTotalSaasMode / hRef) * 100}%` : "100%",
                              background: "linear-gradient(90deg, #1d4ed8, #7c3aed)", borderRadius: "99px",
                              display: "flex", alignItems: "center", justifyContent: "center",
                              fontSize: "9px", fontWeight: "700", color: "#fff"
                            }}>
                              {on && saasMemo.nNonSaas > 0 ? `${saasMemo.nNonSaas} prestation` : ""}
                            </div>
                            {on && saasMemo.nSaas > 0 && (
                              <div style={{ flex: 1, background: "rgba(16,185,129,0.25)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "9px", color: "#10b981", fontWeight: "700", borderLeft: "1px dashed rgba(16,185,129,0.4)" }}>
                                {saasMemo.nSaas} SaaS ✓
                              </div>
                            )}
                          </div>
                          {on && (
                            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "10px", marginTop: "4px" }}>
                              <span style={{ color: "#64748b" }}>Charge agence : {fmtH(saasMemo.hTotalSaasMode)}</span>
                              <span style={{ color: "#10b981" }}>Libéré : {fmtH(saasMemo.hTeamSaved)} ({hRef > 0 ? Math.round((saasMemo.hTeamSaved/hRef)*100) : 0}%)</span>
                            </div>
                          )}
                        </div>

                        {/* Détail par client SaaS */}
                        <div style={{ padding: "12px 14px", background: "rgba(16,185,129,0.06)", border: "1px solid rgba(16,185,129,0.15)", borderRadius: "10px", marginBottom: "10px" }}>
                          <div style={{ fontSize: "11px", color: "#10b981", fontWeight: "700", marginBottom: "8px" }}>Décomposition · charge agence en mode SaaS</div>
                          {[
                            { l: `${saasMemo.nNonSaas} client${saasMemo.nNonSaas !== 1 ? "s" : ""} en prestation normale`, v: fmtH(saasMemo.hRefNonSaas), c: "#64748b" },
                            { l: `${saasMemo.nSaas} client${saasMemo.nSaas !== 1 ? "s" : ""} SaaS autonomes (charge supprimée)`, v: on ? `−${fmtH(saasMemo.hTeamSaved)}` : fmtH(saasMemo.hRefSaas), c: on ? "#10b981" : "#475569" },
                          ].map(r => (
                            <div key={r.l} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: "12px", marginBottom: "6px" }}>
                              <span style={{ color: "#94a3b8" }}>{r.l}</span>
                              <Num value={r.v} color={r.c} size="12px" />
                            </div>
                          ))}
                          <div style={{ borderTop: "1px solid rgba(16,185,129,0.15)", marginTop: "8px", paddingTop: "8px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                            <span style={{ fontSize: "12px", fontWeight: "700", color: "#e2e8f0" }}>Charge totale agence / mois</span>
                            <div style={{ textAlign: "right" }}>
                              {on && <div style={{ fontSize: "10px", color: "#475569", textDecoration: "line-through", fontFamily: "'IBM Plex Mono', monospace" }}>{fmtH(hRef)}</div>}
                              <Num value={on ? fmtH(saasMemo.hTotalSaasMode) : fmtH(hRef)} color={on ? "#10b981" : "#94a3b8"} size="15px" />
                            </div>
                          </div>
                          {on && <div style={{ fontSize: "11px", color: "#10b981", marginTop: "5px", textAlign: "right", fontWeight: "600" }}>−{fmtH(saasMemo.hSavedSaasMode)} vs mode prestation pure</div>}
                        </div>

                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 16px", background: "rgba(16,185,129,0.08)", border: "1px solid rgba(16,185,129,0.2)", borderRadius: "10px" }}>
                          <div>
                            <div style={{ fontSize: "13px", color: "#94a3b8" }}>💰 Valeur du temps libéré équipe</div>
                            <div style={{ fontSize: "10px", color: "#475569", marginTop: "2px" }}>À {hourlyRate}€/h · {on ? fmtH(saasMemo.hTeamSaved) : "—"} libérées</div>
                          </div>
                          <Num value={on ? fmt(saasMemo.moneyTeamSaved) : "—"} color={on ? "#10b981" : "#334155"} size="17px" />
                        </div>
                      </div>

                      {/* Synthèse finale SaaS */}
                      <div style={{ background: "#0a1428", border: `1px solid ${on ? "rgba(168,85,247,0.3)" : "#1a2744"}`, borderRadius: "14px", padding: "20px", transition: "border-color .35s" }}>
                        <div style={{ fontSize: "11px", fontWeight: "700", color: "#334155", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "14px" }}>
                          📊 Synthèse mensuelle · Mode SaaS
                        </div>
                        {[
                          { l: "💼 Marge licences agence (30%)",          v: saasMemo.agencyLic,       c: "#3b82f6", plus: true },
                          { l: "💳 Marge crédits agence (30%)",           v: saasMemo.agencyCredits,   c: "#3b82f6", plus: true },
                          { l: "⏱ Charge libérée · clients autonomes", v: saasMemo.moneyTeamSaved,  c: "#10b981", plus: true },
                          { l: "⚡ Commission TDC (licences + crédits)",   v: -(saasMemo.tdcTotal),     c: "#8b5cf6", plus: false },
                        ].map(r => (
                          <div key={r.l} style={{ display: "flex", justifyContent: "space-between", padding: "10px 13px", background: "#060910", borderRadius: "10px", marginBottom: "6px" }}>
                            <span style={{ fontSize: "12px", color: "#94a3b8" }}>{r.l}</span>
                            <Num value={on ? `${r.plus ? "+" : ""}${fmt(r.v)}` : "—"} color={on ? r.c : "#334155"} size="13px" />
                          </div>
                        ))}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px", marginTop: "10px" }}>
                          <div style={{ background: "linear-gradient(135deg, #1d4ed8, #7c3aed)", borderRadius: "12px", padding: "14px", textAlign: "center", boxShadow: "0 6px 24px rgba(29,78,216,0.3)" }}>
                            <div style={{ fontSize: "10px", color: "rgba(255,255,255,0.65)", textTransform: "uppercase", marginBottom: "4px" }}>Revenu total agence / mois</div>
                            <Num value={on ? fmt(saasMemo.agencyTotal + saasMemo.moneyTeamSaved) : "—"} color="#fff" size="20px" />
                            <div style={{ fontSize: "10px", color: "rgba(255,255,255,0.5)", marginTop: "4px" }}>Licences + crédits + temps libéré</div>
                          </div>
                          <div style={{ background: "#060910", border: "1px solid rgba(168,85,247,0.2)", borderRadius: "12px", padding: "14px", textAlign: "center" }}>
                            <div style={{ fontSize: "10px", color: "#8b5cf6", textTransform: "uppercase", marginBottom: "4px" }}>Commission TDC / mois</div>
                            <Num value={on ? fmt(saasMemo.tdcTotal) : "—"} color={on ? "#a855f7" : "#334155"} size="20px" />
                            <div style={{ fontSize: "10px", color: "#475569", marginTop: "4px" }}>{on ? fmt(saasMemo.tdcTotal * 12) + " / an" : "—"}</div>
                          </div>
                        </div>
                        {on && (
                          <div style={{ marginTop: "12px", padding: "14px 16px", background: "rgba(99,102,241,0.06)", border: "1px solid rgba(99,102,241,0.18)", borderRadius: "12px", fontSize: "13px", color: "#e2e8f0", lineHeight: 1.6 }}>
                            💡 <strong style={{ color: "#a855f7" }}>Le modèle SaaS génère deux types de valeur :</strong>{" "}
                            <strong style={{ color: "#3b82f6" }}>{fmt(saasMemo.agencyTotal)}/mois</strong> de revenus récurrents sur les licences et crédits,
                            plus <strong style={{ color: "#10b981" }}>{fmt(saasMemo.moneyTeamSaved)}/mois</strong> de charge équipe supprimée —
                            les <strong style={{ color: "#94a3b8" }}>{saasMemo.nSaas} client{saasMemo.nSaas !== 1 ? "s" : ""} SaaS</strong> sont autonomes avec Contentz
                            et ne comptent plus dans la production de l'équipe.
                            Soit <strong style={{ color: "#a855f7" }}>{fmt((saasMemo.agencyTotal + saasMemo.moneyTeamSaved) * 12)}/an</strong> de valeur totale créée.
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </>
              )}

              {/* ─── ÉQUIPE ─── */}
              {activeTab === "team" && (
                <TeamCapacity
                  teamSizes={teamSizes}
                  volumes={volumes}
                  clients={contentClients}
                  hourlyRate={hourlyRate}
                  avgRevenuePerClient={avgRevenuePerClient}
                  on={on}
                />
              )}
            </div>
          </div>

          <div style={{ textAlign: "center", marginTop: "24px", fontSize: "11px", color: "#1a2744" }}>
            Simulation indicative · valeurs moyennes constatées · Contentz by TDC · {new Date().getFullYear()}
          </div>
        </div>
      </div>
    </>
  );
}
