/* ------------------------------------------------------------------ *
 *  Mode Expert — Analyse financière détaillée
 *
 *  Formules (fidèles Excel) :
 *  - tempsManuel = imbrication + polissage  (★ seuls comptés)
 *  - coutMO      = tempsManuel × tauxMOparMin
 *  - coutResine  = (prixFlacon / mlFlacon) × (mlImprimer + perteMl)
 *  - coutCuve    = (prixCuve / mlCuve) × (mlImprimer + perteMl)
 *  - coutTotal   = coutMat + cloudDesign + coutMO
 *  - economieU   = coutLabo − coutTotal
 *
 *  casMois et coutLabo sont stockés dans expertRowParams → indépendants
 *  du mode simple.
 * ------------------------------------------------------------------ */

const EXPERT_DEFAULTS = {
  global: {
    tauxMOparMin:  1,
    salaire35h:    0,       // si > 0, écrase tauxMOparMin à la saisie
    prixCuve:      350,
    mlCuve:        15000,
    investissement: 26790,
    dureeAmort:    36,
  },
  rows: {
    /* casMois + coutLabo = valeurs catalogue (indépendantes du mode simple) */
    'midas-couronne-unitaire': { prixFlacon:20,  grParFlacon:1,    mlFlacon:1,   mlImprimer:0,  perteMl:0, tempsCapsule:8,  tempsImbrication:2, tempsLavage:2,  tempsPolymeri:10,   tempsPolissage:10, cloudDesign:0,   casMois:8,  coutLabo:130 },
    'midas-couronne-implant':  { prixFlacon:20,  grParFlacon:1,    mlFlacon:1,   mlImprimer:0,  perteMl:0, tempsCapsule:8,  tempsImbrication:2, tempsLavage:2,  tempsPolymeri:10,   tempsPolissage:10, cloudDesign:0,   casMois:4,  coutLabo:220 },
    'midas-inlay-onlay':       { prixFlacon:20,  grParFlacon:1,    mlFlacon:1,   mlImprimer:0,  perteMl:0, tempsCapsule:8,  tempsImbrication:2, tempsLavage:2,  tempsPolymeri:10,   tempsPolissage:10, cloudDesign:0,   casMois:5,  coutLabo:120 },
    'midas-overlay':           { prixFlacon:20,  grParFlacon:1,    mlFlacon:1,   mlImprimer:0,  perteMl:0, tempsCapsule:8,  tempsImbrication:2, tempsLavage:2,  tempsPolymeri:10,   tempsPolissage:10, cloudDesign:0,   casMois:3,  coutLabo:140 },
    'midas-facette':           { prixFlacon:20,  grParFlacon:1,    mlFlacon:1,   mlImprimer:0,  perteMl:0, tempsCapsule:8,  tempsImbrication:2, tempsLavage:2,  tempsPolymeri:10,   tempsPolissage:10, cloudDesign:0,   casMois:2,  coutLabo:200 },
    'pro2-night-guard':        { prixFlacon:450, grParFlacon:1000, mlFlacon:909, mlImprimer:7,  perteMl:2, tempsCuveStd:53, tempsArchKit:39, tempsImbrication:5, tempsLavage:9, tempsPolymeri:6.51, tempsPolissage:10, cloudDesign:29,  casMois:4,  coutLabo:90  },
    'pro2-couronne-unitaire':  { prixFlacon:550, grParFlacon:1000, mlFlacon:800, mlImprimer:15, perteMl:2, tempsCuveStd:25, tempsArchKit:18, tempsImbrication:5, tempsLavage:2, tempsPolymeri:3,    tempsPolissage:10, cloudDesign:11,  casMois:6,  coutLabo:50  },
    'pro2-couronne-implant':   { prixFlacon:749, grParFlacon:500,  mlFlacon:344, mlImprimer:9,  perteMl:4, tempsCuveStd:37, tempsArchKit:30, tempsImbrication:5, tempsLavage:2, tempsPolymeri:5.21, tempsPolissage:10, cloudDesign:0,   casMois:3,  coutLabo:120 },
    'pro2-guide-chirurgical':  { prixFlacon:349, grParFlacon:1000, mlFlacon:909, mlImprimer:12, perteMl:2, tempsCuveStd:43, tempsArchKit:34, tempsImbrication:5, tempsLavage:9, tempsPolymeri:2.09, tempsPolissage:5,  cloudDesign:89,  casMois:6,  coutLabo:160 },
    'pro2-amovible-complet':   { prixFlacon:679, grParFlacon:1000, mlFlacon:769, mlImprimer:28, perteMl:5, tempsCuveStd:85, tempsArchKit:65, tempsImbrication:5, tempsLavage:9, tempsPolymeri:10,   tempsPolissage:20, cloudDesign:60,  casMois:1,  coutLabo:425 },
    'pro2-amovible-flexible':  { prixFlacon:429, grParFlacon:500,  mlFlacon:476, mlImprimer:28, perteMl:5, tempsCuveStd:87, tempsArchKit:67, tempsImbrication:5, tempsLavage:9, tempsPolymeri:15,   tempsPolissage:20, cloudDesign:55,  casMois:1,  coutLabo:380 },
    'pro2-allonx':             { prixFlacon:749, grParFlacon:500,  mlFlacon:344, mlImprimer:9,  perteMl:4, tempsCuveStd:37, tempsArchKit:30, tempsImbrication:5, tempsLavage:2, tempsPolymeri:5.21, tempsPolissage:25, cloudDesign:250, casMois:1,  coutLabo:900 },
    'pro2-modeles':            { prixFlacon:149, grParFlacon:1000, mlFlacon:909, mlImprimer:12, perteMl:2, tempsCuveStd:25, tempsArchKit:21, tempsImbrication:5, tempsLavage:9, tempsPolymeri:1.17, tempsPolissage:3,  cloudDesign:0,   casMois:15, coutLabo:18  },
    'pro2-retainer':           { prixFlacon:479, grParFlacon:500,  mlFlacon:476, mlImprimer:3,  perteMl:2, tempsCuveStd:48, tempsArchKit:39, tempsImbrication:5, tempsLavage:9, tempsPolymeri:22,   tempsPolissage:10, cloudDesign:9,   casMois:8,  coutLabo:60  },
    'pro2-inlay-onlay':        { prixFlacon:390, grParFlacon:250,  mlFlacon:151, mlImprimer:1,  perteMl:3, tempsCuveStd:22, tempsArchKit:15, tempsImbrication:5, tempsLavage:2, tempsPolymeri:3.11, tempsPolissage:10, cloudDesign:11,  casMois:4,  coutLabo:45  },
    'pro2-facette':            { prixFlacon:390, grParFlacon:250,  mlFlacon:151, mlImprimer:1,  perteMl:3, tempsCuveStd:22, tempsArchKit:15, tempsImbrication:5, tempsLavage:2, tempsPolymeri:3.11, tempsPolissage:10, cloudDesign:20,  casMois:2,  coutLabo:60  },
  },
};

/* Calcule les composantes de coût pour une indication */
function expertComposantes(row, gp, ep) {
  ep = ep || {};
  const tauxMin     = gp.tauxMOparMin || 1;
  const tempsManuel = (ep.tempsImbrication || 0) + (ep.tempsPolissage || 0);
  const coutMO      = tempsManuel * tauxMin;
  const coutDesign  = ep.cloudDesign || 0;

  if (row.machine === 'midas') {
    const coutPellet = ep.prixFlacon || 0;
    return { mlTotal:0, prixParMl:0, coutResine:0, coutCuve:0, coutPellet, coutMat:coutPellet, coutMO, coutDesign, coutTotal:coutPellet+coutMO+coutDesign, tempsManuel };
  }

  const mlTotal    = (ep.mlImprimer || 0) + (ep.perteMl || 0);
  const prixParMl  = (ep.prixFlacon || 0) / Math.max(1, ep.mlFlacon || 1);
  const coutResine = prixParMl * mlTotal;
  const coutCuve   = ((gp.prixCuve || 350) / Math.max(1, gp.mlCuve || 15000)) * mlTotal;
  const coutMat    = coutResine + coutCuve;
  return { mlTotal, prixParMl, coutResine, coutCuve, coutPellet:0, coutMat, coutMO, coutDesign, coutTotal:coutMat+coutDesign+coutMO, tempsManuel };
}

/* Calcule une ligne complète — utilise casMois/coutLabo depuis expertRowParams */
function calculerLigneExpert(row, gp, allRowParams) {
  const ep       = allRowParams[row.id] || EXPERT_DEFAULTS.rows[row.id] || {};
  const c        = expertComposantes(row, gp, ep);
  const coutLabo = ep.coutLabo ?? 0;
  const volume   = ep.casMois  ?? 0;
  const economieUnit = coutLabo - c.coutTotal;
  const margeUnit    = (row.values.honoraire || 0) - c.coutTotal;
  return {
    ...c, economieUnit, margeUnit,
    economieMois: economieUnit * volume,
    economieAn:   economieUnit * volume * 12,
    margeMois:    margeUnit * volume,
    margeAn:      margeUnit * volume * 12,
    caMois:       (row.values.honoraire || 0) * volume,
    caAn:         (row.values.honoraire || 0) * volume * 12,
    coutLaboMois: coutLabo * volume,
    coutLaboAn:   coutLabo * volume * 12,
    coutInterneMois: c.coutTotal * volume,
    coutInterneAn:   c.coutTotal * volume * 12,
  };
}

function calculerTotauxExpert(rows, gp, allRowParams) {
  const effectiveGp = (gp.salaire35h > 0)
    ? { ...gp, tauxMOparMin: gp.salaire35h / (35 * 52 / 12 * 60) }
    : gp;
  let economieMois = 0, economieAn = 0, margeAn = 0, caAn = 0, coutLaboAn = 0, coutInterneAn = 0;
  rows.forEach(r => {
    if (!r.actif) return;
    const c = calculerLigneExpert(r, effectiveGp, allRowParams);
    economieMois  += c.economieMois;
    economieAn    += c.economieAn;
    margeAn       += c.margeAn;
    caAn          += c.caAn;
    coutLaboAn    += c.coutLaboAn;
    coutInterneAn += c.coutInterneAn;
  });
  return { economieMois, economieAn, margeAn, caAn, coutLaboAn, coutInterneAn };
}

/* ================================================================== *
 *  ExpertPage — overlay plein écran, style cohérent avec le mode simple
 * ================================================================== */
function ExpertPage({ rows, setRows, expertGlobal, setExpertGlobal, expertRowParams, setExpertRowParams, onClose }) {
  const { NumberInput, Icon, Wordmark, LangPicker } = window;
  const { t, fmt } = useLang();

  function patchRow(id, delta) {
    setExpertRowParams(p => ({ ...p, [id]: { ...(EXPERT_DEFAULTS.rows[id] || {}), ...(p[id] || {}), ...delta } }));
  }
  function patchGlobal(delta) { setExpertGlobal(p => ({ ...p, ...delta })); }
  function handleSalaire(v) {
    const s = Math.max(0, v);
    const update = { salaire35h: s };
    if (s > 0) update.tauxMOparMin = +(s / (35 * 52 / 12 * 60)).toFixed(4);
    patchGlobal(update);
  }

  /* Taux effectif (salaire prime sur taux/min si renseigné) */
  const tauxMin = expertGlobal.salaire35h > 0
    ? expertGlobal.salaire35h / (35 * 52 / 12 * 60)
    : expertGlobal.tauxMOparMin;

  const effectiveGp = { ...expertGlobal, tauxMOparMin: tauxMin };

  const activeRows   = rows.filter(r => r.actif);
  const totalCasMois = activeRows.reduce((s, r) => {
    const ep = expertRowParams[r.id] || EXPERT_DEFAULTS.rows[r.id] || {};
    return s + (ep.casMois || 0);
  }, 0);
  const amortMensuel = expertGlobal.investissement / Math.max(1, expertGlobal.dureeAmort);
  const amortParCas  = totalCasMois > 0 ? amortMensuel / totalCasMois : 0;

  /* Calcul de toutes les lignes actives */
  const lignes = activeRows.map(r => {
    const ep         = { ...(EXPERT_DEFAULTS.rows[r.id] || {}), ...(expertRowParams[r.id] || {}) };
    const c          = expertComposantes(r, effectiveGp, ep);
    const casMois    = ep.casMois ?? 0;
    const coutLabo   = ep.coutLabo ?? 0;
    const economieUnit  = coutLabo - c.coutTotal;
    const economieMois  = economieUnit * casMois;
    const amortAttribue = amortParCas * casMois;
    const econNette     = economieMois - amortAttribue;
    return { r, ep, c, casMois, coutLabo, economieUnit, economieMois, amortAttribue, econNette };
  });

  const totalEcoMois  = lignes.reduce((s, l) => s + l.economieMois, 0);
  const totalEcoNette = totalEcoMois - amortMensuel;
  const moisROI       = totalEcoMois > 0 ? Math.ceil(expertGlobal.investissement / totalEcoMois) : null;

  /* Helpers de style */
  const th  = 'px-2 py-1.5 text-[10px] font-semibold text-center whitespace-nowrap';
  const td  = 'px-2 py-2 text-[11px] text-center whitespace-nowrap border-b border-slate-100';
  const tdR = td + ' text-right tnum';
  const W   = 'w-[58px]'; /* largeur NumberInput compact */

  return (
    <div className="fixed inset-0 z-50 flex flex-col bg-ink-50">

      {/* ── Header (même style que l'app) ── */}
      <header className="bg-white/95 backdrop-blur border-b border-ink-100 shrink-0 sticky top-0 z-30">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6 py-3 flex items-center gap-3">
          <Wordmark/>
          <div className="h-4 w-px bg-ink-200 mx-1"/>
          <span className="inline-flex items-center gap-1.5 bg-violet-100 text-violet-700 text-[11.5px] font-semibold px-2.5 py-1 rounded-lg">
            <Icon.spark/> {t('expert2.badge')}
          </span>
          <div className="flex-1"/>
          <LangPicker/>
          <button onClick={onClose}
                  className="inline-flex items-center gap-1.5 text-[12.5px] font-semibold px-3 py-2 rounded-lg border shadow-card bg-ink-900 text-white hover:bg-ink-800 border-ink-900 transition">
            <Icon.close/> {t('expert2.close')}
          </button>
        </div>
      </header>

      {/* ── Contenu scrollable ── */}
      <div className="flex-1 overflow-y-auto">

        {/* ─────────────────────────────────────────────
            Section 1 — Paramètres du cabinet
        ───────────────────────────────────────────── */}
        <section className="max-w-[1400px] mx-auto px-6 pt-8 pb-5">
          <div className="bg-white border border-ink-200 rounded-2xl shadow-card p-5">
            <div className="flex items-start gap-3 mb-5">
              <div className="w-7 h-7 rounded-lg bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold shrink-0">1</div>
              <div>
                <h2 className="text-[14.5px] font-semibold text-ink-900">{t('expert2.s1.title')}</h2>
                <p className="text-[12.5px] text-ink-500">{t('expert2.s1.sub')}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
              {/* MO/min */}
              <div className="bg-amber-50 border border-amber-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-amber-700 font-semibold mb-2">{t('expert2.s1.mo')}</div>
                <NumberInput value={expertGlobal.tauxMOparMin}
                             onChange={v => patchGlobal({ tauxMOparMin: Math.max(0.01, v), salaire35h: 0 })}
                             suffix="€" step={0.05}/>
                <div className="text-[10px] text-amber-600 mt-1.5 tnum">{t('expert2.s1.mo.hint', fmt.EUR(expertGlobal.tauxMOparMin * 60))}</div>
              </div>

              {/* Salaire 35h */}
              <div className="bg-amber-50 border border-amber-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-amber-700 font-semibold mb-2">{t('expert2.s1.salaire')}</div>
                <NumberInput value={expertGlobal.salaire35h}
                             onChange={handleSalaire}
                             suffix="€/an" step={500}/>
                <div className="text-[10px] text-amber-600 mt-1.5">
                  {expertGlobal.salaire35h > 0
                    ? <span className="tnum">{t('expert2.s1.salaire.hint', fmt.EUR2(tauxMin))}</span>
                    : <span className="text-ink-400">{t('expert2.s1.salaire.zero')}</span>}
                </div>
              </div>

              {/* Prix cuve */}
              <div className="bg-slate-50 border border-slate-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-slate-600 font-semibold mb-2">{t('expert2.s1.prixCuve')}</div>
                <NumberInput value={expertGlobal.prixCuve}
                             onChange={v => patchGlobal({ prixCuve: Math.max(0, v) })}
                             suffix="€" step={10}/>
                <div className="text-[10px] text-slate-500 mt-1.5">{t('expert2.s1.prixCuve.hint')}</div>
              </div>

              {/* ml/cuve */}
              <div className="bg-slate-50 border border-slate-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-slate-600 font-semibold mb-2">{t('expert2.s1.mlCuve')}</div>
                <NumberInput value={expertGlobal.mlCuve}
                             onChange={v => patchGlobal({ mlCuve: Math.max(1, v) })}
                             suffix="ml" step={100}/>
                <div className="text-[10px] text-slate-500 mt-1.5 tnum">{t('expert2.s1.mlCuve.hint', fmt.EUR2(expertGlobal.prixCuve / Math.max(1, expertGlobal.mlCuve)))}</div>
              </div>

              {/* Investissement */}
              <div className="bg-ink-50 border border-ink-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-ink-600 font-semibold mb-2">{t('expert2.s1.invest')}</div>
                <NumberInput value={expertGlobal.investissement}
                             onChange={v => patchGlobal({ investissement: Math.max(0, v) })}
                             suffix="€" step={100}/>
                <div className="text-[10px] text-ink-500 mt-1.5">{t('expert2.s1.invest.hint')}</div>
              </div>

              {/* Durée amort */}
              <div className="bg-ink-50 border border-ink-200 rounded-xl p-3.5">
                <div className="text-[10px] uppercase tracking-wider text-ink-600 font-semibold mb-2">{t('expert2.s1.amort')}</div>
                <NumberInput value={expertGlobal.dureeAmort}
                             onChange={v => patchGlobal({ dureeAmort: Math.max(1, v) })}
                             suffix={t('synth.gen.fin.mois')} step={6}/>
                <div className="text-[10px] text-ink-500 mt-1.5 tnum">{t('expert2.s1.amort.hint', fmt.EUR(amortMensuel))}</div>
              </div>
            </div>
          </div>
        </section>

        {/* ─────────────────────────────────────────────
            Section 2 — Tableau d'analyse par indication
        ───────────────────────────────────────────── */}
        <section className="max-w-[1400px] mx-auto px-6 pb-5">
          <div className="bg-white border border-ink-200 rounded-2xl shadow-card overflow-hidden">

            {/* En-tête de section */}
            <div className="px-5 py-4 border-b border-ink-100 flex items-start gap-3">
              <div className="w-7 h-7 rounded-lg bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold shrink-0 mt-0.5">2</div>
              <div className="flex-1 min-w-0">
                <h2 className="text-[14.5px] font-semibold text-ink-900">{t('expert2.s2.title')}</h2>
                <p className="text-[12.5px] text-ink-500">{t('expert2.s2.sub.before')}<strong className="text-ink-600">{t('expert2.s2.sub.strong')}</strong>{t('expert2.s2.sub.after')}</p>
              </div>
              <div className="flex items-center gap-3 text-[10px] shrink-0 pt-0.5">
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-amber-300 inline-block"/><span className="text-ink-500">{t('expert2.s2.legend.manual')}</span></span>
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-blue-200 inline-block"/><span className="text-ink-500">{t('expert2.s2.legend.auto')}</span></span>
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-violet-200 inline-block"/><span className="text-ink-500">{t('expert2.s2.legend.calc')}</span></span>
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-emerald-200 inline-block"/><span className="text-ink-500">{t('expert2.s2.legend.roi')}</span></span>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="text-[11px] border-collapse" style={{minWidth:'1900px'}}>
                <thead>

                  {/* Groupe headers */}
                  <tr className="text-[9px] font-bold uppercase tracking-wider">
                    <th colSpan={2} className={`${th} bg-ink-100 text-ink-700 text-left pl-3 border-b border-ink-200`} style={{position:'sticky',left:0,zIndex:3}}>{t('expert2.col.indication')}</th>
                    <th colSpan={7} className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>{t('expert2.col.material')}</th>
                    <th colSpan={5} className={`${th} bg-blue-100 text-blue-700 border-b border-blue-200`}>{t('expert2.col.auto')}</th>
                    <th colSpan={4} className={`${th} bg-amber-100 text-amber-700 border-b border-amber-300`}>{t('expert2.col.manual')}</th>
                    <th colSpan={4} className={`${th} bg-violet-100 text-violet-700 border-b border-violet-200`}>{t('expert2.col.costs')}</th>
                    <th colSpan={6} className={`${th} bg-emerald-100 text-emerald-700 border-b border-emerald-200`}>{t('expert2.col.roi')}</th>
                  </tr>

                  {/* Colonne headers */}
                  <tr className="text-[9.5px]">
                    <th className={`${th} w-8 bg-ink-100 border-b border-ink-200`} style={{position:'sticky',left:0,zIndex:3}}/>
                    <th className={`${th} text-left pl-3 bg-ink-100 text-ink-700 w-[165px] border-b border-ink-200`} style={{position:'sticky',left:'32px',zIndex:3}}>{t('expert2.col.indication')}</th>

                    {/* Matériau */}
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>{t('expert2.col.prixFlacon')}</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>gr/flacon</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>ml/flacon</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>{t('expert2.col.mlImprimer')}</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>{t('expert2.col.perteMl')}</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>{t('expert2.col.mlTotal')}</th>
                    <th className={`${th} bg-slate-100 text-slate-600 border-b border-slate-200`}>€/ml</th>

                    {/* Auto — hors MO */}
                    <th className={`${th} bg-blue-50 text-blue-600 border-b border-blue-100`}>{t('expert2.col.cuveStd')}</th>
                    <th className={`${th} bg-blue-50 text-blue-600 border-b border-blue-100`}>{t('expert2.col.archKit')}</th>
                    <th className={`${th} bg-blue-50 text-blue-600 border-b border-blue-100`}>{t('expert2.col.capsule')}</th>
                    <th className={`${th} bg-blue-50 text-blue-600 border-b border-blue-100`}>{t('expert2.col.lavage')}</th>
                    <th className={`${th} bg-blue-50 text-blue-600 border-b border-blue-100`}>{t('expert2.col.polymeri')}</th>

                    {/* Manuels — comptés MO */}
                    <th className={`${th} bg-amber-100 text-amber-700 border-b border-amber-200`}>{t('expert2.col.imbric')}</th>
                    <th className={`${th} bg-amber-100 text-amber-700 border-b border-amber-200`}>{t('expert2.col.polissage')}</th>
                    <th className={`${th} bg-amber-200 text-amber-800 border-b border-amber-300 font-bold`}>{t('expert2.col.totalManuel')}</th>
                    <th className={`${th} bg-amber-200 text-amber-800 border-b border-amber-300 font-bold`}>{t('expert2.col.coutMO')}</th>

                    {/* Coûts */}
                    <th className={`${th} bg-violet-50 text-violet-600 border-b border-violet-100`}>{t('expert2.col.coutResine')}</th>
                    <th className={`${th} bg-violet-50 text-violet-600 border-b border-violet-100`}>{t('expert2.col.coutCuve')}</th>
                    <th className={`${th} bg-violet-50 text-violet-600 border-b border-violet-100`}>{t('expert2.col.cloudDesign')}</th>
                    <th className={`${th} bg-violet-100 text-violet-800 border-b border-violet-200 font-bold`}>{t('expert2.col.totalInterne')}</th>

                    {/* ROI indépendant */}
                    <th className={`${th} bg-emerald-50 text-emerald-700 border-b border-emerald-100`}>{t('expert2.col.coutLabo')}</th>
                    <th className={`${th} bg-emerald-100 text-emerald-800 border-b border-emerald-200`}>{t('expert2.col.ecocas')}</th>
                    <th className={`${th} bg-emerald-50 text-emerald-700 border-b border-emerald-100`}>{t('expert2.col.casMois')}</th>
                    <th className={`${th} bg-emerald-100 text-emerald-800 border-b border-emerald-200`}>{t('expert2.col.ecomois')}</th>
                    <th className={`${th} bg-emerald-50 text-emerald-700 border-b border-emerald-100`}>{t('expert2.col.amort')}</th>
                    <th className={`${th} bg-emerald-200 text-emerald-900 border-b border-emerald-300 font-bold`}>{t('expert2.col.econette')}</th>
                  </tr>
                </thead>

                <tbody>
                  {['midas', 'pro2'].map(machine => {
                    const machRows = rows.filter(r => r.actif && r.machine === machine);
                    if (!machRows.length) return null;
                    return (
                      <React.Fragment key={machine}>
                        <tr className="bg-gradient-to-r from-brand-50 to-white">
                          <td colSpan={28} className="px-4 py-2">
                            <div className="text-[10px] uppercase tracking-[0.12em] font-semibold text-brand-700 flex items-center gap-1.5">
                              <Icon.printer/> SprintRay {machine === 'midas' ? 'Midas' : 'Pro 2'}
                            </div>
                          </td>
                        </tr>

                        {machRows.map(r => {
                          const lig = lignes.find(l => l.r.id === r.id);
                          if (!lig) return null;
                          const { ep, c, casMois, coutLabo, economieUnit, economieMois, amortAttribue, econNette } = lig;
                          const isMidas = r.machine === 'midas';

                          return (
                            <tr key={r.id} className="hover:bg-ink-50/30 transition-colors border-b border-slate-100">

                              {/* Toggle */}
                              <td className="px-2 py-1.5 bg-white" style={{position:'sticky',left:0,zIndex:2}}>
                                <button onClick={() => setRows(rs => rs.map(x => x.id === r.id ? { ...x, actif: !x.actif } : x))}
                                        className="w-5 h-5 rounded grid place-items-center border border-brand-500 bg-brand-500 text-white">
                                  <Icon.check/>
                                </button>
                              </td>

                              {/* Indication */}
                              <td className="px-3 py-1.5 bg-white text-left" style={{position:'sticky',left:'32px',zIndex:2}}>
                                <div className="font-medium text-ink-900 leading-tight text-[11px]">{t('cat.' + r.id + '.label')}</div>
                                <span className={`text-[9px] mt-0.5 font-medium px-1.5 py-0.5 rounded-full inline-block ${isMidas ? 'bg-violet-100 text-violet-600' : 'bg-brand-50 text-brand-600'}`}>
                                  {isMidas ? 'Midas' : 'Pro 2'}
                                </span>
                              </td>

                              {/* ── Matériau ── */}
                              <td className="bg-slate-50 px-2 py-1.5">
                                <NumberInput value={ep.prixFlacon ?? 0} onChange={v => patchRow(r.id, { prixFlacon: Math.max(0, v) })} suffix="€" step={1} className={W}/>
                                {isMidas && <div className="text-[9px] text-center text-slate-400 mt-0.5">{t('expert2.cell.pellet')}</div>}
                              </td>
                              <td className="bg-slate-50 px-2 py-1.5 text-center">
                                {!isMidas ? <NumberInput value={ep.grParFlacon ?? 1} onChange={v => patchRow(r.id, { grParFlacon: Math.max(1, v) })} suffix="g" step={10} className={W}/> : <span className="text-slate-300">—</span>}
                              </td>
                              <td className="bg-slate-50 px-2 py-1.5 text-center">
                                {!isMidas ? <NumberInput value={ep.mlFlacon ?? 1} onChange={v => patchRow(r.id, { mlFlacon: Math.max(1, v) })} suffix="ml" step={1} className={W}/> : <span className="text-slate-300">—</span>}
                              </td>
                              <td className="bg-slate-50 px-2 py-1.5 text-center">
                                {!isMidas ? <NumberInput value={ep.mlImprimer ?? 0} onChange={v => patchRow(r.id, { mlImprimer: Math.max(0, v) })} suffix="ml" step={0.5} className={W}/> : <span className="text-slate-300">—</span>}
                              </td>
                              <td className="bg-slate-50 px-2 py-1.5 text-center">
                                {!isMidas ? <NumberInput value={ep.perteMl ?? 0} onChange={v => patchRow(r.id, { perteMl: Math.max(0, v) })} suffix="ml" step={0.5} className={W}/> : <span className="text-slate-300">—</span>}
                              </td>
                              <td className={`${tdR} bg-slate-50 text-slate-700`}>{!isMidas ? c.mlTotal + ' ml' : '—'}</td>
                              <td className={`${tdR} bg-slate-50 text-slate-600`}>{!isMidas ? fmt.EUR2(c.prixParMl) : '—'}</td>

                              {/* ── Auto (ref, hors MO) ── */}
                              <td className="bg-blue-50 px-2 py-1.5 text-center">
                                {!isMidas ? <span className="text-blue-600 tnum text-[10.5px]">{ep.tempsCuveStd ?? 0} min</span> : <span className="text-blue-200">—</span>}
                              </td>
                              <td className="bg-blue-50 px-2 py-1.5 text-center">
                                {!isMidas ? <span className="text-blue-600 tnum text-[10.5px]">{ep.tempsArchKit ?? 0} min</span> : <span className="text-blue-200">—</span>}
                              </td>
                              <td className="bg-blue-50 px-2 py-1.5 text-center">
                                {isMidas ? <span className="text-blue-600 tnum text-[10.5px]">{ep.tempsCapsule ?? 0} min</span> : <span className="text-blue-200">—</span>}
                              </td>
                              <td className="bg-blue-50 px-2 py-1.5 text-center">
                                <span className="text-blue-600 tnum text-[10.5px]">{ep.tempsLavage ?? 0} min</span>
                              </td>
                              <td className="bg-blue-50 px-2 py-1.5 text-center">
                                <span className="text-blue-600 tnum text-[10.5px]">{ep.tempsPolymeri ?? 0} min</span>
                              </td>

                              {/* ── Manuels ★ (comptés MO) ── */}
                              <td className="bg-amber-50 px-2 py-1.5">
                                <NumberInput value={ep.tempsImbrication ?? 0} onChange={v => patchRow(r.id, { tempsImbrication: Math.max(0, v) })} step={1} suffix="min" className={W}/>
                              </td>
                              <td className="bg-amber-50 px-2 py-1.5">
                                <NumberInput value={ep.tempsPolissage ?? 0} onChange={v => patchRow(r.id, { tempsPolissage: Math.max(0, v) })} step={1} suffix="min" className={W}/>
                              </td>
                              <td className="bg-amber-100 px-2 py-1.5 text-center">
                                <div className="font-bold text-amber-900 tnum">{c.tempsManuel} min</div>
                                <div className="text-[8.5px] text-amber-600">{t('expert2.cell.imbricpol')}</div>
                              </td>
                              <td className="bg-amber-100 px-2 py-1.5 text-center">
                                <div className="font-semibold text-amber-900 tnum">{fmt.EUR2(c.coutMO)}</div>
                                <div className="text-[8.5px] text-amber-600">{c.tempsManuel} × {fmt.EUR2(tauxMin)}</div>
                              </td>

                              {/* ── Coûts ── */}
                              <td className={`${tdR} bg-violet-50 text-violet-700`}>{!isMidas ? fmt.EUR2(c.coutResine) : '—'}</td>
                              <td className={`${tdR} bg-violet-50 text-violet-700`}>{!isMidas ? fmt.EUR2(c.coutCuve) : '—'}</td>
                              <td className="bg-violet-50 px-2 py-1.5">
                                <NumberInput value={ep.cloudDesign ?? 0} onChange={v => patchRow(r.id, { cloudDesign: Math.max(0, v) })} suffix="€" step={1} className={W}/>
                              </td>
                              <td className="bg-violet-100 px-2 py-1.5 text-center">
                                <div className="font-bold text-violet-900 tnum">{fmt.EUR(c.coutTotal)}</div>
                              </td>

                              {/* ── ROI — indépendant du mode simple ── */}
                              <td className="bg-emerald-50 px-2 py-1.5">
                                <NumberInput value={coutLabo} onChange={v => patchRow(r.id, { coutLabo: Math.max(0, v) })} suffix="€" step={1} className={W}/>
                              </td>
                              <td className="bg-emerald-100 px-2 py-1.5 text-center">
                                <span className={`font-semibold tnum ${economieUnit >= 0 ? 'text-emerald-700' : 'text-rose-700'}`}>{fmt.EUR(economieUnit)}</span>
                              </td>
                              <td className="bg-emerald-50 px-2 py-1.5">
                                <NumberInput value={casMois} onChange={v => patchRow(r.id, { casMois: Math.max(0, Math.round(v)) })} step={1} className={W}/>
                              </td>
                              <td className="bg-emerald-100 px-2 py-1.5 text-center">
                                <span className={`font-semibold tnum ${economieMois >= 0 ? 'text-emerald-700' : 'text-rose-700'}`}>{fmt.EUR(economieMois)}</span>
                              </td>
                              <td className={`${tdR} bg-emerald-50 text-ink-500`}>
                                <span>{fmt.EUR(amortAttribue)}</span>
                                <div className="text-[8.5px] text-slate-400">{casMois} cas</div>
                              </td>
                              <td className="bg-emerald-200 px-2 py-1.5 text-center">
                                <span className={`font-bold tnum ${econNette >= 0 ? 'text-emerald-900' : 'text-rose-700'}`}>{fmt.EUR(econNette)}</span>
                              </td>

                            </tr>
                          );
                        })}
                      </React.Fragment>
                    );
                  })}

                  {/* Ligne totaux */}
                  <tr className="bg-ink-100 border-t-2 border-ink-300 text-[11px] font-semibold">
                    <td colSpan={2} className="px-4 py-3 text-left text-ink-800 font-bold sticky left-0 bg-ink-100 z-10">
                      {t('expert2.total.label', totalCasMois)}
                    </td>
                    <td colSpan={20} className="px-3 py-3 text-center text-ink-400 text-[10px] font-normal">
                      {t('expert2.total.amort', fmt.EUR(amortMensuel), expertGlobal.dureeAmort, fmt.EUR2(amortParCas))}
                    </td>
                    <td className="px-2 py-3 text-right tnum text-emerald-800">{fmt.EUR(totalEcoMois)}</td>
                    <td className="px-2 py-3 text-right tnum text-ink-500">{fmt.EUR(amortMensuel)}</td>
                    <td className={`px-2 py-3 text-right tnum font-bold ${totalEcoNette >= 0 ? 'text-emerald-900' : 'text-rose-700'}`}>{fmt.EUR(totalEcoNette)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </section>

        {/* ─────────────────────────────────────────────
            Section 3 — KPI Dashboard
        ───────────────────────────────────────────── */}
        <section className="max-w-[1400px] mx-auto px-6 pb-5">
          <div className="flex items-start gap-3 mb-3">
            <div className="w-7 h-7 rounded-lg bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold shrink-0">3</div>
            <div>
              <h2 className="text-[14.5px] font-semibold text-ink-900">{t('expert2.s3.title')}</h2>
              <p className="text-[12.5px] text-ink-500">{t('expert2.s3.sub')}</p>
            </div>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { label: t('expert2.kpi.bruteMois'),  value: fmt.EUR(totalEcoMois),       sub: t('expert2.kpi.bruteMois.sub', totalCasMois), color: totalEcoMois  >= 0 ? 'text-emerald-700' : 'text-rose-700' },
              { label: t('expert2.kpi.netteMois'),  value: fmt.EUR(totalEcoNette),      sub: t('expert2.kpi.netteMois.sub'),               color: totalEcoNette >= 0 ? 'text-emerald-700' : 'text-rose-700' },
              { label: t('expert2.kpi.netteAn'),    value: fmt.EUR(totalEcoNette * 12), sub: t('expert2.kpi.netteAn.sub'),                 color: totalEcoNette >= 0 ? 'text-emerald-700' : 'text-rose-700' },
              { label: t('expert2.kpi.roi'),        value: moisROI ? t('expert2.kpi.roi.val', moisROI) : '—', sub: moisROI ? t('expert2.kpi.roi.detail', Math.floor(moisROI / 12), moisROI % 12) : t('expert2.kpi.roi.na'), color: moisROI ? 'text-brand-600' : 'text-ink-400' },
            ].map((k, i) => (
              <div key={i} className="bg-white border border-ink-200 rounded-2xl shadow-card p-5">
                <div className="text-[10.5px] uppercase tracking-wider text-ink-400 mb-2 leading-snug">{k.label}</div>
                <div className={`text-[24px] font-bold tnum leading-none ${k.color}`}>{k.value}</div>
                <div className="text-[11px] text-ink-400 mt-1.5">{k.sub}</div>
              </div>
            ))}
          </div>
        </section>

        {/* ─────────────────────────────────────────────
            Section 4 — Graphique économies par indication
        ───────────────────────────────────────────── */}
        <section className="max-w-[1400px] mx-auto px-6 pb-12">
          <div className="flex items-start gap-3 mb-3">
            <div className="w-7 h-7 rounded-lg bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold shrink-0">4</div>
            <div>
              <h2 className="text-[14.5px] font-semibold text-ink-900">{t('expert2.s4.title')}</h2>
              <p className="text-[12.5px] text-ink-500">{t('expert2.s4.sub')}</p>
            </div>
          </div>

          <div className="bg-white border border-ink-200 rounded-2xl shadow-card p-5">
            {/* Légende */}
            <div className="flex flex-wrap items-center gap-5 mb-5 text-[11.5px]">
              <span className="flex items-center gap-1.5">
                <span className="w-4 h-3 rounded inline-block" style={{background:'#10b981'}}/>
                <span className="text-ink-600">{t('expert2.chart.legend.brute')}</span>
              </span>
              <span className="flex items-center gap-1.5">
                <span className="w-4 h-3 rounded inline-block border border-emerald-300" style={{background:'#a7f3d0'}}/>
                <span className="text-ink-600">{t('expert2.chart.legend.nette')} <span className="text-ink-400">{t('expert2.chart.legend.afterAmort')}</span></span>
              </span>
              <span className="flex items-center gap-1.5">
                <span className="w-4 h-3 rounded inline-block" style={{background:'#f87171'}}/>
                <span className="text-ink-400">{t('expert2.chart.legend.negative')}</span>
              </span>
            </div>

            {/* ── Graphique SVG ── */}
            {lignes.length === 0
              ? <div className="text-center text-ink-400 py-16 text-[13px]">{t('expert2.chart.empty')}</div>
              : (() => {
                  const CH = 320, ML = 70, MR = 24, MT = 20, MB = 92;
                  const n  = lignes.length;
                  const svgW = Math.max(640, n * 88 + ML + MR);
                  const cW   = svgW - ML - MR;
                  const cH   = CH - MT - MB;

                  /* Domaine Y */
                  const allV = lignes.flatMap(l => [l.economieMois, l.econNette, 0]);
                  const rawMax = Math.max(...allV), rawMin = Math.min(...allV);
                  const rawRange = rawMax - rawMin || 100;
                  const mag      = Math.pow(10, Math.floor(Math.log10(rawRange / 4)));
                  const step     = [1,2,5,10].map(m => m * mag).find(s => s >= rawRange / 4) || mag;
                  const yMin = Math.floor(rawMin / step) * step;
                  const yMax = Math.ceil(rawMax  / step) * step;
                  const yRange = yMax - yMin || 1;

                  function toY(v) { return MT + cH - ((v - yMin) / yRange) * cH; }
                  const z = toY(0);

                  /* Ticks Y */
                  const ticks = [];
                  for (let v = yMin; v <= yMax + step * 0.01; v += step) ticks.push(Math.round(v));

                  function fmtY(v) {
                    const a = Math.abs(v);
                    if (a >= 1000) return (v / 1000).toFixed(1).replace(/\.0$/, '') + 'k€';
                    return v + '€';
                  }

                  const gW = cW / n;
                  const bW = Math.min(gW * 0.28, 26);
                  const bg = gW * 0.06;

                  function bar(x, val, isBrute) {
                    const neg  = val < 0;
                    const px   = Math.max(Math.abs((val / yRange) * cH), 2);
                    const by   = neg ? z : z - px;
                    const fill = neg ? (isBrute ? '#f87171' : '#fca5a5') : (isBrute ? '#10b981' : '#a7f3d0');
                    const lbY  = neg ? by + px + 11 : Math.max(by - 5, MT + 11);
                    const lbV  = Math.abs(val) >= 1000
                      ? (val / 1000).toFixed(1).replace(/\.0$/, '') + 'k'
                      : String(Math.round(Math.abs(val)));
                    return (
                      <g key={isBrute ? 'b' : 'n'}>
                        <rect x={x} y={by} width={bW} height={px} fill={fill} rx="3"/>
                        {px > 18 && (
                          <text x={x + bW / 2} y={lbY} textAnchor="middle" fontSize="9"
                                fontWeight="600" fill={neg ? '#b91c1c' : (isBrute ? '#065f46' : '#059669')}>
                            {lbV}€
                          </text>
                        )}
                      </g>
                    );
                  }

                  return (
                    <div className="overflow-x-auto">
                      <svg width={svgW} height={CH} style={{fontFamily:'inherit',display:'block'}}>

                        {/* Grille Y */}
                        {ticks.map((v, i) => {
                          const y = toY(v);
                          return (
                            <g key={i}>
                              <line x1={ML} y1={y} x2={svgW - MR} y2={y}
                                    stroke={v === 0 ? '#9ca3af' : '#f3f4f6'}
                                    strokeWidth={v === 0 ? 1.5 : 1}
                                    strokeDasharray={v === 0 ? '' : '3,3'}/>
                              <text x={ML - 6} y={y + 4} textAnchor="end"
                                    fontSize="10" fill="#9ca3af" fontVariantNumeric="tabular-nums">
                                {fmtY(v)}
                              </text>
                            </g>
                          );
                        })}

                        {/* Axe Y */}
                        <line x1={ML} y1={MT} x2={ML} y2={MT + cH} stroke="#e5e7eb" strokeWidth="1"/>

                        {/* Barres + labels X */}
                        {lignes.map((lig, i) => {
                          const gx = ML + i * gW;
                          const cx = gx + gW / 2;
                          const x1 = cx - bW - bg / 2;
                          const x2 = cx + bg / 2;
                          const label = t('cat.' + lig.r.id + '.label');
                          const lx = gx + gW / 2;
                          const ly = MT + cH + 14;
                          return (
                            <g key={lig.r.id}>
                              {i > 0 && <line x1={gx} y1={MT} x2={gx} y2={MT + cH} stroke="#f9fafb" strokeWidth="1"/>}
                              {bar(x1, lig.economieMois, true)}
                              {bar(x2, lig.econNette,    false)}
                              <text x={lx} y={ly} textAnchor="end" fontSize="10" fill="#6b7280"
                                    transform={`rotate(-38, ${lx}, ${ly})`}>
                                {label}
                              </text>
                            </g>
                          );
                        })}

                        <text x={ML} y={MT - 6} fontSize="9" fill="#9ca3af">{t('expert2.chart.yaxis')}</text>
                      </svg>
                    </div>
                  );
                })()
            }

            {/* Totaux sous le graphique */}
            <div className="mt-5 pt-4 border-t border-ink-100 grid grid-cols-3 gap-4 text-center">
              <div>
                <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-1">{t('expert2.chart.total.brute')}</div>
                <div className={`text-[20px] font-bold tnum ${totalEcoMois >= 0 ? 'text-emerald-700' : 'text-rose-700'}`}>{fmt.EUR(totalEcoMois)}</div>
                <div className="text-[10.5px] text-ink-400">{t('expert2.chart.total.bruteSub', totalCasMois)}</div>
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-1">{t('expert2.chart.total.amort')}</div>
                <div className="text-[20px] font-bold tnum text-ink-500">{fmt.EUR(amortMensuel)}</div>
                <div className="text-[10.5px] text-ink-400">{t('expert2.chart.total.amortSub', expertGlobal.investissement.toLocaleString(), expertGlobal.dureeAmort)}</div>
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-1">{t('expert2.chart.total.nette')}</div>
                <div className={`text-[20px] font-bold tnum ${totalEcoNette >= 0 ? 'text-emerald-700' : 'text-rose-700'}`}>{fmt.EUR(totalEcoNette)}</div>
                <div className="text-[10.5px] text-ink-400">{t('expert2.chart.total.netteSub', fmt.EUR(totalEcoNette * 12))}</div>
              </div>
            </div>
          </div>

          <p className="mt-3 text-[11px] text-ink-400 leading-relaxed">{t('expert2.footer')}</p>
        </section>

      </div>
    </div>
  );
}

Object.assign(window, {
  EXPERT_DEFAULTS,
  expertComposantes,
  calculerLigneExpert,
  calculerTotauxExpert,
  ExpertPage,
});
