// settings-page.jsx — Page Paramètres unifiée (Règle n°6 SaaS-wide)
// Couvre : CRM (P5.1), Solaire (P5.2), Communication (P5.3), Visites (P5.4),
// Dossiers CEE (P5.5). Persisté en localStorage `ae_settings_v1` + endpoint
// /api/settings (optionnel, fallback transparent).

const { useState: _stUseS, useEffect: _stUseE, useMemo: _stUseM } = React;

// ── Schéma défaut ──────────────────────────────────────────────────────────
const DEFAULT_SETTINGS = {
  crm: {
    stages: [
      { key: 'prospect',     label: 'Prospect',           color: '#8A8D90' },
      { key: 'qualification',label: 'Qualification',      color: '#6B4CFF' },
      { key: 'visite',       label: 'Visite',             color: '#3FE07C' },
      { key: 'devis',        label: 'Devis envoyé',       color: '#E8B341' },
      { key: 'signe',        label: 'Devis signé',        color: '#0F7A3D' },
      { key: 'travaux',      label: 'Travaux',            color: '#C66A2B' },
      { key: 'depot_pncee',  label: 'Dépôt PNCEE',        color: '#6B4CFF' },
      { key: 'prime_versee', label: 'Prime versée',       color: '#0F7A3D' },
    ],
    relanceTemplate: `Bonjour {prenom},\n\nJ'espère que vous allez bien.\nJe me permets de revenir vers vous au sujet de votre projet d'audit énergétique.\n\nAvez-vous eu l'occasion de revoir notre proposition ?\n\nBien cordialement,\n{signature}`,
    autoSyncOdoo: true,
    syncIntervalMin: 30,
  },
  solaire: {
    catalogues: {
      panneauxFavoris: ['Trina Vertex S+ 440', 'DualSun Flash 425', 'Voltec Tarka 410'],
      onduleurFavori: 'SolarEdge',
      batterieFavorite: 'BYD HVM',
    },
    tarifs: {
      achatMWh: 75,    // €/MWh autoconsommation
      revente:  130,   // €/MWh injection
      tva:      20,    // %
    },
    fostDefaut: 'BAR-EN-101',
    delegataireDefaut: 'Audits-Énergies SAS',
  },
  communication: {
    signatureEmail: `--\nNils Bazin\nChef de projet — Audits Énergies\nemail · 06 XX XX XX XX\nwww.audits-energies.com`,
    templates: {
      relance30j:  { subject: 'Relance projet — {ref}',           body: 'Bonjour {prenom},\nNous revenons vers vous concernant…' },
      visiteOk:    { subject: 'Visite confirmée — {date}',         body: 'Bonjour {prenom},\nVotre visite technique est confirmée…' },
      devisEnvoye: { subject: 'Votre devis Audits Énergies — {ref}',body: 'Bonjour {prenom},\nVeuillez trouver ci-joint…' },
    },
    scanProspectsAuto: false,
    scanProspectsIntervalH: 24,
  },
  visites: {
    fostFavoris: ['BAT-TH-139', 'BAT-TH-129', 'BAR-EN-101', 'BAT-TH-113'],
    rapportTemplate: 'standard', // 'standard' | 'detaille' | 'minimal'
    pipelineAutoStart: true,
    extractionConfidenceMin: 0.6,
  },
  dossiers: {
    workflowOrder: ['draft','in_progress','approved','depot_pncee','prime_versee'],
    delegataireDefaut: 'Audits-Énergies SAS',
    autoApprove: false,
    minCoherenceScore: 80,
  },
};

const STORAGE_KEY = 'ae_settings_v1';

function loadSettingsLocal() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      return mergeWithDefaults(parsed);
    }
  } catch (_) {}
  return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
}

function mergeWithDefaults(parsed) {
  return {
    crm:           { ...DEFAULT_SETTINGS.crm,           ...(parsed.crm || {}) },
    solaire:       { ...DEFAULT_SETTINGS.solaire,       ...(parsed.solaire || {}) },
    communication: { ...DEFAULT_SETTINGS.communication, ...(parsed.communication || {}) },
    visites:       { ...DEFAULT_SETTINGS.visites,       ...(parsed.visites || {}) },
    dossiers:      { ...DEFAULT_SETTINGS.dossiers,      ...(parsed.dossiers || {}) },
  };
}

// A2 — Backend persistence : si user authentifié, sync via /api/settings
async function loadSettingsBackend() {
  const API = (window.AE_API && window.AE_API.BASE) || '';
  try {
    const r = await fetch(`${API}/api/settings`, { credentials: 'include' });
    if (!r.ok) return null;
    const d = await r.json();
    if (d.ok && d.settings) return mergeWithDefaults(d.settings);
  } catch (_) {}
  return null;
}

async function saveSettingsBackend(scope, data) {
  const API = (window.AE_API && window.AE_API.BASE) || '';
  try {
    await fetch(`${API}/api/settings/${scope}`, {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
  } catch (_) { /* fail-silent : localStorage reste source de fallback */ }
}

function loadSettings() {
  return loadSettingsLocal();
}

function saveSettings(s, changedScope) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch (_) {}
  window.AE_SETTINGS = s;
  window.dispatchEvent(new CustomEvent('ae:settings-changed', { detail: s }));
  // A2 : sync vers backend si authentifié
  if (changedScope && s[changedScope]) {
    saveSettingsBackend(changedScope, s[changedScope]);
  }
}

// Initial load on script execution → expose to other modules
window.AE_SETTINGS = loadSettings();

// ── Page ────────────────────────────────────────────────────────────────────
function SettingsPage() {
  const [settings, setSettings] = _stUseS(loadSettings);
  const [section, setSection] = _stUseS('crm');
  const [savedAt, setSavedAt] = _stUseS(null);

  // A2 — Au montage, hydrate depuis backend si user authentifié (override local)
  _stUseE(() => {
    loadSettingsBackend().then(remote => {
      if (remote) {
        setSettings(remote);
        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(remote)); } catch (_) {}
        window.AE_SETTINGS = remote;
        window.dispatchEvent(new CustomEvent('ae:settings-changed', { detail: remote }));
      }
    });
  }, []);

  const persist = (next, changedScope) => {
    setSettings(next);
    saveSettings(next, changedScope);
    setSavedAt(Date.now());
    setTimeout(() => setSavedAt(null), 2500);
  };

  const update = (sec, patch) => {
    persist({ ...settings, [sec]: { ...settings[sec], ...patch } }, sec);
  };

  const reset = () => {
    if (!window.confirm('Réinitialiser tous les paramètres aux valeurs par défaut ?')) return;
    persist(JSON.parse(JSON.stringify(DEFAULT_SETTINGS)));
  };

  const exportSettings = () => {
    const blob = new Blob([JSON.stringify(settings, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `ae-settings-${new Date().toISOString().slice(0,10)}.json`; a.click();
    URL.revokeObjectURL(url);
  };

  const importSettings = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const parsed = JSON.parse(reader.result);
        persist(parsed);
        alert('✓ Paramètres importés');
      } catch (err) { alert('Fichier invalide : ' + err.message); }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const SECTIONS = [
    { key: 'crm',           label: 'CRM Clients',     icon: '👥' },
    { key: 'solaire',       label: 'Solaire',         icon: '☀️' },
    { key: 'communication', label: 'Communication',   icon: '✉️' },
    { key: 'visites',       label: 'Visites IA',      icon: '📹' },
    { key: 'dossiers',      label: 'Dossiers CEE',    icon: '📁' },
  ];

  return (
    <div style={{ padding: '20px 24px 40px' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 20 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.8, fontWeight: 600 }}>Règle n°6 · Personnalisation par module</div>
          <h1 style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', margin: '4px 0 0' }}>Paramètres</h1>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>Configurez les défauts, templates, catalogues et workflows de chaque module sans toucher au code. Persisté localement par utilisateur.</div>
        </div>
        <span style={{ flex: 1 }} />
        {savedAt && <span style={{ fontSize: 11, color: 'var(--signal-deep)', padding: '4px 10px', background: 'var(--signal-tint)', border: '1px solid var(--signal-soft)', borderRadius: 4 }}>✓ Enregistré</span>}
        <Btn variant="outline" size="sm" onClick={exportSettings}>📤 Exporter</Btn>
        <label style={{ cursor: 'pointer' }}>
          <input type="file" accept=".json" onChange={importSettings} style={{ display: 'none' }} />
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', fontSize: 12, fontWeight: 500, border: '1px solid var(--line-2)', borderRadius: 5, background: 'var(--paper)', color: 'var(--ink)' }}>📥 Importer</span>
        </label>
        <Btn variant="ghost" size="sm" onClick={reset}>🔄 Réinitialiser</Btn>
      </div>

      {/* N5 — Sélecteur de langue */}
      {window.AE_I18N && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 6, marginBottom: 16 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>🌍 Langue / Language</span>
          <span style={{ flex: 1 }} />
          {window.AE_I18N.getSupported().map(loc => (
            <button key={loc} onClick={() => { window.AE_I18N.setLocale(loc); window.location.reload(); }}
              style={{
                padding: '5px 12px', fontSize: 12, fontWeight: window.AE_I18N.getLocale() === loc ? 700 : 500,
                background: window.AE_I18N.getLocale() === loc ? 'var(--ink)' : 'var(--paper)',
                color: window.AE_I18N.getLocale() === loc ? 'var(--paper)' : 'var(--ink-2)',
                border: '1px solid ' + (window.AE_I18N.getLocale() === loc ? 'var(--ink)' : 'var(--line-2)'),
                borderRadius: 4, cursor: 'pointer', textTransform: 'uppercase',
              }}>{loc}</button>
          ))}
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 16 }}>
        {/* Sidebar sections */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2, position: 'sticky', top: 70, alignSelf: 'flex-start' }}>
          {SECTIONS.map(s => (
            <button key={s.key} onClick={() => setSection(s.key)} style={{
              padding: '10px 14px', fontSize: 13, fontWeight: section === s.key ? 600 : 500,
              background: section === s.key ? 'var(--paper-2)' : 'transparent',
              color: section === s.key ? 'var(--ink)' : 'var(--ink-3)',
              border: '1px solid ' + (section === s.key ? 'var(--line-2)' : 'transparent'),
              borderRadius: 5, cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <span style={{ fontSize: 14 }}>{s.icon}</span>
              {s.label}
            </button>
          ))}
        </div>

        {/* Content */}
        <div>
          {section === 'crm'           && <CrmSettings           v={settings.crm}           onChange={(p) => update('crm', p)}/>}
          {section === 'solaire'       && <SolaireSettings       v={settings.solaire}       onChange={(p) => update('solaire', p)}/>}
          {section === 'communication' && <CommunicationSettings v={settings.communication} onChange={(p) => update('communication', p)}/>}
          {section === 'visites'       && <VisitesSettings       v={settings.visites}       onChange={(p) => update('visites', p)}/>}
          {section === 'dossiers'      && <DossiersSettings      v={settings.dossiers}       onChange={(p) => update('dossiers', p)}/>}
        </div>
      </div>
    </div>
  );
}

// ── Helpers UI ──────────────────────────────────────────────────────────────
function Card({ title, sub, children }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper)', marginBottom: 16, overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--hairline)' }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ padding: 16 }}>{children}</div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 12 }}>
      <span style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600 }}>{label}</span>
      {children}
      {hint && <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>{hint}</span>}
    </label>
  );
}

function Toggle({ value, onChange, label }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10, cursor: 'pointer' }}>
      <span style={{
        width: 32, height: 18, borderRadius: 999,
        background: value ? 'var(--signal)' : 'var(--paper-3)',
        position: 'relative', transition: 'background 120ms',
      }}>
        <span style={{
          width: 14, height: 14, borderRadius: '50%', background: 'var(--paper)',
          position: 'absolute', top: 2, left: value ? 16 : 2,
          transition: 'left 120ms', boxShadow: '0 1px 2px rgba(0,0,0,0.15)',
        }}/>
      </span>
      <input type="checkbox" checked={!!value} onChange={e => onChange(e.target.checked)} style={{ display: 'none' }} />
      <span style={{ fontSize: 12 }}>{label}</span>
    </label>
  );
}

const inp = { padding: '7px 10px', fontSize: 12, border: '1px solid var(--line-2)', borderRadius: 5, background: 'var(--paper-2)', fontFamily: 'inherit', width: '100%', boxSizing: 'border-box' };

// ── P5.1 — CRM ──────────────────────────────────────────────────────────────
function CrmSettings({ v, onChange }) {
  return (
    <>
      <Card title="Stages workflow CEE" sub="Réordonnez et renommez les étapes du Kanban CRM">
        {v.stages.map((s, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '60px 1fr 110px 80px 60px', gap: 8, alignItems: 'center', marginBottom: 6 }}>
            <input value={s.key} onChange={e => {
              const next = [...v.stages]; next[i] = { ...s, key: e.target.value }; onChange({ stages: next });
            }} style={{ ...inp, fontFamily: 'var(--font-mono)', fontSize: 10 }} />
            <input value={s.label} onChange={e => {
              const next = [...v.stages]; next[i] = { ...s, label: e.target.value }; onChange({ stages: next });
            }} style={inp} />
            <input type="color" value={s.color} onChange={e => {
              const next = [...v.stages]; next[i] = { ...s, color: e.target.value }; onChange({ stages: next });
            }} style={{ ...inp, padding: 2, height: 30 }} />
            <button onClick={() => {
              if (i === 0) return;
              const next = [...v.stages]; [next[i-1], next[i]] = [next[i], next[i-1]]; onChange({ stages: next });
            }} style={{ fontSize: 11, padding: '4px 8px', border: '1px solid var(--line-2)', background: 'var(--paper)', borderRadius: 3 }}>↑</button>
            <button onClick={() => {
              const next = v.stages.filter((_, j) => j !== i); onChange({ stages: next });
            }} style={{ fontSize: 11, padding: '4px 8px', border: '1px solid var(--rouge-soft)', background: 'var(--rouge-tint)', color: 'var(--rouge)', borderRadius: 3 }}>🗑</button>
          </div>
        ))}
        <button onClick={() => onChange({ stages: [...v.stages, { key: 'nouveau', label: 'Nouveau', color: '#8A8D90' }] })}
          style={{ marginTop: 8, fontSize: 11, padding: '6px 12px', background: 'var(--signal-tint)', color: 'var(--signal-deep)', border: '1px solid var(--signal-soft)', borderRadius: 4, fontWeight: 600 }}>
          + Ajouter un stage
        </button>
      </Card>

      <Card title="Template email de relance" sub="Variables disponibles : {prenom} {nom} {ref} {signature} {date}">
        <textarea value={v.relanceTemplate} onChange={e => onChange({ relanceTemplate: e.target.value })}
          rows={8} style={{ ...inp, resize: 'vertical', fontFamily: 'var(--font-mono)' }} />
      </Card>

      <Card title="Synchronisation Odoo">
        <Toggle value={v.autoSyncOdoo} onChange={x => onChange({ autoSyncOdoo: x })} label="Sync auto depuis Odoo (incrémental)" />
        <Field label="Intervalle de sync (minutes)" hint="Min 5 min · max 1440 (24h)">
          <input type="number" value={v.syncIntervalMin} onChange={e => onChange({ syncIntervalMin: Math.max(5, Math.min(1440, parseInt(e.target.value) || 30)) })} style={inp} />
        </Field>
      </Card>
    </>
  );
}

// ── P5.2 — Solaire ─────────────────────────────────────────────────────────
function SolaireSettings({ v, onChange }) {
  const c = v.catalogues || {};
  return (
    <>
      <Card title="Catalogue panneaux favoris" sub="Affichés en premier dans le sélecteur Studio solaire">
        {(c.panneauxFavoris || []).map((p, i) => (
          <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
            <input value={p} onChange={e => {
              const next = [...c.panneauxFavoris]; next[i] = e.target.value;
              onChange({ catalogues: { ...c, panneauxFavoris: next } });
            }} style={inp} />
            <button onClick={() => {
              const next = c.panneauxFavoris.filter((_, j) => j !== i);
              onChange({ catalogues: { ...c, panneauxFavoris: next } });
            }} style={{ fontSize: 11, padding: '4px 10px', border: '1px solid var(--rouge-soft)', background: 'var(--rouge-tint)', color: 'var(--rouge)', borderRadius: 3 }}>🗑</button>
          </div>
        ))}
        <button onClick={() => onChange({ catalogues: { ...c, panneauxFavoris: [...(c.panneauxFavoris || []), ''] } })}
          style={{ fontSize: 11, padding: '6px 12px', background: 'var(--signal-tint)', color: 'var(--signal-deep)', border: '1px solid var(--signal-soft)', borderRadius: 4, fontWeight: 600 }}>
          + Ajouter un panneau
        </button>
      </Card>

      <Card title="Onduleur & batterie favoris">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Onduleur favori"><input value={c.onduleurFavori || ''} onChange={e => onChange({ catalogues: { ...c, onduleurFavori: e.target.value } })} style={inp} /></Field>
          <Field label="Batterie favorite"><input value={c.batterieFavorite || ''} onChange={e => onChange({ catalogues: { ...c, batterieFavorite: e.target.value } })} style={inp} /></Field>
        </div>
      </Card>

      <Card title="Tarifs énergie par défaut">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <Field label="Achat EDF (€/MWh)"><input type="number" value={v.tarifs.achatMWh} onChange={e => onChange({ tarifs: { ...v.tarifs, achatMWh: parseFloat(e.target.value) || 0 } })} style={inp} /></Field>
          <Field label="Revente injection (€/MWh)"><input type="number" value={v.tarifs.revente} onChange={e => onChange({ tarifs: { ...v.tarifs, revente: parseFloat(e.target.value) || 0 } })} style={inp} /></Field>
          <Field label="TVA (%)"><input type="number" value={v.tarifs.tva} onChange={e => onChange({ tarifs: { ...v.tarifs, tva: parseFloat(e.target.value) || 0 } })} style={inp} /></Field>
        </div>
      </Card>

      <Card title="FOST par défaut & délégataire">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Code FOST par défaut" hint="Ex: BAR-EN-101 (isolation combles)"><input value={v.fostDefaut} onChange={e => onChange({ fostDefaut: e.target.value })} style={{ ...inp, fontFamily: 'var(--font-mono)' }} /></Field>
          <Field label="Délégataire par défaut"><input value={v.delegataireDefaut} onChange={e => onChange({ delegataireDefaut: e.target.value })} style={inp} /></Field>
        </div>
      </Card>
    </>
  );
}

// ── P5.3 — Communication ───────────────────────────────────────────────────
function CommunicationSettings({ v, onChange }) {
  return (
    <>
      <Card title="Signature email" sub="Apposée automatiquement aux emails sortants composés depuis le module Communication">
        <textarea value={v.signatureEmail} onChange={e => onChange({ signatureEmail: e.target.value })}
          rows={6} style={{ ...inp, resize: 'vertical', fontFamily: 'var(--font-mono)' }} />
      </Card>

      <Card title="Templates pré-définis">
        {Object.entries(v.templates).map(([key, tpl]) => (
          <div key={key} style={{ marginBottom: 14, padding: 12, background: 'var(--paper-2)', borderRadius: 5, border: '1px solid var(--line)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--plasma)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>{key}</div>
            <Field label="Sujet">
              <input value={tpl.subject} onChange={e => onChange({ templates: { ...v.templates, [key]: { ...tpl, subject: e.target.value } } })} style={inp} />
            </Field>
            <Field label="Corps">
              <textarea value={tpl.body} onChange={e => onChange({ templates: { ...v.templates, [key]: { ...tpl, body: e.target.value } } })}
                rows={3} style={{ ...inp, resize: 'vertical' }} />
            </Field>
          </div>
        ))}
      </Card>

      <Card title="Scan boîte mail automatique" sub="Crée automatiquement des fiches prospects (Contact + Organization) pour chaque expéditeur inconnu">
        <Toggle value={v.scanProspectsAuto} onChange={x => onChange({ scanProspectsAuto: x })} label="Scanner automatiquement à intervalle régulier" />
        <Field label="Intervalle (heures)" hint="Min 1h · max 168 (1 semaine)">
          <input type="number" value={v.scanProspectsIntervalH} onChange={e => onChange({ scanProspectsIntervalH: Math.max(1, Math.min(168, parseInt(e.target.value) || 24)) })} style={inp} disabled={!v.scanProspectsAuto} />
        </Field>
      </Card>
    </>
  );
}

// ── P5.4 — Visites ─────────────────────────────────────────────────────────
function VisitesSettings({ v, onChange }) {
  return (
    <>
      <Card title="FOST favoris (suggestions auto)" sub="Codes FOST suggérés en priorité après détection IA d'équipements">
        {(v.fostFavoris || []).map((f, i) => (
          <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
            <input value={f} onChange={e => {
              const next = [...v.fostFavoris]; next[i] = e.target.value; onChange({ fostFavoris: next });
            }} style={{ ...inp, fontFamily: 'var(--font-mono)' }} />
            <button onClick={() => {
              onChange({ fostFavoris: v.fostFavoris.filter((_, j) => j !== i) });
            }} style={{ fontSize: 11, padding: '4px 10px', border: '1px solid var(--rouge-soft)', background: 'var(--rouge-tint)', color: 'var(--rouge)', borderRadius: 3 }}>🗑</button>
          </div>
        ))}
        <button onClick={() => onChange({ fostFavoris: [...(v.fostFavoris || []), 'BAT-TH-XXX'] })}
          style={{ fontSize: 11, padding: '6px 12px', background: 'var(--signal-tint)', color: 'var(--signal-deep)', border: '1px solid var(--signal-soft)', borderRadius: 4, fontWeight: 600 }}>
          + Ajouter un FOST
        </button>
      </Card>

      <Card title="Template rapport visite">
        <Field label="Modèle de rapport">
          <select value={v.rapportTemplate} onChange={e => onChange({ rapportTemplate: e.target.value })} style={inp}>
            <option value="standard">Standard (10 sections)</option>
            <option value="detaille">Détaillé (avec annexes techniques)</option>
            <option value="minimal">Minimal (résumé exécutif uniquement)</option>
          </select>
        </Field>
      </Card>

      <Card title="Pipeline IA">
        <Toggle value={v.pipelineAutoStart} onChange={x => onChange({ pipelineAutoStart: x })} label="Lancer l'analyse IA automatiquement après chaque enregistrement terminé" />
        <Field label="Seuil de confiance minimum" hint="Les détections d'équipements en-dessous de ce seuil ne sont pas validées automatiquement (0 = tout valider, 1 = ne rien valider)">
          <input type="number" step="0.05" min="0" max="1" value={v.extractionConfidenceMin} onChange={e => onChange({ extractionConfidenceMin: Math.max(0, Math.min(1, parseFloat(e.target.value) || 0)) })} style={inp} />
        </Field>
      </Card>
    </>
  );
}

// ── P5.5 — Dossiers CEE ─────────────────────────────────────────────────────
function DossiersSettings({ v, onChange }) {
  return (
    <>
      <Card title="Workflow stages" sub="Ordre des étapes du cycle de vie d'un dossier CEE (de la création au versement de la prime)">
        {v.workflowOrder.map((s, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '40px 1fr 60px 60px', gap: 8, alignItems: 'center', marginBottom: 6 }}>
            <span style={{ fontSize: 12, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)', textAlign: 'center' }}>#{i + 1}</span>
            <input value={s} onChange={e => {
              const next = [...v.workflowOrder]; next[i] = e.target.value; onChange({ workflowOrder: next });
            }} style={inp} />
            <button onClick={() => {
              if (i === 0) return;
              const next = [...v.workflowOrder]; [next[i-1], next[i]] = [next[i], next[i-1]]; onChange({ workflowOrder: next });
            }} style={{ fontSize: 11, padding: '4px 8px', border: '1px solid var(--line-2)', background: 'var(--paper)', borderRadius: 3 }}>↑</button>
            <button onClick={() => {
              onChange({ workflowOrder: v.workflowOrder.filter((_, j) => j !== i) });
            }} style={{ fontSize: 11, padding: '4px 8px', border: '1px solid var(--rouge-soft)', background: 'var(--rouge-tint)', color: 'var(--rouge)', borderRadius: 3 }}>🗑</button>
          </div>
        ))}
        <button onClick={() => onChange({ workflowOrder: [...v.workflowOrder, 'nouveau_stage'] })}
          style={{ marginTop: 8, fontSize: 11, padding: '6px 12px', background: 'var(--signal-tint)', color: 'var(--signal-deep)', border: '1px solid var(--signal-soft)', borderRadius: 4, fontWeight: 600 }}>
          + Ajouter un stage
        </button>
      </Card>

      <Card title="Délégataire">
        <Field label="Délégataire par défaut" hint="Mandataire qui dépose les dossiers au PNCEE">
          <input value={v.delegataireDefaut} onChange={e => onChange({ delegataireDefaut: e.target.value })} style={inp} />
        </Field>
      </Card>

      <Card title="Approbation">
        <Toggle value={v.autoApprove} onChange={x => onChange({ autoApprove: x })} label="Approuver automatiquement les dossiers avec score de cohérence élevé" />
        <Field label="Score de cohérence minimum" hint="0–100 · seuil au-dessus duquel un dossier peut être auto-approuvé sans validation manuelle">
          <input type="number" min="0" max="100" value={v.minCoherenceScore} onChange={e => onChange({ minCoherenceScore: Math.max(0, Math.min(100, parseInt(e.target.value) || 0)) })} style={inp} disabled={!v.autoApprove} />
        </Field>
      </Card>
    </>
  );
}

Object.assign(window, { SettingsPage });
