/* global React */
// bilan-carbone.jsx — M3 Bilan Carbone GES / CSRD / BEGES
// Scope 1/2/3 live, facteurs ADEME Base Carbone v23.1, lien automatique CEE → réduction CO2e

const { useState, useEffect, useMemo, useCallback } = React;
const BASE = (window.AE_API && window.AE_API.BASE) || '';

// ── Facteurs locaux (miroir routes/index.js — autorité = backend) ─────────────
const FACTEURS_LOCAL = {
  // Scope 1
  gaz_naturel:   { label:'Gaz naturel',             scope:1, unite:'kWh PCI', facteur:0.2010,  cat:'energie' },
  fioul_dom:     { label:'Fioul domestique',         scope:1, unite:'kWh PCI', facteur:0.3068,  cat:'energie' },
  propane_gpl:   { label:'Propane / GPL',            scope:1, unite:'kWh PCI', facteur:0.2719,  cat:'energie' },
  charbon:       { label:'Charbon / houille',        scope:1, unite:'kWh PCI', facteur:0.3445,  cat:'energie' },
  bois_buches:   { label:'Bois bûches',              scope:1, unite:'kWh PCI', facteur:0.0313,  cat:'energie' },
  bois_granules: { label:'Granulés de bois',         scope:1, unite:'kWh PCI', facteur:0.0330,  cat:'energie' },
  diesel_veh:    { label:'Diesel (véhicules fleet)', scope:1, unite:'L',       facteur:2.6310,  cat:'transport' },
  essence_veh:   { label:'Essence SP95/E10',         scope:1, unite:'L',       facteur:2.2620,  cat:'transport' },
  fuite_r410:    { label:'Fuite fluide R410A',       scope:1, unite:'kg',      facteur:2088,    cat:'process' },
  fuite_r32:     { label:'Fuite fluide R32',         scope:1, unite:'kg',      facteur:675,     cat:'process' },
  // Scope 2
  elec_france:   { label:'Électricité France',       scope:2, unite:'kWh',     facteur:0.0571,  cat:'energie' },
  rcu_moyen:     { label:'Réseau de chaleur (moy.)', scope:2, unite:'kWh',     facteur:0.0852,  cat:'energie' },
  rcf_moyen:     { label:'Réseau de froid (moy.)',   scope:2, unite:'kWh',     facteur:0.0684,  cat:'energie' },
  vapeur:        { label:'Vapeur (réseau)',           scope:2, unite:'kWh',     facteur:0.1100,  cat:'energie' },
  // Scope 3
  voiture_essence:  { label:'Voiture essence (dép. pro)',   scope:3, unite:'km',    facteur:0.2180,  cat:'deplacement' },
  voiture_diesel:   { label:'Voiture diesel (dép. pro)',    scope:3, unite:'km',    facteur:0.2020,  cat:'deplacement' },
  voiture_elec:     { label:'Véhicule électrique',          scope:3, unite:'km',    facteur:0.0193,  cat:'deplacement' },
  avion_court:      { label:'Avion court-courrier',         scope:3, unite:'km',    facteur:0.2580,  cat:'deplacement' },
  avion_moyen:      { label:'Avion moyen-courrier',         scope:3, unite:'km',    facteur:0.2200,  cat:'deplacement' },
  avion_long:       { label:'Avion long-courrier',          scope:3, unite:'km',    facteur:0.1950,  cat:'deplacement' },
  tgv_train:        { label:'TGV / Train intercités',       scope:3, unite:'km',    facteur:0.00285, cat:'deplacement' },
  metro_rer:        { label:'Métro / RER / Tram',           scope:3, unite:'km',    facteur:0.00488, cat:'deplacement' },
  bus_interurbain:  { label:'Bus / Car',                    scope:3, unite:'km',    facteur:0.1127,  cat:'deplacement' },
  fret_routier:     { label:'Fret routier (PL)',            scope:3, unite:'t.km',  facteur:0.0681,  cat:'fret' },
  fret_maritime:    { label:'Fret maritime',                scope:3, unite:'t.km',  facteur:0.0117,  cat:'fret' },
  fret_aerien:      { label:'Fret aérien',                  scope:3, unite:'t.km',  facteur:2.1000,  cat:'fret' },
  fret_ferroviaire: { label:'Fret ferroviaire',             scope:3, unite:'t.km',  facteur:0.0028,  cat:'fret' },
  dechets_enf:      { label:'Déchets — enfouissement',      scope:3, unite:'t',     facteur:440,     cat:'dechets' },
  dechets_inci:     { label:'Déchets — incinération',       scope:3, unite:'t',     facteur:630,     cat:'dechets' },
  dechets_rec:      { label:'Déchets — recyclage',          scope:3, unite:'t',     facteur:20,      cat:'dechets' },
  eau_reseau:       { label:'Eau du réseau',                scope:3, unite:'m³',    facteur:0.3440,  cat:'autres' },
  papier_bureau:    { label:'Papier bureau',                scope:3, unite:'kg',    facteur:0.9190,  cat:'autres' },
  repas_mixte:      { label:'Repas mixte (viande)',         scope:3, unite:'repas', facteur:2.50,    cat:'autres' },
  repas_vegeta:     { label:'Repas végétarien',             scope:3, unite:'repas', facteur:0.83,    cat:'autres' },
};

const SCOPE_LABELS = { 1: 'Scope 1 — Émissions directes', 2: 'Scope 2 — Énergie achetée', 3: 'Scope 3 — Autres indirectes' };
const SCOPE_COLORS = { 1: 'var(--rouge)', 2: 'var(--copper)', 3: 'var(--plasma)' };
const STATUS_INFO = {
  brouillon: { label: 'Brouillon',  tone: 'neutral' },
  complet:   { label: 'Complet',    tone: 'amber' },
  verifie:   { label: 'Vérifié',    tone: 'signal' },
  publie:    { label: 'Publié',     tone: 'signal' },
};

function apiGES(path, opts) {
  return fetch(BASE + '/api/bilan-carbone' + path, { headers: { 'Content-Type': 'application/json' }, ...opts }).then(r => r.json());
}
function fmt2(n) { return (n ?? 0).toLocaleString('fr-FR', { maximumFractionDigits: 2 }); }
function fmtT(n) { return fmt2(n) + ' tCO₂e'; }

function calcScopeLocal(scopeData) {
  let total = 0;
  for (const entry of Object.values(scopeData || {})) {
    if (!entry?.facteurKey || !entry?.quantite) continue;
    const f = FACTEURS_LOCAL[entry.facteurKey];
    if (!f) continue;
    total += parseFloat(entry.quantite) * f.facteur;
  }
  return Math.round(total / 10) / 100; // kgCO2e → tCO2e, 2 déc
}

// ── Shared UI ──────────────────────────────────────────────────────────────────
function Panel({ title, subtitle, children, actions, style }) {
  return (
    <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden', ...style }}>
      {(title || actions) && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
            {subtitle && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{subtitle}</div>}
          </div>
          {actions && <div style={{ display: 'flex', gap: 6 }}>{actions}</div>}
        </div>
      )}
      <div style={{ padding: 16 }}>{children}</div>
    </div>
  );
}
function Modal({ title, onClose, children, width = 760 }) {
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 3000, background: 'rgba(0,0,0,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={onClose}>
      <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 10, width, maxWidth: '96vw', maxHeight: '92vh', overflow: 'auto', boxShadow: '0 24px 48px rgba(0,0,0,.2)' }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontWeight: 600, fontSize: 14 }}>{title}</span>
          <Btn variant="ghost" size="sm" onClick={onClose} icon={<Icon.cross />} />
        </div>
        <div style={{ padding: 20 }}>{children}</div>
      </div>
    </div>
  );
}
function Field({ label, children, hint }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</label>
      {children}
      {hint && <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 3 }}>{hint}</div>}
    </div>
  );
}
function Input({ value, onChange, type = 'text', placeholder, step, min, disabled, style }) {
  return <input type={type} value={value ?? ''} onChange={onChange} placeholder={placeholder} step={step} min={min} disabled={disabled}
    style={{ width: '100%', padding: '7px 10px', fontSize: 13, borderRadius: 6, border: '1px solid var(--line-2)', background: 'var(--paper-2)', color: 'var(--ink)', outline: 'none', boxSizing: 'border-box', ...style }} />;
}
function Select({ value, onChange, children, style }) {
  return <select value={value ?? ''} onChange={onChange}
    style={{ width: '100%', padding: '7px 10px', fontSize: 13, borderRadius: 6, border: '1px solid var(--line-2)', background: 'var(--paper-2)', color: 'var(--ink)', ...style }}>{children}</select>;
}

// ── ScopeBar — barre visuelle d'un scope ──────────────────────────────────────
function ScopeBar({ scope, total, value }) {
  const pct = total > 0 ? Math.min(100, (value / total) * 100) : 0;
  const color = SCOPE_COLORS[scope];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color, width: 50, flexShrink: 0 }}>S{scope}</div>
      <div style={{ flex: 1, height: 8, background: 'var(--paper-3)', borderRadius: 99 }}>
        <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 99, transition: 'width 600ms ease' }} />
      </div>
      <div style={{ fontSize: 12, fontWeight: 600, width: 90, textAlign: 'right', color }}>{fmtT(value)}</div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', width: 36, textAlign: 'right' }}>{Math.round(pct)}%</div>
    </div>
  );
}

// ── Saisie d'un scope (lignes d'entrée) ───────────────────────────────────────
function ScopeSaisie({ scopeNum, scopeData, onChange, total }) {
  const entries = Object.entries(scopeData || {});
  const scopeFact = Object.entries(FACTEURS_LOCAL).filter(([, f]) => f.scope === scopeNum);

  // grouper par catégorie
  const cats = [...new Set(scopeFact.map(([, f]) => f.cat))];

  const addLine = (facteurKey) => {
    onChange({ ...scopeData, [`${facteurKey}_${Date.now()}`]: { facteurKey, quantite: '', label: FACTEURS_LOCAL[facteurKey]?.label } });
  };
  const updateLine = (k, field, val) => {
    onChange({ ...scopeData, [k]: { ...scopeData[k], [field]: val } });
  };
  const removeLine = (k) => {
    const next = { ...scopeData };
    delete next[k];
    onChange(next);
  };

  const scopeTotal = calcScopeLocal(scopeData);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div>
          <span style={{ fontSize: 13, fontWeight: 700, color: SCOPE_COLORS[scopeNum] }}>{SCOPE_LABELS[scopeNum]}</span>
          {total > 0 && <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--ink-3)' }}>({Math.round(scopeTotal / total * 100)}% du total)</span>}
        </div>
        <strong style={{ color: SCOPE_COLORS[scopeNum], fontSize: 15 }}>{fmtT(scopeTotal)}</strong>
      </div>

      {/* Sélecteur d'ajout de ligne */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
        {cats.map(cat => (
          <div key={cat} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5 }}>{cat}</div>
            <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
              {scopeFact.filter(([, f]) => f.cat === cat).map(([key, f]) => (
                <button key={key} onClick={() => addLine(key)}
                  style={{ padding: '3px 8px', fontSize: 11, borderRadius: 4, border: '1px solid var(--line-2)', background: 'var(--paper-2)', color: 'var(--ink-2)', cursor: 'pointer' }}>
                  + {f.label}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Lignes saisies */}
      {entries.length === 0
        ? <div style={{ textAlign: 'center', padding: '12px 0', color: 'var(--ink-4)', fontSize: 12 }}>Aucune source émettrice — cliquer pour en ajouter.</div>
        : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--line)' }}>
                {['Source', 'Quantité', 'Unité', 'Facteur (kgCO₂e/u)', 'Émissions (tCO₂e)', ''].map(h => (
                  <th key={h} style={{ padding: '5px 6px', textAlign: 'left', color: 'var(--ink-3)', fontWeight: 600, fontSize: 11 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {entries.map(([k, entry]) => {
                const f = FACTEURS_LOCAL[entry.facteurKey];
                const emis = f && entry.quantite ? (parseFloat(entry.quantite) * f.facteur / 1000) : 0;
                return (
                  <tr key={k} style={{ borderBottom: '1px solid var(--line-2)' }}>
                    <td style={{ padding: '6px 6px', fontWeight: 500, maxWidth: 180 }}>{entry.label || f?.label || entry.facteurKey}</td>
                    <td style={{ padding: '6px 6px', width: 110 }}>
                      <Input type="number" value={entry.quantite} onChange={e => updateLine(k, 'quantite', e.target.value)} placeholder="0" min="0" step="any" style={{ width: 100 }} />
                    </td>
                    <td style={{ padding: '6px 6px', color: 'var(--ink-3)' }}>{f?.unite || '—'}</td>
                    <td style={{ padding: '6px 6px', color: 'var(--ink-3)' }}>{f ? fmt2(f.facteur) : '—'}</td>
                    <td style={{ padding: '6px 6px', fontWeight: emis > 0 ? 600 : 400, color: emis > 0 ? SCOPE_COLORS[scopeNum] : 'var(--ink-4)' }}>
                      {emis > 0 ? fmtT(emis) : '—'}
                    </td>
                    <td style={{ padding: '6px 6px' }}>
                      <Btn variant="ghost" size="sm" onClick={() => removeLine(k)} icon={<Icon.cross />} style={{ color: 'var(--rouge)' }} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )
      }
    </div>
  );
}

// ── Formulaire bilan complet ────────────────────────────────────────────────────
function BilanForm({ initial, onSave, onClose }) {
  const isNew = !initial?.id;
  const [form, setForm] = useState(initial || {
    nom: '', description: '', organisationNom: '', siret: '', secteurActivite: '', nombreSalaries: '',
    annee: new Date().getFullYear() - 1,
    perimetre: 'operationnel', status: 'brouillon',
    scope1: {}, scope2: {}, scope3: {},
    notes: '',
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const f = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

  // Totaux live
  const s1 = useMemo(() => calcScopeLocal(form.scope1), [form.scope1]);
  const s2 = useMemo(() => calcScopeLocal(form.scope2), [form.scope2]);
  const s3 = useMemo(() => calcScopeLocal(form.scope3), [form.scope3]);
  const total = s1 + s2 + s3;

  const save = async () => {
    if (!form.nom) { setError('Le nom du bilan est requis'); return; }
    setSaving(true); setError('');
    try {
      const method = isNew ? 'POST' : 'PATCH';
      const url = isNew ? '/bilans' : `/bilans/${form.id}`;
      const saved = await apiGES(url, { method, body: JSON.stringify(form) });
      if (saved.id) {
        // Déclencher calcul côté backend pour obtenir totalCO2e + lien CEE
        await apiGES(`/bilans/${saved.id}/calcul`, { method: 'POST' });
      }
      onSave && onSave();
      onClose();
    } catch (e) { setError(e.message || 'Erreur'); }
    setSaving(false);
  };

  return (
    <div>
      {/* Identité */}
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>📋 Identification</div>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: '0 14px' }}>
        <Field label="Nom du bilan *"><Input value={form.nom} onChange={f('nom')} placeholder="Bilan GES 2023 — Siège social" /></Field>
        <Field label="Année de référence">
          <Select value={form.annee} onChange={f('annee')}>
            {Array.from({ length: 10 }, (_, i) => new Date().getFullYear() - 1 - i).map(y => <option key={y} value={y}>{y}</option>)}
          </Select>
        </Field>
        <Field label="Périmètre">
          <Select value={form.perimetre} onChange={f('perimetre')}>
            <option value="operationnel">Opérationnel (contrôle financier)</option>
            <option value="financier">Financier (part de capital)</option>
          </Select>
        </Field>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '0 14px' }}>
        <Field label="Raison sociale"><Input value={form.organisationNom} onChange={f('organisationNom')} placeholder="Audits Énergies SAS" /></Field>
        <Field label="SIRET"><Input value={form.siret} onChange={f('siret')} placeholder="123 456 789 00012" /></Field>
        <Field label="Secteur d'activité"><Input value={form.secteurActivite} onChange={f('secteurActivite')} placeholder="Conseil en énergie" /></Field>
        <Field label="Nb salariés (ETP)"><Input type="number" value={form.nombreSalaries} onChange={f('nombreSalaries')} placeholder="12" min="0" /></Field>
      </div>

      {/* Mini-dashboard live */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, margin: '16px 0', padding: '14px', background: 'var(--paper-2)', borderRadius: 8, border: '1px solid var(--line)' }}>
        {[
          { label: 'Scope 1', value: s1, color: SCOPE_COLORS[1] },
          { label: 'Scope 2', value: s2, color: SCOPE_COLORS[2] },
          { label: 'Scope 3', value: s3, color: SCOPE_COLORS[3] },
          { label: 'Total', value: total, color: 'var(--ink)', big: true },
        ].map((kpi, i) => (
          <div key={i} style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 4 }}>{kpi.label}</div>
            <div style={{ fontSize: kpi.big ? 18 : 15, fontWeight: 700, color: kpi.color }}>{fmtT(kpi.value)}</div>
          </div>
        ))}
      </div>

      {/* Scope 1 */}
      <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, marginTop: 4, marginBottom: 16 }}>
        <ScopeSaisie scopeNum={1} scopeData={form.scope1} onChange={s1 => setForm(p => ({ ...p, scope1: s1 }))} total={total} />
      </div>

      {/* Scope 2 */}
      <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, marginBottom: 16 }}>
        <ScopeSaisie scopeNum={2} scopeData={form.scope2} onChange={s2 => setForm(p => ({ ...p, scope2: s2 }))} total={total} />
      </div>

      {/* Scope 3 */}
      <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, marginBottom: 16 }}>
        <ScopeSaisie scopeNum={3} scopeData={form.scope3} onChange={s3 => setForm(p => ({ ...p, scope3: s3 }))} total={total} />
      </div>

      <Field label="Notes"><Input value={form.notes} onChange={f('notes')} placeholder="Méthodologie, hypothèses, périmètre d'exclusion…" /></Field>

      {error && <div style={{ color: 'var(--rouge)', fontSize: 12, marginBottom: 10 }}>{error}</div>}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
        <Btn variant="ghost" onClick={onClose}>Annuler</Btn>
        <Btn variant="primary" onClick={save} disabled={saving || !form.nom}>{saving ? 'Sauvegarde + calcul…' : isNew ? 'Créer le bilan' : 'Enregistrer'}</Btn>
      </div>
    </div>
  );
}

// ── Résultats d'un bilan ───────────────────────────────────────────────────────
function BilanResultats({ bilan }) {
  const s1 = bilan.totalScope1 || 0;
  const s2 = bilan.totalScope2 || 0;
  const s3 = bilan.totalScope3 || 0;
  const total = bilan.totalCO2e || (s1 + s2 + s3);
  const cee = bilan.reductionCEE || 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)', overflow: 'hidden' }}>
        {[
          { label: 'Total GES', value: fmtT(total), sub: `${bilan.annee} · ${bilan.perimetre}`, color: 'var(--ink)' },
          { label: 'Scope 1 (direct)', value: fmtT(s1), sub: `${total > 0 ? Math.round(s1/total*100) : 0}% du total`, color: SCOPE_COLORS[1], div: true },
          { label: 'Scope 2 (énergie)', value: fmtT(s2), sub: `${total > 0 ? Math.round(s2/total*100) : 0}% du total`, color: SCOPE_COLORS[2], div: true },
          { label: 'Scope 3 (indirect)', value: fmtT(s3), sub: `${total > 0 ? Math.round(s3/total*100) : 0}% du total`, color: SCOPE_COLORS[3], div: true },
        ].map((kpi, i) => (
          <div key={i} style={{ padding: '16px 18px', borderLeft: kpi.div ? '1px solid var(--line)' : 'none' }}>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>{kpi.label}</div>
            <div style={{ fontSize: 20, fontWeight: 700, color: kpi.color, letterSpacing: '-0.02em' }}>{kpi.value}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{kpi.sub}</div>
          </div>
        ))}
      </div>

      {/* Barres scope */}
      {total > 0 && (
        <Panel title="Répartition par scope" subtitle="GHG Protocol — tCO₂e">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <ScopeBar scope={1} value={s1} total={total} />
            <ScopeBar scope={2} value={s2} total={total} />
            <ScopeBar scope={3} value={s3} total={total} />
          </div>
        </Panel>
      )}

      {/* Lien CEE */}
      <Panel title="🔗 Réductions CEE → Scope 1/2" subtitle="Différenciateur unique — économies générées par vos dossiers CEE">
        {cee > 0
          ? (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--signal)' }}>−{fmtT(cee)}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>économisées via dossiers CEE validés</div>
                </div>
                {total > 0 && (
                  <div style={{ borderLeft: '1px solid var(--line)', paddingLeft: 16 }}>
                    <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--signal-deep)' }}>{fmtT(Math.max(0, total - cee))}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>émissions nettes après CEE</div>
                  </div>
                )}
              </div>
              {(bilan.reductionDetail || []).slice(0, 5).map((d, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', borderTop: '1px solid var(--line-2)', fontSize: 12 }}>
                  <RefChip r={d.ref} />
                  <span style={{ color: 'var(--ink-3)' }}>{(d.kWhCumac / 1000).toFixed(1)} MWhcumac</span>
                  <span style={{ marginLeft: 'auto', fontWeight: 600, color: 'var(--signal)' }}>−{fmtT(d.tCO2e)}</span>
                </div>
              ))}
            </div>
          )
          : <div style={{ fontSize: 12, color: 'var(--ink-3)', padding: '8px 0' }}>Aucune réduction CEE détectée. Les dossiers CEE validés dans votre espace seront automatiquement comptabilisés après recalcul.</div>
        }
      </Panel>
    </div>
  );
}

// ── Tab Facteurs ADEME ─────────────────────────────────────────────────────────
function FacteursTab() {
  const scopes = [1, 2, 3];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {scopes.map(s => {
        const items = Object.entries(FACTEURS_LOCAL).filter(([, f]) => f.scope === s);
        const cats = [...new Set(items.map(([, f]) => f.cat))];
        return (
          <Panel key={s} title={SCOPE_LABELS[s]} subtitle="Source : ADEME Base Carbone® v23.1 — kgCO₂e / unité">
            {cats.map(cat => (
              <div key={cat} style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>{cat}</div>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                  <thead>
                    <tr style={{ borderBottom: '1px solid var(--line)' }}>
                      {['Source', 'Facteur (kgCO₂e)', 'Unité'].map(h => <th key={h} style={{ padding: '4px 6px', textAlign: 'left', color: 'var(--ink-3)', fontWeight: 600, fontSize: 11 }}>{h}</th>)}
                    </tr>
                  </thead>
                  <tbody>
                    {items.filter(([, f]) => f.cat === cat).map(([key, f]) => (
                      <tr key={key} style={{ borderBottom: '1px solid var(--line-2)' }}>
                        <td style={{ padding: '5px 6px', fontWeight: 500 }}>{f.label}</td>
                        <td style={{ padding: '5px 6px', color: SCOPE_COLORS[s], fontWeight: 600 }}>{fmt2(f.facteur)}</td>
                        <td style={{ padding: '5px 6px', color: 'var(--ink-3)' }}>{f.unite}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ))}
          </Panel>
        );
      })}
    </div>
  );
}

// ── Main ────────────────────────────────────────────────────────────────────────
function BilanCarbonePage() {
  const TABS = [
    { key: 'bilans',   label: 'Bilans GES',       icon: Icon.chart },
    { key: 'facteurs', label: 'Facteurs ADEME',   icon: Icon.doc },
    { key: 'params',   label: '⚙ Paramètres',    icon: null },
  ];
  const [tab, setTab] = useState('bilans');
  const [bilans, setBilans] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modal, setModal] = useState(null);     // null | 'new' | bilan
  const [viewBilan, setViewBilan] = useState(null); // bilan pour résultats

  const load = useCallback(async () => {
    setLoading(true);
    const d = await apiGES('/bilans').catch(() => ({ bilans: [] }));
    setBilans(d.bilans || []);
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  const del = async (id) => {
    if (!confirm('Supprimer ce bilan ?')) return;
    await apiGES(`/bilans/${id}`, { method: 'DELETE' });
    load();
  };

  const recalc = async (id) => {
    await apiGES(`/bilans/${id}/calcul`, { method: 'POST' });
    load();
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ padding: '16px 24px 0', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <h1 style={{ fontSize: 16, fontWeight: 700, margin: 0 }}>🌿 Bilan Carbone / CSRD</h1>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>BEGES réglementaire · GHG Protocol Scope 1/2/3 · ADEME Base Carbone v23.1 · Lien CEE automatique</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Badge tone="signal">M3 Bilan Carbone</Badge>
            <Badge tone="plasma">CSRD 2026</Badge>
            <Btn variant="ghost" size="sm" icon={<Icon.refresh />} onClick={load}>Actualiser</Btn>
            <Btn variant="primary" size="sm" icon={<Icon.plus />} onClick={() => setModal('new')}>Nouveau bilan</Btn>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--line)' }}>
          {TABS.map(t => (
            <button key={t.key} onClick={() => setTab(t.key)}
              style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', fontSize: 13, fontWeight: tab === t.key ? 600 : 400, color: tab === t.key ? 'var(--ink)' : 'var(--ink-3)', background: 'none', border: 'none', borderBottom: tab === t.key ? '2px solid var(--signal)' : '2px solid transparent', cursor: 'pointer' }}>
              {t.icon && <t.icon />} {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px 60px' }}>
        {tab === 'bilans' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* KPIs */}
            {bilans.length > 0 && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)', overflow: 'hidden' }}>
                {[
                  { label: 'Bilans réalisés', value: bilans.length, color: 'var(--ink)' },
                  { label: 'Total CO₂e (dernier)', value: fmtT(bilans[0]?.totalCO2e || 0), color: 'var(--plasma)', div: true },
                  { label: 'Réductions CEE', value: fmtT(bilans.reduce((s, b) => s + (b.reductionCEE || 0), 0)), color: 'var(--signal)', div: true },
                ].map((kpi, i) => (
                  <div key={i} style={{ padding: '16px 20px', borderLeft: kpi.div ? '1px solid var(--line)' : 'none' }}>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>{kpi.label}</div>
                    <div style={{ fontSize: 22, fontWeight: 700, color: kpi.color, letterSpacing: '-0.02em' }}>{typeof kpi.value === 'number' ? kpi.value : kpi.value}</div>
                  </div>
                ))}
              </div>
            )}

            {/* Liste bilans */}
            {loading && <div style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>Chargement…</div>}
            {!loading && bilans.length === 0 && (
              <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-3)' }}>
                <div style={{ fontSize: 32, marginBottom: 10 }}>🌿</div>
                <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Aucun bilan carbone</div>
                <div style={{ fontSize: 12, marginBottom: 16 }}>Créez votre premier bilan GES pour déclarer vos émissions Scope 1/2/3 et piloter votre trajectoire bas-carbone.</div>
                <Btn variant="primary" onClick={() => setModal('new')} icon={<Icon.plus />}>Créer le premier bilan</Btn>
              </div>
            )}
            {bilans.map(b => (
              <div key={b.id} style={{ border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper)', overflow: 'hidden' }}>
                <div style={{ display: 'flex', alignItems: 'center', padding: '14px 18px', borderBottom: '1px solid var(--line)', gap: 16 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{b.nom}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{b.organisationNom || '—'} · Année {b.annee} · {b.perimetre}</div>
                  </div>
                  <Badge tone={STATUS_INFO[b.status]?.tone || 'neutral'}>{STATUS_INFO[b.status]?.label || b.status}</Badge>
                  <strong style={{ fontSize: 15, color: b.totalCO2e > 0 ? 'var(--plasma)' : 'var(--ink-4)' }}>{fmtT(b.totalCO2e || 0)}</strong>
                  {b.reductionCEE > 0 && <Badge tone="signal">−{fmtT(b.reductionCEE)} CEE</Badge>}
                  <div style={{ display: 'flex', gap: 6 }}>
                    <Btn variant="outline" size="sm" onClick={() => setViewBilan(b === viewBilan ? null : b)}>Résultats</Btn>
                    <Btn variant="ghost" size="sm" icon={<Icon.doc />} onClick={() => setModal(b)}>Modifier</Btn>
                    <Btn variant="ghost" size="sm" icon={<Icon.refresh />} onClick={() => recalc(b.id)}>Recalc.</Btn>
                    <Btn variant="ghost" size="sm" icon={<Icon.cross />} onClick={() => del(b.id)} style={{ color: 'var(--rouge)' }} />
                  </div>
                </div>
                {viewBilan?.id === b.id && (
                  <div style={{ padding: 18 }}>
                    <BilanResultats bilan={b} />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
        {tab === 'facteurs' && <FacteursTab />}
        {tab === 'params' && (
          <div style={{ maxWidth: 560 }}>
            <Panel title="Réglementation BEGES / CSRD" subtitle="Rappel des obligations légales">
              <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.8 }}>
                <div><strong>BEGES réglementaire :</strong> Obligatoire tous les 4 ans pour les entreprises {'>'} 500 salariés (France)</div>
                <div><strong>CSRD (EU) :</strong> Extension aux PME cotées dès 2026 — reporting GES annuel obligatoire</div>
                <div><strong>Référentiel :</strong> GHG Protocol — Scope 1 (direct) + Scope 2 (énergie) + Scope 3 (indirect)</div>
                <div><strong>Facteurs :</strong> ADEME Base Carbone® v23.1 — mis à jour annuellement</div>
              </div>
            </Panel>
          </div>
        )}
      </div>

      {/* Modal bilan */}
      {modal && (
        <Modal title={modal === 'new' ? 'Nouveau bilan GES' : `Modifier — ${modal.nom}`} onClose={() => setModal(null)} width={860}>
          <BilanForm initial={modal === 'new' ? null : modal} onSave={load} onClose={() => setModal(null)} />
        </Modal>
      )}
    </div>
  );
}

Object.assign(window, { BilanCarbonePage });
