// schema-re.jsx : schéma unifilaire (demandes d'autoproduction Hydro-Québec, norme E.12-07).
// v3 (5 nov. 2026, règles de JF, maître électricien) :
//   · le schéma représente le devis : il se génère UNIQUEMENT à partir des lignes de la soumission (state.lignes et les groupes
//     de CALC_RE.compute), jamais des valeurs par défaut du parcours ; sans ligne, schéma vide (service et panneau) et avertissement ;
//   · bandeau du haut générique (logo, titre, norme, dossier, version, date), aucune description du système ;
//   · cartouche populée selon les composantes présentes, sans ligne de signature ni de date, sans mention du logiciel ;
//   · le champ PV et l'arrêt rapide (RSD, EPO, MCI, ProJoy, Tigo) se raccordent à l'onduleur (ou au Powerwall 3), jamais à la
//     passerelle ; câble de communication entre chaque onduleur (ou chaque Powerwall 3) et la passerelle ; le routeur Wi-Fi du client
//     se branche dans le premier Powerwall 3 (un seul lien, même avec 2 ou 3 Powerwall), jamais dans la passerelle ;
//   · Tesla (JF, 5 nov. 2026) : deux disjoncteurs cadenassables, chacun une composante : l'un part du panneau principal (vers la
//     passerelle ; en maison complète, entre la passerelle et le panneau principal), l'autre part de la passerelle et alimente le
//     Powerwall 3 (un par Powerwall, 60 A pour un Powerwall 3 de 11,5 kW) ; sans panneau de charges critiques ni embase combinée,
//     la Gateway 3 contient les charges critiques et sert de panneau de secours (aucun panneau de secours ajouté) ;
//   · Lux Power et Volthium : aucun sectionneur CC entre les batteries et l'onduleur (onduleur, busbar s'il y en a un, batteries) ;
//   · câblage d'une seule couleur, tracé orthogonal continu par un routeur en canaux (aucun segment coupé ni trait qui traverse un
//     appareil), ports précis, jonctions marquées d'un point, ponts en demi-cercle aux croisements inévitables ;
//   · aucun pictogramme de cadenas : un sectionneur ou un disjoncteur cadenassable est une composante à part entière ;
//   · palette avec recherche instantanée (nom, groupe, mots-clés, sans accents ni casse), ajout par clic ou glisser-déposer sur la scène ;
//   · glisser-déposer fluide (requestAnimationFrame), aimantation 10 px, sélection multiple (Maj + clic), flèches (Maj = 10 px).
// Généré depuis une soumission ou une fiche client, retouches à la main conservées, modèles, export PDF (11 × 17 et lettre) et PNG,
// enregistrement dans la soumission et dans le dossier client, analyse d'une facture Hydro-Québec par le worker
// (POST /raycast/hq/analyser), import des anciens préréglages JSON du builder.
//
// Exposé : window.SchemaRE = { DEFAUT, depuisSoumission, depuisFiche, depuisPreset, depuisLignes, construire, cabler, topologie, Page,
//                              Studio, exporterPNG, exporterPDF, ... }
//          window.SchemaBoutonRE ({ state, setState })        bouton « Schéma unifilaire » dans la soumission
//          window.SchemaBoutonFicheRE ({ prefill, r })          bouton « Schéma unifilaire » dans la fiche client
//
// MODÈLE (JSON, sérialisable dans state.schema_unifilaire) :
// {
//   version: 3,
//   client:  { nom, adresse1, adresse2, telephone, courriel },
//   hq:      { numero_client, numero_contrat, numero_compteur, dossier, tarif, titulaire },
//   service: { calibre: 100 | 200 | 320 | 400, tension: "120/240 V", embase: "standard" | "meter_main" },
//   systeme: { objectif: "vide" | "service" | "borne" | "solaire" | "batterie" | "solaire_batterie", marque: "tesla" | "fox" | "sigenergy" | "lux",
//              nb (Powerwall ou modules), nb_gateways (0..2), expansion (nombre), secours: "aucun" | "base" (charges critiques dans la
//              passerelle) | "partiel" (panneau de charges critiques) | "complet",
//              panneau_critique: 100 | 60, onduleur, nb_onduleurs, onduleur_nom, onduleur_kw, batterie_nom, kwh },
//   pv:      { nb, watts, modele, rsd: "mci" | "projoy" | "tigo" | "optimiseur" | "aucun", nb_rsd },
//   bornes:  [{ modele, amperes }],
//   extras:  [{ cle: "sect_ext" | "sect_ac" | "busbar" | "enceinte" | "panneau_sec" | "generatrice" | "ats" | "inlet" | "dongle" | "compteur_distant", nom, qty }],
//   options: { malt, epo, routeur, mesurage_net },
//   source:  { lignes, avertissements: [] }                         (lu sur la soumission)
//   retouches: { positions: { [id]: { dx, dy } }, tailles: { [id]: { w, h } }, masques: [id], noms: { [id]: "texte" }, cotes: { [id]: "texte" },
//                legendes: { [id]: [nom, detail, norme] }, ordre: [id], ajouts: [{ id, cle (palette), type, x, y, w, h, nom, cote, leg }],
//                cables: [{ id, de, a, deCote, aCote, genre: "principal"|"comm", calibre, coudes: [{ x, y }] }],
//                cables_retires: ["de>a"], annotations: [{ id, x, y, texte, taille }] },
//   meta:    { dossier, version, date }
// }
(function () {
  const { useState, useEffect, useMemo, useRef } = React;
  const PAGE = { w: 1632, h: 1056 };                       // 11 × 17 paysage à 96 ppp
  const ZONE = { x: 36, y: 128, w: 1160, h: 620 };          // dessin
  const LEG = { x: 1216, y: 128, w: 380, h: 620 };          // légende
  const CART = { x: 36, y: 768, w: 1560, h: 256 };          // cartouche
  const ENTREPRISE = { nom: "Raycom Électrique inc.", adresse: "3321 av. de la Gare, bureau 112, Mascouche (Québec) J7K 0X7", tel: "450 474-8470", courriel: "info@raycomelectrique.com", site: "www.raycomelectrique.com", rbq: "RBQ 5590-9402-01", maitre: "Jean-François Rayle, maître électricien (CMEQ)" };
  // Une seule couleur pour tout le câblage (puissance 1,6 px, communication en pointillé fin de la même couleur)
  const FIL = { couleur: "#111827", puissance: 1.6, comm: 1.1, tirets: "5 3.5" };
  const COULEUR = { trait: "#111827", pv: "#111827", comm: "#111827", secours: "#0a6fc8", boite: "#ffffff", bleu: "#0a3a8c", gris: "#475569", ui: "#0a6fc8" };

  const auj = () => new Intl.DateTimeFormat("fr-CA", { timeZone: "America/Toronto", year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date());
  const DEFAUT = () => ({
    version: 3,
    client: { nom: "", adresse1: "", adresse2: "", telephone: "", courriel: "" },
    hq: { numero_client: "", numero_contrat: "", numero_compteur: "", dossier: "", tarif: "D", titulaire: "" },
    service: { calibre: 200, tension: "120/240 V", embase: "standard" },
    systeme: { objectif: "vide", marque: "tesla", nb: 0, nb_gateways: 0, expansion: 0, secours: "aucun", panneau_critique: 100, onduleur: "auto", nb_onduleurs: 0, onduleur_nom: "", onduleur_kw: 0, batterie_nom: "", kwh: 0 },
    pv: { nb: 0, watts: 500, modele: "", rsd: "aucun", nb_rsd: 0 },
    bornes: [],
    extras: [],
    options: { malt: true, epo: true, routeur: true, mesurage_net: true },
    source: { lignes: 0, avertissements: [] },
    retouches: retouchesDefaut(),
    meta: { dossier: "", version: "v1", date: auj() },
  });

  // ───────────────────────── Spécifications par marque ─────────────────────────
  const MARQUES = {
    tesla: { nom: "Tesla", batterie: "Powerwall 3", kwh: 13.5, kw: 11.5, dim: "Tesla Gateway 3", dim_calibre: 200, disj_a: 60, onduleur: "intégré au Powerwall 3", cert: "UL 1741-SB · UL 9540 · IEEE 2030.5", rsd: "mci", par_rsd: 3, expansion_kwh: 13.5 },
    fox: { nom: "Fox ESS", batterie: "module EQ4000", kwh: 3.97, kw: 11.4, dim: "Fox ESS Hub G2", dim_calibre: 200, onduleur: "Fox ESS AIO 11,4 kW", cert: "UL 1741-SB · UL 9540", rsd: "projoy", par_rsd: 12, expansion_kwh: 0 },
    sigenergy: { nom: "Sigenergy", batterie: "module SigenStor", kwh: 9.04, kw: 11.5, dim: "Sigenergy LoadHub", dim_calibre: 200, onduleur: "Sigenergy Energy Controller 11,5 kW", cert: "UL 1741-SB · UL 9540", rsd: "tigo", par_rsd: 2, expansion_kwh: 0 },
    lux: { nom: "Lux Power", batterie: "Volthium 100 Ah", kwh: 5.1, kw: 12, dim: "Boîtier de transfert EPS (Lux Power)", dim_calibre: 200, onduleur: "Lux Power LXP-LB-US 12K", cert: "UL 1741-SB · UL 9540", rsd: "optimiseur", par_rsd: 1, expansion_kwh: 0 },
  };
  const ONDULEURS = { fox_h1: { nom: "Fox ESS H1 11,4 kW", kw: 11.4 }, fox_h1_96: { nom: "Fox ESS H1 9,6 kW", kw: 9.6 }, fox_aio: { nom: "Fox ESS AIO 11,4 kW", kw: 11.4 }, fox_aio_96: { nom: "Fox ESS AIO 9,6 kW", kw: 9.6 },
    lux_lxp: { nom: "Lux Power LXP-LB-US 12K", kw: 12 }, lux_lxp10: { nom: "Lux Power LXP 10K", kw: 10 }, lux_gen13: { nom: "Lux Power GEN-LB-US 13K", kw: 13 }, lux_gen16: { nom: "Lux Power GEN-LB-US 16K", kw: 16 },
    lux_sna6: { nom: "Lux Power SNA-US 6K (hors réseau)", kw: 6, hors_reseau: true }, lux_sna12: { nom: "Lux Power SNA-US 12K (hors réseau)", kw: 12, hors_reseau: true }, sig_ctrl: { nom: "Sigenergy Energy Controller 11,5 kW", kw: 11.5 } };
  const RSD = { mci: { nom: "MCI Tesla (arrêt rapide)", par: 3 }, projoy: { nom: "ProJoy RSD (arrêt rapide)", par: 12 }, tigo: { nom: "Tigo TS4 (arrêt rapide)", par: 2 }, optimiseur: { nom: "Optimiseurs Tigo (arrêt rapide)", par: 3 }, aucun: null };
  const r1 = (x) => Math.round(x * 10) / 10;
  const fmt = (n) => Number(n).toLocaleString("fr-CA");
  const kwPv = (m) => r1((Number(m.pv.nb) || 0) * (Number(m.pv.watts) || 0) / 1000);
  const stockageKwh = (m) => { const s = MARQUES[m.systeme.marque] || MARQUES.tesla; if (Number(m.systeme.kwh) > 0) return r1(Number(m.systeme.kwh)); return r1((Number(m.systeme.nb) || 0) * s.kwh + (Number(m.systeme.expansion) || 0) * s.expansion_kwh); };
  const kwOnduleur = (m) => { const s = MARQUES[m.systeme.marque] || MARQUES.tesla; const o = ONDULEURS[m.systeme.onduleur]; return Number(m.systeme.onduleur_kw) || (o ? o.kw : s.kw); };
  const kwCa = (m) => { if (m.systeme.marque === "tesla" && m.systeme.objectif !== "solaire") return r1((Number(m.systeme.nb) || 0) * MARQUES.tesla.kw); return r1((Number(m.systeme.nb_onduleurs) || 0) * kwOnduleur(m)); };

  /** Topologie HQ dérivée du modèle (sert au formulaire ; le bandeau du schéma reste générique). */
  function topologie(m) {
    const o = m.systeme.objectif;
    if (o === "vide") return { id: "vide", titre: "", sous: "Aucune composante", figure: "" };
    if (o === "service") return { id: "service", titre: "", sous: "Entrée électrique", figure: "" };
    if (o === "borne") return { id: "borne", titre: "", sous: "Borne de recharge · aucune production", figure: "" };
    if (o === "solaire") return { id: "mesurage_net", titre: "", sous: "Photovoltaïque sans stockage", figure: "" };
    const sec = m.systeme.secours;
    const base = o === "batterie" ? "Stockage sans production" : "Photovoltaïque avec stockage";
    const s = sec === "complet" ? "secours complet" : sec === "partiel" ? "secours partiel" : sec === "base" ? (m.systeme.marque === "tesla" ? "secours partiel, charges critiques dans la passerelle" : "secours de base") : "sans secours";
    return { id: o === "batterie" ? "stockage" : "autoproduction", titre: "", sous: `${base} · ${s}`, figure: "" };
  }

  const PALETTE = [
    { cle: "reseau_hq", groupe: "Service HQ", type: "hq", nom: "Réseau Hydro-Québec", w: 60, h: 60, leg: ["Réseau Hydro-Québec · point de raccordement", "Source · BT 120/240 V · 1Ø · réseau distribution", ""] },
    { cle: "compteur_hq", groupe: "Service HQ", type: "compteur", nom: "Compteur HQ", w: 100, h: 68, leg: ["Compteur Hydro-Québec · communicant bidirectionnel", "Mesurage net · communicant · bidirectionnel HQ", ""] },
    { cle: "malt", groupe: "Mise à la terre et sécurité", type: "malt", nom: "Mise à la terre", w: 30, h: 26, leg: ["Mise à la terre", "Conducteur de mise à la terre · conforme HQ · 6 AWG min.", ""] },
    { cle: "coffret_200a_disj22ka", groupe: "Service HQ", type: "coffret", nom: "Coffret branchement 200A · disj. 22kA cadenass.", w: 110, h: 68, leg: ["Coffret branchement 200A · disjoncteur 22 kAIC cadenass.", "200 A · 120/240V · 1Ø · disj. princ. 22 kAIC cadenass.", ""] },
    { cle: "coffret_200a_sectfus", groupe: "Service HQ", type: "coffret", nom: "Coffret branchement 200A · sect. fus.", w: 110, h: 68, leg: ["Coffret branchement 200A · sect. à fusibles cadenass.", "200 A · 120/240V · 1Ø · sect. à fusibles cadenassable", ""] },
    { cle: "coffret_400a_disj", groupe: "Service HQ", type: "coffret", nom: "Coffret branchement 400A · disj. 400A", w: 110, h: 68, leg: ["Coffret de branchement 400A · disjoncteur principal 400A", "400 A · 120/240 V · disj. principal 400 A cadenassable", ""] },
    { cle: "armoire_mesurage", groupe: "Service HQ", type: "armoire", nom: "Armoire de mesurage HQ (TC, sans compteur)", w: 100, h: 90, leg: ["Armoire de mesurage Hydro-Québec · transformateurs de courant", "Armoire de mesurage HQ (TC) · compteur à part", ""] },
    { cle: "coffret_branchement", groupe: "Service HQ", type: "coffret", nom: "Coffret branchement 400A · sect. fus.", w: 110, h: 68, leg: ["Coffret de branchement principal 400A · sect. fusibles cadenass.", "400A · 120/240V · 1Ø · F400 sect. fusibles cadenass. (Art. 84-024)", ""] },
    { cle: "embase_combo_200a", groupe: "Service HQ", type: "compteur", nom: "Embase de compteur combinée 200 A (disj. principal)", w: 100, h: 68, leg: ["Embase de compteur combinée 200 A avec disjoncteur principal", "Approuvée Hydro-Québec · secours maison complète (alimente la passerelle)", "22 kA · NEMA 3R"] },
    { cle: "panneau_200a_section_60a", groupe: "Protection et distribution", type: "panneau", nom: "Panneau 200 A combiné, section de secours 60 A", w: 130, h: 96, leg: ["Panneau 200 A combiné avec section de secours 60 A", "200 A · 120/240 V · section secourue 60 A (charges critiques)", ""] },
    { cle: "embase_320a", groupe: "Service HQ", type: "coffret", nom: "Embase 320A (1×200+1×100)", w: 110, h: 68, leg: ["Embase 320A (compteur + 1×200A + 1×100A)", "Boîte compteur 320A · 2 panneaux : 1×200A + 1×100A · 120/240V · 1Ø", ""] },
    { cle: "panneau_400a", groupe: "Service HQ", type: "coffret", nom: "Service 400A", w: 110, h: 68, leg: ["Service de branchement 400A", "400A · 120/240V · 1Ø · service principal commercial", ""] },
    { cle: "panneau_100a", groupe: "Protection et distribution", type: "panneau", nom: "Panneau secondaire 100A", w: 130, h: 96, leg: ["Panneau de distribution 100A", "100 A · 120/240 V · 1Ø", ""] },
    { cle: "panneau_200a", groupe: "Protection et distribution", type: "panneau", nom: "Panneau principal 200A · disj. standard", w: 130, h: 96, leg: ["Panneau de distribution principal 200A · disjoncteur standard", "200A · 120/240V · 1Ø · panneau de distribution principal", ""] },
    { cle: "panneau_200a_disj22ka", groupe: "Protection et distribution", type: "panneau", nom: "Panneau principal 200A · disj 22kA cadenass.", w: 130, h: 96, leg: ["Panneau de distribution principal 200A · disj. 22 kAIC cadenass.", "200 A · 120/240 V · 1Ø · disj. principal 22 kAIC cadenass. (Art. 84-024)", ""] },
    { cle: "panneau_200a_bk60_principal", groupe: "Protection et distribution", type: "panneau", nom: "Panneau principal 200A + section backup 60A", w: 130, h: 96, leg: ["Panneau principal 200A avec section backup 60A intégrée", "200A · principal + section 60A backup intégrée (charges critiques)", ""] },
    { cle: "panneau_200a_bk60_secondaire", groupe: "Protection et distribution", type: "panneau", nom: "Panneau secondaire 200A + section backup 60A", w: 130, h: 96, leg: ["Panneau secondaire 200A avec section backup 60A intégrée", "Sous-tableau 200A + section 60A backup intégrée", ""] },
    { cle: "panneau_generatrice_3p", groupe: "Protection et distribution", type: "panneau", nom: "Panneau de génératrice · disj. 3P", w: 130, h: 96, leg: ["Panneau de génératrice triphasé · disjoncteurs 3P", "Tableau commutation génératrice · disj. 3P (HQ + gén.) · charges essentielles", ""] },
    { cle: "panneau_charges_critiques_60a", groupe: "Protection et distribution", type: "pcc", nom: "Panneau charges critiques 60A", w: 110, h: 80, leg: ["Panneau de charges critiques 60A", "60 A · 120/240 V · 1Ø · sous-tableau backup · charges critiques (alim. DIM)", ""] },
    { cle: "panneau_charges_critiques_100a", groupe: "Protection et distribution", type: "pcc", nom: "Panneau charges critiques 100A", w: 110, h: 80, leg: ["Panneau de charges critiques 100A", "100 A · 120/240 V · 1Ø · sous-tableau backup · charges critiques", ""] },
    { cle: "sous_panneau_100a_ext", groupe: "Protection et distribution", type: "panneau", nom: "Sous-panneau 100A ext. (non secouru)", w: 130, h: 96, leg: ["Sous-panneau 100A extérieur (non secouru)", "100 A · 120/240 V · NEMA 3R · non secouru", ""] },
    { cle: "panneau_charges_critiques_transfert", groupe: "Protection et distribution", type: "pcc", nom: "Panneau charges critiques · transfert 3P", w: 110, h: 80, leg: ["Panneau de charges critiques · interrupteur de transfert tripolaire (2P+N)", "60 A · 120/240 V · 1Ø · transfert 3P (L1-L2-N) · alim. DIM / génératrice · charges critiques", ""] },
    { cle: "prise_generatrice", groupe: "Protection et distribution", type: "inlet", nom: "Prise génératrice (inlet)", w: 60, h: 44, leg: ["Prise d'entrée génératrice portative (inlet)", "Inlet 30/50 A · 120/240 V · 1Ø · NEMA L14-30 ou 14-50 · vers interrupteur de transfert", ""] },
    { cle: "panneau_gen", groupe: "Protection et distribution", type: "panneau", nom: "Panneau secondaire générique", w: 130, h: 96, leg: ["Panneau secondaire / sous-panneau", "Sous-panneau de distribution · configurable", ""] },
    { cle: "auget", groupe: "Service HQ", type: "auget", nom: "Auget de répartition", w: 120, h: 60, leg: ["Auget de répartition 400A", "400A · 120/240V · 1Ø · barre commune vers 2 panneaux 200A", ""] },
    { cle: "sect_nf_60a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. s/fus. 60A", w: 70, h: 44, leg: ["Sectionneur sans fusible 60A", "60 A · cadenassable · isolation visible · Art. 84-024 CSA C22.10", ""] },
    { cle: "sect_nf_100a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. s/fus. 100A", w: 70, h: 44, leg: ["Sectionneur sans fusible 100A", "100 A · cadenassable · isolation visible · Art. 84-024 CSA C22.10", ""] },
    { cle: "sect_nf_200a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. s/fus. 200A", w: 70, h: 44, leg: ["Sectionneur sans fusible 200A", "200 A · cadenassable · isolation visible · Art. 84-024 CSA C22.10", ""] },
    { cle: "sect_fus_60a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. fusibles 60A", w: 70, h: 44, leg: ["Sectionneur à fusibles 60A", "60 A · cadenassable · à fusibles · Art. 84-024 CSA C22.10", ""] },
    { cle: "sect_fus_100a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. fusibles 100A", w: 70, h: 44, leg: ["Sectionneur à fusibles 100A", "100 A · cadenassable · à fusibles · Art. 84-024 CSA C22.10", ""] },
    { cle: "sect_fus_200a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sect. fusibles 200A", w: 70, h: 44, leg: ["Sectionneur à fusibles 200A", "200 A · cadenassable · à fusibles · Art. 84-024 CSA C22.10", ""] },
    { cle: "sectionneur_fusible", groupe: "Protection et distribution", type: "sectionneur", nom: "Sectionneur à fusibles (générique)", w: 70, h: 44, leg: ["Sectionneur à fusibles cadenassable", "Cadenassable · Art. 84-024 CSA C22.10", ""] },
    { cle: "disjoncteur_2p", groupe: "Protection et distribution", type: "disjoncteur", nom: "Disjoncteur 2P", w: 44, h: 30, leg: ["Disjoncteur 2P cadenassable", "2P · 120/240 V · cadenassable", ""] },
    { cle: "disj_2p_200a_22ka", groupe: "Protection et distribution", type: "disjoncteur", nom: "Disjoncteur 2P 200A · 22 kAIC cadenass.", w: 44, h: 30, leg: ["Disjoncteur cadenassable 2P 200A · 22 kAIC", "200 A · 2 pôles · 22 kAIC · cadenassable Art. 84-024 CSA C22.10", ""] },
    { cle: "disjoncteur_2p_cadenassable", groupe: "Protection et distribution", type: "disjoncteur", nom: "Disjoncteur 2P 240V · cadenassable (padlock)", w: 44, h: 30, leg: ["Disjoncteur bipolaire 240 V avec dispositif de cadenassage (padlock)", "2P · 240 V · cadenassable (padlock)", ""] },
    { cle: "sect_3p", groupe: "Protection et distribution", type: "sectionneur", nom: "Sectionneur 3P (2P+N) · cadenassable", w: 70, h: 44, leg: ["Sectionneur tripolaire (2 pôles + neutre commuté) cadenassable", "3P (2P+N) · 120/240 V · cadenassable", ""] },
    { cle: "disjoncteur_3p", groupe: "Protection et distribution", type: "disjoncteur", nom: "Disjoncteur 3P", w: 44, h: 30, leg: ["Disjoncteur 3P (triphasé)", "Disjoncteur triphasé · commercial 120/208V ou 347/600V", ""] },
    { cle: "parafoudre", groupe: "Mise à la terre et sécurité", type: "parafoudre", nom: "Parafoudre", w: 44, h: 44, leg: ["Parafoudre (SPD)", "Surge Protection Device · protection contre surtensions", ""] },
    { cle: "transfo_hq", groupe: "Service HQ", type: "transfo", nom: "Transformateur HQ", w: 70, h: 70, leg: ["Transformateur HQ (HT/BT)", "Transformateur réseau Hydro-Québec · commercial", ""] },
    { cle: "ats", groupe: "Protection et distribution", type: "ats", nom: "ATS (Commutation automatique)", w: 90, h: 60, leg: ["ATS · Commutation automatique HQ/génératrice", "Automatic transfer switch · bascule HQ ↔ génératrice", ""] },
    { cle: "generatrice", groupe: "Protection et distribution", type: "generatrice", nom: "Génératrice", w: 70, h: 70, leg: ["Génératrice (groupe électrogène)", "Source secondaire · groupe électrogène · diesel/gaz", ""] },
    { cle: "rsd", groupe: "Solaire", type: "rsd", nom: "Arrêt rapide RSD", w: 130, h: 26, leg: ["Module RSD (Rapid Shut Down)", "Arrêt rapide générique · CSA C22.10:26 Art. 64-218 · SunSpec", ""] },
    { cle: "rsd_projoy", groupe: "Solaire", type: "rsd", nom: "Arrêt rapide ProJoy PEFS (Fox ESS)", w: 130, h: 26, leg: ["Arrêt rapide ProJoy PEFS-PL (compatible Fox ESS)", "Arrêt rapide SunSpec · commandé par l'onduleur", "Art. 64-218 CSA C22.10:26"] },
    { cle: "rsd_tigo", groupe: "Solaire", type: "rsd", nom: "Arrêt rapide Tigo TS4-A-2F (1 par 2 panneaux)", w: 130, h: 26, leg: ["Arrêt rapide Tigo TS4-A-2F, 1 par 2 panneaux (SunSpec)", "Compatible Sigenergy et Fox ESS · commandé par l'onduleur", "Art. 64-218 CSA C22.10:26"] },
    { cle: "tigo_optimiseur", groupe: "Solaire", type: "rsd", nom: "Optimiseur Tigo TS4-A-O (1 par 3 panneaux)", w: 130, h: 26, leg: ["Optimiseur Tigo TS4-A-O, 1 par 3 panneaux", "Optimisation et arrêt rapide des modules", "Art. 64-218 CSA C22.10:26"] },
    { cle: "mci_tesla", groupe: "Solaire", type: "rsd", nom: "Tesla MCI-2 (interrupteur mi-circuit)", w: 130, h: 26, leg: ["Interrupteur mi-circuit Tesla MCI-2 (arrêt rapide PV)", "Un par chaîne solaire raccordée au Powerwall 3", "Art. 64-218 CSA C22.10:26"] },
    { cle: "bouton_epo", groupe: "Mise à la terre et sécurité", type: "epo", nom: "Bouton EPO (arrêt urgence PV)", w: 34, h: 34, leg: ["Bouton poussoir d'arrêt d'urgence PV (EPO)", "Arrêt d'urgence PV · accessible et identifié", ""] },
    { cle: "module_pv", groupe: "Solaire", type: "pv", nom: "Module PV générique", w: 170, h: 78, leg: ["Module photovoltaïque générique", "Module PV · 400-550 W", ""] },
    { cle: "module_thornova", groupe: "Solaire", type: "pv", nom: "Module Thornova TS-BBT54 (500 W bif.)", w: 170, h: 78, leg: ["Module PV Thornova TS-BBT54-G11 500 W bifacial", "500 W · bifacial", ""] },
    { cle: "module_longi", groupe: "Solaire", type: "pv", nom: "Module LONGi LR8-54HGBB-500M (500 W)", w: 170, h: 78, leg: ["Module PV LONGi Hi-MO 7 LR8-54HGBB-500M · 500 W", "500 W · bifacial double verre · CSA 61730 et 61215", "CSA C22.2 no 61730"] },
    { cle: "module_longi_625", groupe: "Solaire", type: "pv", nom: "Module LONGi LR8-66HGD-625M (625 W)", w: 170, h: 78, leg: ["Module PV LONGi Hi-MO 7 LR8-66HGD-625M · 625 W", "625 W · bifacial · CSA 61730 et 61215", "CSA C22.2 no 61730"] },
    { cle: "module_ja_620", groupe: "Solaire", type: "pv", nom: "Module JA Solar JAM66D45-620/LB (620 W)", w: 170, h: 78, leg: ["Module PV JA Solar JAM66D45-620/LB · 620 W", "620 W · bifacial TOPCon · CSA 61730 et 61215", "CSA C22.2 no 61730"] },
    { cle: "combiner_box", groupe: "Solaire", type: "jonction", nom: "Boîte de jonction PV (combiner box)", w: 80, h: 50, leg: ["Boîte de jonction PV (combiner box)", "Combiner box · regroupement de strings PV · avec parafoudre/fusibles", ""] },
    { cle: "foxess_h1", groupe: "Onduleurs", type: "onduleur", nom: "Fox ESS H1 11,4 kW (mural)", w: 100, h: 84, leg: ["Onduleur hybride Fox ESS H1 11,4 kW, mural", "Hybride 11,4 kW CA · batteries CM4000 / CS4000 · UL 1741-SB · IEEE 2030.5", "UL 1741-SB"] },
    { cle: "foxess_h1_96", groupe: "Onduleurs", type: "onduleur", nom: "Fox ESS H1 9,6 kW (mural)", w: 100, h: 84, leg: ["Onduleur hybride Fox ESS H1 9,6 kW, mural", "Hybride 9,6 kW CA · batteries CM4000 / CS4000 · UL 1741-SB", "UL 1741-SB"] },
    { cle: "foxess_aio_96", groupe: "Onduleurs", type: "onduleur", nom: "Fox ESS AIO 9,6 kW (sur pile EQ4000)", w: 100, h: 84, leg: ["Onduleur hybride Fox ESS AIO 9,6 kW sur pile EQ4000", "Hybride 9,6 kW CA · multimode", "UL 1741-SB"] },
    { cle: "foxess_eq4000", groupe: "Stockage et passerelles", type: "module", nom: "Fox ESS EQ4000 · 3,97 kWh (pile AIO)", w: 110, h: 24, leg: ["Batterie Fox ESS EQ4000 · 3,97 kWh par module", "LFP · empilée sous l'AIO · réf. FRK-5600743", "UL 9540 · UL 1973"] },
    { cle: "foxess_cm4000", groupe: "Stockage et passerelles", type: "module", nom: "Fox ESS CM4000 maître · 4 kWh (H1)", w: 110, h: 24, leg: ["Batterie Fox ESS CM4000 maître · 4 kWh", "LFP · module maître de la pile de l'onduleur H1", "UL 9540 · UL 1973"] },
    { cle: "foxess_cs4000", groupe: "Stockage et passerelles", type: "module", nom: "Fox ESS CS4000 esclave · 4 kWh (H1)", w: 110, h: 24, leg: ["Batterie Fox ESS CS4000 esclave · 4 kWh", "LFP · module esclave de la pile de l'onduleur H1", "UL 9540 · UL 1973"] },
    { cle: "foxess_hub_g2", groupe: "Stockage et passerelles", type: "hub", nom: "FoxESS Hub G2 (DIM)", w: 110, h: 84, leg: ["DIM · FoxESS Hub G2", "Dispositif d'interconnexion microréseau · UL 1741 CRD multimode · IEEE 2030.5", ""] },
    { cle: "foxess_battery", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS HV2600 (module batterie)", w: 110, h: 24, leg: ["Module batterie FoxESS HV2600", "2.6 kWh par module · empilable jusqu'à 12.96 kWh", ""] },
    { cle: "foxess_ecs", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS ECS (stack 2.6-13.0 kWh)", w: 110, h: 24, leg: ["Batterie FoxESS ECS stack (modules HV2600)", "Stack 2-5 modules · 5.2 à 13.0 kWh · LFP · 51-60V", ""] },
    { cle: "foxess_aio_h1", groupe: "Onduleurs", type: "onduleur", nom: "Fox ESS AIO 11,4 kW (sur pile EQ4000)", w: 100, h: 84, leg: ["Onduleur hybride Fox ESS AIO H1 11,4 kW sur pile EQ4000", "Hybride 11,4 kW CA · réf. FRK-5101083 · multimode · IEEE 2030.5", "UL 1741-SB"] },
    { cle: "foxess_aio_bat_5", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS AIO BAT 5.2 kWh (2 modules)", w: 110, h: 24, leg: ["Batterie FoxESS AIO Flex · 5.2 kWh (2× HV2600)", "2 modules HV2600 · 5.2 kWh utilisable · LFP", ""] },
    { cle: "foxess_aio_bat_8", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS AIO BAT 7.8 kWh (3 modules)", w: 110, h: 24, leg: ["Batterie FoxESS AIO Flex · 7.8 kWh (3× HV2600)", "3 modules HV2600 · 7.8 kWh utilisable · LFP", ""] },
    { cle: "foxess_aio_bat_10", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS AIO BAT 10.4 kWh (4 modules)", w: 110, h: 24, leg: ["Batterie FoxESS AIO Flex · 10.4 kWh (4× HV2600)", "4 modules HV2600 · 10.4 kWh utilisable · LFP", ""] },
    { cle: "foxess_aio_bat_13", groupe: "Stockage et passerelles", type: "module", nom: "FoxESS AIO BAT 13.0 kWh (5 modules)", w: 110, h: 24, leg: ["Batterie FoxESS AIO Flex · 13.0 kWh (5× HV2600)", "5 modules HV2600 · 13.0 kWh utilisable · LFP", ""] },
    { cle: "powerwall_3", groupe: "Stockage et passerelles", type: "powerwall", nom: "Tesla Powerwall 3 (onduleur + batterie)", w: 62, h: 118, leg: ["Tesla Powerwall 3 · onduleur hybride 11.5 kW + batterie 13.5 kWh intégrés", "13.5 kWh LFP + onduleur 11.5 kW AC · compatible PV jusqu'à 20 kW DC · UL 9540", ""] },
    { cle: "powerwall_3_expansion", groupe: "Stockage et passerelles", type: "expansion", nom: "Tesla Powerwall 3 Expansion (13,5 kWh)", w: 62, h: 118, leg: ["Batterie d'expansion Tesla Powerwall 3 · 13,5 kWh", "13,5 kWh · couplée en CC au Powerwall 3 (harnais d'expansion)", "UL 9540"] },
    { cle: "tesla_remote_meter", groupe: "Communication", type: "cpt_distant", nom: "Tesla Remote Meter (compteur distant 200 A)", w: 70, h: 34, leg: ["Compteur distant Tesla Remote Meter Kit 200 A (2 CT)", "Mesure de la consommation ou de la production · RS485 vers la passerelle", ""] },
    { cle: "gateway_3", groupe: "Stockage et passerelles", type: "gateway", nom: "Tesla Gateway 3 (DIM)", w: 110, h: 120, leg: ["DIM · Tesla Gateway 3", "Dispositif d'interconnexion microréseau · UL 1741 CRD multimode", ""] },
    { cle: "tesla_wall_connector", groupe: "Bornes", type: "borne", nom: "Tesla Wall Connector Gen 3 (48 A)", w: 52, h: 80, leg: ["Tesla Wall Connector Gen 3 (borne VE niv. 2)", "240 V · 48 A · connecteur NACS · circuit 2P 60 A", "UL 2594"] },
    { cle: "tesla_uwc", groupe: "Bornes", type: "borne", nom: "Tesla Universal Wall Connector (48 A)", w: 52, h: 80, leg: ["Tesla Universal Wall Connector (NACS + J1772)", "240 V · 48 A · circuit 2P 60 A", "UL 2594"] },
    { cle: "flo_home_x3", groupe: "Bornes", type: "borne", nom: "FLO Home X3", w: 52, h: 80, leg: ["Borne FLO Home X3 (niveau 2)", "240 V · J1772 · circuit dédié 2P", "UL 2594"] },
    { cle: "flo_home_x8", groupe: "Bornes", type: "borne", nom: "FLO Home X8 (80 A)", w: 52, h: 80, leg: ["Borne FLO Home X8 (niveau 2)", "240 V · 80 A · 19,2 kW · J1772 · circuit 2P 100 A", "UL 2594"] },
    { cle: "wallbox_pulsar", groupe: "Bornes", type: "borne", nom: "Wallbox Pulsar Plus J1772 (40 A)", w: 52, h: 80, leg: ["Borne Wallbox Pulsar Plus J1772", "240 V · 40 A · circuit 2P 50 A", "UL 2594"] },
    { cle: "wallbox_nacs", groupe: "Bornes", type: "borne", nom: "Wallbox 48 A NACS", w: 52, h: 80, leg: ["Borne Wallbox 48 A NACS", "240 V · 48 A · circuit 2P 60 A", "UL 2594"] },
    { cle: "evduty_evc48", groupe: "Bornes", type: "borne", nom: "EV Duty EVC48 (48 A)", w: 52, h: 80, leg: ["Borne EV Duty EVC48", "240 V · 48 A · circuit 2P 60 A", "UL 2594"] },
    { cle: "flo_core_max", groupe: "Bornes", type: "borne", nom: "FLO CoRe+ MAX (commerciale)", w: 52, h: 80, leg: ["Borne commerciale FLO CoRe+ MAX", "208/240 V · jusqu'à 80 A · niveau 2 commercial", "UL 2594"] },
    { cle: "sigen_inverter", groupe: "Onduleurs", type: "onduleur", nom: "Sigenergy Energy Controller 11,5 kW", w: 100, h: 84, leg: ["Onduleur Sigenergy Contrôleur 11.5 kW (PG Controller 11.5)", "Hybride 11.5 kW · multimode · UL 1741-SB · CSA 80175606 (PointGuard)", ""] },
    { cle: "sigen_loadhub", groupe: "Stockage et passerelles", type: "hub", nom: "Sigenergy LoadHub (DIM)", w: 110, h: 84, leg: ["DIM · Sigenergy LoadHub", "Dispositif d'interconnexion microréseau · CSA 80256253 · UL 1741", ""] },
    { cle: "sigenstor", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy SigenStack · modules 6/9 kWh", w: 110, h: 24, leg: ["Batterie Sigenergy SigenStack (modules 6 et 9 kWh)", "Stack 6/9/15/18/24/27 kWh · LFP · CSA 80254671 (UL 1973) · 80254673 (UL 9540)", ""] },
    { cle: "sigen_battery_stack", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy Stack 6/9/15/18/24/27 kWh", w: 110, h: 24, leg: ["Batterie Sigenergy SigenStack (configurations Roulez Électrique)", "1 BAT 6 / 1 BAT 9 / 1×9+1×6 / 2×9 / 2×9+1×6 / 3×9 / 3×9+1×6 kWh · LFP", ""] },
    { cle: "sigen_bat_6", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 6.0 · 6,02 kWh", w: 110, h: 24, leg: ["Batterie Sigenergy BAT 6.0 · 6,02 kWh", "1 module SigenStor · LFP · CSA 80254671 (UL 1973) · 80254673 (UL 9540)", ""] },
    { cle: "sigen_bat_9", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 9.0 · 9,04 kWh", w: 110, h: 24, leg: ["Batterie Sigenergy BAT 9.0 · 9,04 kWh", "1 module SigenStor · LFP · CSA 80254671 (UL 1973) · 80254673 (UL 9540)", ""] },
    { cle: "sigen_bat_12", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 12 kWh (2× BAT 6)", w: 110, h: 24, leg: ["Batterie Sigenergy · 12 kWh (2× BAT 6)", "2 modules 6 kWh · 12 kWh total · LFP", ""] },
    { cle: "sigen_bat_15", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 15 kWh (1× BAT 9 + 1× BAT 6)", w: 110, h: 24, leg: ["Batterie Sigenergy · 15 kWh (KIT 1×9 + 1×6)", "1 module 9 + 1 module 6 kWh · 15 kWh total · LFP", ""] },
    { cle: "sigen_bat_18", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 18 kWh (2× BAT 9)", w: 110, h: 24, leg: ["Batterie Sigenergy · KIT 2 BAT 9 kWh (18 kWh)", "2 modules 9 kWh · 18 kWh total · LFP · sweet spot 13-15 kW PV", ""] },
    { cle: "sigen_bat_24", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 24 kWh (2× BAT 9 + 1× BAT 6)", w: 110, h: 24, leg: ["Batterie Sigenergy · 24 kWh (KIT 2×9 + 1×6)", "2 modules 9 + 1 module 6 kWh · 24 kWh total · LFP", ""] },
    { cle: "sigen_bat_27", groupe: "Stockage et passerelles", type: "module", nom: "Sigenergy BAT 27 kWh (3× BAT 9)", w: 110, h: 24, leg: ["Batterie Sigenergy · KIT 3 BAT 9 kWh (27 kWh)", "3 modules 9 kWh · 27 kWh total · LFP · capacité max stack", ""] },
    { cle: "sigen_v2x", groupe: "Bornes", type: "borne", nom: "Sigenergy EVDC 25 kW bidirectionnelle (V2X)", w: 52, h: 80, leg: ["Borne Sigenergy EVDC 25 kW bidirectionnelle (V2X), NACS ou CCS1", "25 kW CC · couplée en CC au Sigenergy Energy Controller", "CSA 80175606"] },
    { cle: "sigen_ac_nacs", groupe: "Bornes", type: "borne", nom: "Sigenergy AC 11,5 kW NACS", w: 52, h: 80, leg: ["Borne Sigenergy AC 11,5 kW NACS", "240 V · 48 A · circuit 2P 60 A", "UL 2594"] },
    { cle: "sigen_ac_j1772", groupe: "Bornes", type: "borne", nom: "Sigenergy AC 11,5 kW J1772", w: 52, h: 80, leg: ["Borne Sigenergy AC 11,5 kW J1772", "240 V · 48 A · circuit 2P 60 A", "UL 2594"] },
    { cle: "solark", groupe: "Onduleurs", type: "onduleur", nom: "Sol-Ark 12K", w: 100, h: 84, leg: ["Onduleur Sol-Ark 12K hybride (12 kW)", "Hybride · UL 1741-SB · IEEE 2030.5 · multimode", ""] },
    { cle: "solis_s6", groupe: "Onduleurs", type: "onduleur", nom: "Solis S6 (6-12 kW)", w: 100, h: 84, leg: ["Onduleur Solis S6 (6-12 kW)", "Grid-tie monophasé · UL 1741-SB · IEEE 1547", ""] },
    { cle: "luxpower_lxp12k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power LXP-LB-US 12K", w: 100, h: 84, leg: ["Onduleur hybride Lux Power LXP-LB-US 12K, raccordé au réseau", "Hybride 12 kW CA · 120/240 V · batteries 48 V LFP · multimode", "UL 1741-SB"] },
    { cle: "lux_lxp10k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power LXP 10K", w: 100, h: 84, leg: ["Onduleur hybride Lux Power LXP 10K, raccordé au réseau", "Hybride 10 kW CA · 120/240 V · Volthium EQP-ONDU-10K-LXP", "UL 1741-SB"] },
    { cle: "lux_gen13k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power GEN-LB-US 13K", w: 100, h: 84, leg: ["Onduleur hybride Lux Power GEN-LB-US 13K, raccordé au réseau", "Hybride 13 kW CA · 120/240 V · Volthium EQP-GEN-LB-US 13K", "UL 1741-SB"] },
    { cle: "lux_gen16k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power GEN-LB-US 16K", w: 100, h: 84, leg: ["Onduleur hybride Lux Power GEN-LB-US 16K, raccordé au réseau", "Hybride 16 kW CA · 120/240 V · batteries 48 V LFP", "UL 1741-SB"] },
    { cle: "lux_sna6k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power SNA-US 6K (hors réseau)", w: 100, h: 84, leg: ["Onduleur Lux Power SNA-US 6K, hors réseau", "6 kW CA · 120/240 V · non raccordé au réseau (aucune injection)", ""] },
    { cle: "lux_sna12k", groupe: "Onduleurs", type: "onduleur", nom: "Lux Power SNA-US 12K (hors réseau)", w: 100, h: 84, leg: ["Onduleur Lux Power SNA-US 12K, hors réseau", "12 kW CA · 120/240 V · non raccordé au réseau (aucune injection)", ""] },
    { cle: "lux_dongle_wifi", groupe: "Communication", type: "dongle", nom: "Dongle Lux Power Wi-Fi", w: 60, h: 30, leg: ["Dongle Lux Power Wi-Fi", "Surveillance de l'onduleur · portail Lux Power", ""] },
    { cle: "lux_dongle_eth", groupe: "Communication", type: "dongle", nom: "Dongle Lux Power Ethernet", w: 60, h: 30, leg: ["Dongle Lux Power Ethernet (LAN)", "Surveillance de l'onduleur · câble réseau vers le routeur", ""] },
    { cle: "volthium_5k", groupe: "Stockage et passerelles", type: "module", nom: "Volthium 51,2 V 100 Ah · 5,1 kWh (3U)", w: 110, h: 24, leg: ["Batterie Volthium 51,2 V 100 Ah · 5,1 kWh, rackmount 3U autochauffante", "LFP · modèle 51.2-100-R-H-ST-3U-C", "UL 1973"] },
    { cle: "volthium_10k", groupe: "Stockage et passerelles", type: "module", nom: "Volthium 51,2 V 200 Ah · 10,2 kWh", w: 110, h: 24, leg: ["Batterie Volthium 51,2 V 200 Ah · 10,2 kWh, rackmount autochauffante", "LFP · couplée en CC à l'onduleur", "UL 1973"] },
    { cle: "volthium_16k", groupe: "Stockage et passerelles", type: "module", nom: "Volthium 51,2 V 314 Ah · 16,1 kWh (armoire)", w: 110, h: 24, leg: ["Batterie Volthium 51,2 V 314 Ah · 16,1 kWh, armoire au sol autochauffante", "LFP · couplée en CC à l'onduleur", "UL 1973"] },
    { cle: "volthium_busbar", groupe: "Stockage et passerelles", type: "busbar", nom: "Busbar Volthium 2U", w: 80, h: 30, leg: ["Barre omnibus (busbar) Volthium 2U", "Mise en parallèle des batteries (3 et plus) · 4/0 AWG vers l'onduleur", ""] },
    { cle: "volthium_armoire", groupe: "Stockage et passerelles", type: "armoire_bat", nom: "Armoire extérieure Volthium IP66 (4 × 3U)", w: 90, h: 70, leg: ["Armoire extérieure Volthium IP66", "Contient jusqu'à 4 batteries 3U", "IP66"] },
    { cle: "volthium_rack", groupe: "Stockage et passerelles", type: "armoire_bat", nom: "Rack au sol Volthium (8 × 3U)", w: 90, h: 70, leg: ["Rack au sol Volthium", "Jusqu'à 8 batteries 3U · barres et câbles inclus", ""] },
    { cle: "volthium_support", groupe: "Stockage et passerelles", type: "armoire_bat", nom: "Support mural Volthium (2 × 3U)", w: 90, h: 70, leg: ["Support mural Volthium 2 batteries 3U", "Busbars inclus", ""] },
    { cle: "sect_dc_250a", groupe: "Protection et distribution", type: "sectionneur", nom: "Sectionneur CC 250 A (batteries)", w: 70, h: 44, leg: ["Sectionneur CC 250 A cadenassable", "Entre les batteries et l'onduleur · isolation visible", "Art. 84-024 CSA C22.10"] },
    { cle: "fronius_primo", groupe: "Onduleurs", type: "onduleur", nom: "Fronius Primo (5-12 kW)", w: 100, h: 84, leg: ["Onduleur Fronius Primo (5-12 kW)", "Grid-tie monophasé · UL 1741-SB · IEEE 1547", ""] },
    { cle: "enphase_micro", groupe: "Onduleurs", type: "onduleur", nom: "Enphase IQ8 (micro-onduleur)", w: 100, h: 84, leg: ["Micro-onduleur Enphase IQ8", "Micro-onduleur par module · 290-380 W AC · couplé AC", ""] },
    { cle: "pylontech_us5000", groupe: "Stockage et passerelles", type: "module", nom: "Pylontech US5000 (4.8 kWh ×N)", w: 110, h: 24, leg: ["Batterie Pylontech US5000 · 4.8 kWh empilable", "4.8 kWh par module · 48V LFP · jusqu'à 8 modules en parallèle", ""] },
    { cle: "byd_hvs", groupe: "Stockage et passerelles", type: "module", nom: "BYD HVS (5.1-12.8 kWh)", w: 110, h: 24, leg: ["BYD Battery-Box Premium HVS", "Modules HV 2.56 kWh · stack 5.1/7.7/10.2/12.8 kWh · LFP", ""] },
    { cle: "enphase_iq5p", groupe: "Stockage et passerelles", type: "module", nom: "Enphase IQ Battery 5P (5 kWh ×N)", w: 110, h: 24, leg: ["Enphase IQ Battery 5P · 5 kWh empilable AC-couplé", "5 kWh par unité · AC-couplé · jusqu'à 4 unités", ""] },
    { cle: "fox_wilan", groupe: "Communication", type: "dongle", nom: "Module Fox ESS Smart WiLAN", w: 60, h: 30, leg: ["Module Fox ESS Smart WiLAN (Wi-Fi ou LAN)", "Surveillance de l'onduleur · portail Fox ESS", ""] },
    { cle: "fox_4g", groupe: "Communication", type: "dongle", nom: "Module Fox ESS 4G", w: 60, h: 30, leg: ["Module Fox ESS 4G", "Communication cellulaire de l'onduleur", ""] },
    { cle: "sigen_lte", groupe: "Communication", type: "dongle", nom: "Module Sigenergy LTE", w: 60, h: 30, leg: ["Module Sigenergy cellulaire LTE (5 ans)", "Communication cellulaire du contrôleur", ""] },
    { cle: "routeur_wifi", groupe: "Communication", type: "routeur", nom: "Routeur WiFi", w: 80, h: 30, leg: ["Routeur WiFi client", "Routeur réseau client · WiFi + Ethernet", ""] },
    { cle: "dongle_wifi", groupe: "Communication", type: "dongle", nom: "Dongle WiFi onduleur", w: 60, h: 30, leg: ["Dongle WiFi pour onduleur", "Connexion WiFi onduleur ↔ portail constructeur", ""] },
    { cle: "cable_comm_dim", groupe: "Communication", type: "cable_comm", nom: "Câble comm. onduleur↔DIM", w: 80, h: 24, leg: ["Câble communication onduleur↔DIM (Ethernet/RS485)", "CAT5e/CAT6 ou RS485 · pas dans le même conduit que CA", ""] },
    { cle: "antenne_lte", groupe: "Communication", type: "antenne", nom: "Antenne LTE (DIM)", w: 40, h: 60, leg: ["Antenne LTE pour DIM (option)", "Connexion cellulaire backup si pas de WiFi/Ethernet client", ""] },
    { cle: "borne_l2", groupe: "Bornes", type: "borne", nom: "Borne VE niveau 2 (J1772)", w: 52, h: 80, leg: ["Borne de recharge VE niveau 2 (J1772)", "240V · 30-48A · charge AC niveau 2 · connecteur J1772", ""] },
    { cle: "borne_l3", groupe: "Bornes", type: "borne", nom: "Borne VE niveau 3 (DCFC)", w: 52, h: 80, leg: ["Borne de recharge VE niveau 3 DCFC", "DC fast charging · 25-150 kW · connecteur CCS1/CHAdeMO", ""] },
    { cle: "panneau_200a_transfert_3p_60a", groupe: "Protection et distribution", type: "panneau", nom: "Panneau 200A + disj. transfert 3P 60A combiné", w: 130, h: 96, leg: ["Panneau principal 200A avec disjoncteur de transfert tripolaire 60A combiné (interverrouillage)", "200 A · 120/240 V · 1Ø · disj. 22 kAIC · section secours 60 A à transfert 3P (L1-L2-N) interverrouillé · alim. DIM ou génératrice", ""] },
    { cle: "texte", groupe: "Annotations", type: "texte", nom: "Annotation (texte libre)", w: 0, h: 0, leg: null }
  ];
  const GROUPES_PALETTE = ["Service HQ", "Protection et distribution", "Stockage et passerelles", "Onduleurs", "Solaire", "Bornes", "Mise à la terre et sécurité", "Communication", "Annotations"];
  const retouchesDefaut = () => ({ positions: {}, tailles: {}, masques: [], noms: {}, cotes: {}, legendes: {}, ordre: [], ajouts: [], cables: [], cables_retires: [], annotations: [] });
  /** Anciens schémas (v1) : complète les retouches manquantes. */
  const normaliserRetouches = (r) => ({ ...retouchesDefaut(), ...(r || {}) });
  const TAILLES_TYPE = { hq: [60, 60], compteur: [100, 68], coffret: [110, 68], panneau: [130, 96], pcc: [110, 80], gateway: [110, 120], hub: [110, 84], powerwall: [62, 118], expansion: [62, 118], module: [110, 24], pile: [100, 78], onduleur: [100, 84], pv: [170, 78], rsd: [130, 26], epo: [34, 34], borne: [52, 80], malt: [30, 26], routeur: [80, 30], sectionneur: [70, 44], disjoncteur: [44, 30], transfo: [70, 70], ats: [90, 60], generatrice: [70, 70], inlet: [60, 44], parafoudre: [44, 44], jonction: [80, 50], dongle: [60, 30], cpt_distant: [70, 34], cable_comm: [80, 24], antenne: [40, 60], auget: [120, 60], armoire: [100, 90], busbar: [80, 30], armoire_bat: [90, 70] };
  const GENRES_CABLE = [["principal", "Puissance (CA ou CC)"], ["comm", "Communication"]];
  const estComm = (f) => f.genre === "comm";
  // Mots-clés de recherche de la palette (en plus du nom, du groupe et de la légende)
  const MOTS_TYPE = { hq: "reseau hydro quebec source branchement", compteur: "compteur kwh mesurage", coffret: "coffret branchement entree service", panneau: "panneau distribution tableau breaker disjoncteurs", pcc: "panneau charges critiques backup secours", gateway: "passerelle gateway dim tesla interconnexion microreseau", hub: "passerelle hub dim loadhub interconnexion", powerwall: "batterie onduleur tesla powerwall stockage", module: "batterie module stockage", onduleur: "onduleur inverter hybride", pv: "panneau solaire photovoltaique module pv", cpt_distant: "compteur distant remote meter ct", rsd: "arret rapide rapid shutdown rsd mci projoy tigo", epo: "bouton arret urgence epo rsd", borne: "borne recharge vehicule electrique ve ev chargeur", malt: "mise a la terre malt ground", routeur: "routeur wifi internet ethernet communication", sectionneur: "sectionneur disconnect cadenassable interrupteur", disjoncteur: "disjoncteur breaker cadenassable", transfo: "transformateur", ats: "commutateur transfert automatique ats generatrice", generatrice: "generatrice generateur groupe electrogene", inlet: "prise generatrice inlet portative", parafoudre: "parafoudre surtension spd", jonction: "boite jonction combiner", dongle: "dongle wifi lan communication module", cable_comm: "cable communication rs485 ethernet", antenne: "antenne lte cellulaire 4g", auget: "auget repartition barre", armoire: "armoire mesurage tc", busbar: "busbar barre omnibus batteries volthium parallele", armoire_bat: "armoire rack support batteries volthium enceinte", texte: "annotation texte note" };
  const sansAccents = (s) => String(s || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
  const indexPalette = PALETTE.map(p => ({ p, texte: sansAccents([p.nom, p.groupe, p.cle.replace(/_/g, " "), p.type, MOTS_TYPE[p.type] || "", ...(p.leg || [])].join(" ")) }));
  /** Filtre instantané de la palette : tous les mots doivent se trouver (nom, groupe, mots-clés), sans accents ni casse. */
  function chercherPalette(q) {
    const mots = sansAccents(q).split(/[\s,;]+/).filter(Boolean);
    const res = mots.length ? indexPalette.filter(e => mots.every(w => e.texte.includes(w))).map(e => e.p) : PALETTE.slice();
    return GROUPES_PALETTE.map(g => ({ groupe: g, items: res.filter(x => x.groupe === g) })).filter(g => g.items.length);
  }

  // ───────────────────────── Construction : nœuds, fils, légende ─────────────────────────
  // Chaque nœud : { id, type, x, y, w, h, nom, cote, leg: [nom, detail, norme], num, kw, kwh }. Chaque fil : { de, deCote, a, aCote, genre, bus }.
  // Côtés : "g" gauche, "d" droite, "h" haut, "b" bas. Disposition en rangée principale (réseau → compteur → panneau → passerelle →
  // onduleurs ou Powerwall), champ PV et arrêt rapide au-dessus de l'onduleur, charges secourues sous la passerelle, bornes sous le panneau.
  const borne = (v, a, b) => Math.max(a, Math.min(b, Number(v) || 0));
  function construire(m) {
    const sys = m.systeme || {}, obj = sys.objectif || "vide";
    const S = MARQUES[sys.marque] || MARQUES.tesla;
    const top = topologie(m);
    const n = [], fils = [];
    const R = m.retouches || {};
    const nomDe = (id, d) => (R.noms && R.noms[id]) || d;
    const add = (o) => { n.push(o); return o; };
    const lier = (a, ac, b, bc, genre, extra) => { if (a && b) fils.push({ de: a.id, deCote: ac, a: b.id, aCote: bc, genre: genre || "principal", ...(extra || {}) }); };
    const extras = (cle) => (m.extras || []).filter(e => e.cle === cle);
    const calibre = Number(m.service.calibre) || 200;
    const tension = m.service.tension || "120/240 V";
    const vide = obj === "vide";
    const quatreCents = calibre >= 320 && !vide;
    const tesla = sys.marque === "tesla";
    const aStock = obj === "batterie" || obj === "solaire_batterie";
    const nbPw = tesla ? borne(sys.nb, 0, 6) : 0;
    const nbOnd = !nbPw && (aStock || obj === "solaire") ? borne(sys.nb_onduleurs, 0, 4) : 0;
    const nbGw = ["vide", "service", "borne"].includes(obj) ? 0 : borne(sys.nb_gateways, 0, 2);
    const secours = nbGw ? (sys.secours || "base") : (aStock && sys.secours === "partiel" ? "partiel" : "aucun");
    // Rangée resserrée (36 px) avec les disjoncteurs cadenassables Tesla (leur étiquette de 112 px déborde de 34 px de chaque côté) ;
    // en maison complète, le panneau n'est pas dans la rangée : écart normal, l'étiquette de l'embase ne touche pas celle du réseau
    const Y = quatreCents ? 380 : 400, GAP = quatreCents || extras("sect_ext").length || (tesla && nbPw > 0 && secours !== "complet") ? 36 : 54;
    let x = ZONE.x + 16;
    const place = (o) => { o.x = x; o.y = o.y != null ? o.y : Y - o.h / 2; x += o.w + GAP; return add(o); };

    // 1. Réseau, compteur, sectionneur extérieur
    const hq = place({ id: "hq", type: "hq", w: 60, h: 60, nom: "Réseau HQ", cote: `${tension} · 1 Ø` });
    const meterMain = m.service.embase === "meter_main";
    const cpt = place({ id: "compteur", type: "compteur", w: 100, h: 68, num: true, nom: nomDe("compteur", meterMain ? `Embase ${calibre} A avec disjoncteur` : "Compteur HQ"),
      cote: m.options.mesurage_net && (obj === "solaire" || obj === "solaire_batterie") ? "communicant · bidirectionnel" : "communicant",
      leg: [meterMain ? `Embase de compteur ${calibre} A avec disjoncteur intégré` : "Compteur communicant Hydro-Québec", m.options.mesurage_net && (obj === "solaire" || obj === "solaire_batterie") ? "Bidirectionnel · lecture mesurage net" : "Lecture standard", meterMain ? "22 kA · NEMA 3R" : ""] });
    lier(hq, "d", cpt, "g");
    let amont = cpt;
    const se = extras("sect_ext")[0];
    if (se) { const s = place({ id: "sect_ext", type: "sectionneur", w: 70, h: 44, num: true, nom: nomDe("sect_ext", "Sectionneur 200 A"), cote: "extérieur · cadenassable", leg: [se.nom || "Sectionneur extérieur 200 A cadenassable", "Sectionneur cadenassable · isolation visible de l'entrée", "Art. 84-024 CSA C22.10"] }); lier(amont, "d", s, "g"); amont = s; }

    // 2. Panneau(x) principal(aux) ; à 320 ou 400 A, coffret à fusibles et deux panneaux 200 A ; secours complet : la passerelle est en amont
    const mkPanneau = (id, nom, cote, leg) => ({ id, type: "panneau", w: 130, h: 96, num: true, nom: nomDe(id, nom), cote, leg });
    // Petit kit Tesla (secours « base ») : la Gateway 3 contient les charges critiques et sert de panneau de secours
    const ccGw = tesla && secours === "base";
    const mkGw = (g, nb) => ({ id: `dim${g + 1}`, type: tesla ? "gateway" : "hub", w: 110, h: tesla ? 120 : 84, num: g === 0, nom: nomDe(`dim${g + 1}`, nb > 1 ? `${S.dim} no ${g + 1}` : S.dim), cote: ccGw ? `${S.dim_calibre} A · charges critiques intégrées` : `${S.dim_calibre} A · DIM`,
      leg: [`${nb > 1 ? `${nb} × ${S.dim}` : S.dim}${ccGw ? " · charges critiques intégrées" : ""}`, ccGw ? "Sert de panneau de secours (aucun panneau de charges critiques) · DIM" : secours === "complet" ? "Dispositif d'interconnexion de microréseau · maison complète secourue" : secours === "base" ? "Dispositif d'interconnexion · circuits de secours internes" : "Dispositif d'interconnexion de microréseau", "UL 1741 CRD · IEEE 2030.5"] });
    // Disjoncteurs cadenassables Tesla (JF, 5 nov. 2026) : composantes à part entière. Le premier part du panneau principal (vers la
    // passerelle ; en maison complète, entre la passerelle et le panneau principal), calibre à confirmer ; les autres partent de la
    // passerelle et alimentent chacun un Powerwall 3 (S.disj_a = 60 A pour un Powerwall 3 de 11,5 kW, article 568 du catalogue).
    const disjTesla = tesla && nbPw > 0;
    const ART = "Art. 84-024 CSA C22.10";
    const mkDisjPan = (id, nb, complet) => ({ id, type: "disjoncteur", w: 44, h: 30, num: id === "disj_pan", nom: nomDe(id, "Disj. cadenassable"), cote: "2P · calibre à confirmer",
      leg: [complet ? "Disjoncteur cadenassable 2P du panneau principal" : `${nb > 1 ? nb + " × " : ""}Disjoncteur cadenassable 2P, départ du panneau principal`, complet ? "Entre la passerelle et le panneau principal · calibre à confirmer" : "Alimente la passerelle Tesla Gateway 3 · calibre à confirmer", ART] });
    let panneaux = [], gws = [];
    if (quatreCents) {
      const cof = place({ id: "coffret", type: "coffret", w: 110, h: 68, num: true, nom: nomDe("coffret", `Coffret ${calibre} A`), cote: "sectionneur à fusibles cadenassable", leg: [`Coffret de branchement ${calibre} A`, "Sectionneur à fusibles cadenassable", "Art. 84-024 CSA C22.10"] });
      lier(amont, "d", cof, "g");
      const px = x;
      const p1 = add({ ...mkPanneau("panneau", "Panneau 200 A no 1", `200 A · ${tension}`, ["Panneau de distribution 200 A no 1", "Disjoncteur principal 22 kA", "Charges de la maison"]), x: px, y: Y - 48 });
      const p2 = add({ ...mkPanneau("panneau2", "Panneau 200 A no 2", `200 A · ${tension}`, ["Panneau de distribution 200 A no 2", "Disjoncteur principal 22 kA", "Charges de la maison"]), x: px, y: Y + 142 });
      x += 130 + GAP;
      lier(cof, "d", p1, "g", "principal", { bus: true }); lier(cof, "d", p2, "g", "principal", { bus: true });
      panneaux = [p1, p2];
    } else if (secours === "complet") {
      const g = place(mkGw(0, 1)); lier(amont, "d", g, "g"); gws = [g];
      const mkP = (o) => ({ ...mkPanneau("panneau", `Panneau principal ${calibre} A`, "maison complète secourue", [`Panneau de distribution principal ${calibre} A`, "Alimenté par la passerelle · maison complète en secours", "Disjoncteur principal 22 kA"]), ...o });
      if (disjTesla) {
        // le départ vers le panneau sort du bas de la passerelle, côté gauche : l'étiquette de la passerelle reste dégagée
        const xf = g.x + 13;
        const dA = add({ ...mkDisjPan("disj_pan", 1, true), x: xf - 22, y: g.y + g.h + 40, etq: "g" });   // étiquette à gauche : la droite mène aux départs des Powerwall
        const p1 = add(mkP({ x: xf - 65, y: dA.y + dA.h + 34 }));
        lier(g, "b", dA, "h"); lier(dA, "b", p1, "h"); panneaux = [p1];
      } else {
        const p1 = add(mkP({ x: g.x - 10, y: g.y + g.h + 50 }));
        lier(g, "b", p1, "h"); panneaux = [p1];
      }
    } else {
      const p1 = place(mkPanneau("panneau", `Panneau principal ${calibre} A`, `${calibre} A · ${tension}`, [`Panneau de distribution principal ${calibre} A`, "Disjoncteur principal 22 kA AIC", "Art. 84-024 CSA C22.10"]));
      lier(amont, "d", p1, "g"); panneaux = [p1];
    }
    const P = panneaux[0], Pdernier = panneaux[panneaux.length - 1];

    // 3. Passerelle(s) en aval du panneau (secours de base ou partiel) ; la 2e passerelle (400 A) est sur le panneau no 2
    if (!gws.length) for (let g = 0; g < nbGw; g++) {
      const pan = panneaux[g] || P;
      const o = mkGw(g, nbGw);
      let dep = pan;
      if (disjTesla) {
        const d = mkDisjPan(g === 0 ? "disj_pan" : `disj_pan${g + 1}`, nbGw, false);
        if (g === 0) place(d); else { d.x = n.find(z => z.id === "disj_pan").x; d.y = pan.y + pan.h / 2 - d.h / 2; add(d); }
        lier(pan, "d", d, "g"); dep = d;
      }
      if (g === 0) place(o); else { o.x = gws[0].x; o.y = pan.y + pan.h / 2 - o.h / 2; add(o); }
      lier(dep, "d", o, "g"); gws.push(o);
    }
    const G = gws[0] || null;

    // 4. Sectionneur CA de l'onduleur (ligne du devis), puis onduleurs ou Powerwall 3
    let source = G || P;
    const sac = extras("sect_ac")[0];
    if (sac && (nbPw || nbOnd)) { const s = place({ id: "sect_ac", type: "sectionneur", w: 70, h: 44, num: true, nom: nomDe("sect_ac", "Sectionneur CA 60 A"), cote: "cadenassable", leg: [sac.nom || "Sectionneur CA 60 A cadenassable", "Sectionneur cadenassable de l'onduleur · isolation visible", "Art. 84-024 CSA C22.10"] }); lier(source, "d", s, "g"); source = s; }
    const unites = [];
    const disjPw = [];
    // premier disjoncteur à 24 px de la passerelle (tronçon de sortie 16 px + marge 7 px ; sa cote déborde de 15 px) : la rangée
    // tient à 400 A avec deux passerelles
    if (!disjTesla) x += 30; else x -= GAP - 24;
    if (nbPw) {
      // Tesla : chaque disjoncteur cadenassable est en ligne, juste à gauche de son Powerwall (disjoncteur et Powerwall sur la même
      // ligne) ; sa cote courte (74 px) passe au-dessus, l'étiquette du Powerwall juste dessous. La barre d'alimentation entre par le
      // bas des disjoncteurs suivants, sous les étiquettes des Powerwall. Écarts de 18 px : la cote déborde de 15 px de chaque côté.
      const PAS = disjTesla ? 44 + 18 + 62 + 18 : 104;
      for (let i = 0; i < nbPw; i++) {
        const x0 = x + i * PAS;
        if (disjTesla) disjPw.push(add({ id: `disj_pw${i + 1}`, type: "disjoncteur", x: x0, y: Y - 15, w: 44, h: 30, num: i === 0, etq: "h", nom: nomDe(`disj_pw${i + 1}`, `Disj. ${S.disj_a} A`), cote: "2P cadenassable",
          leg: [`${nbPw > 1 ? nbPw + " × " : ""}Disjoncteur cadenassable 2P ${S.disj_a} A, départ ${G ? "de la passerelle" : "du panneau principal"}`, `Alimente le Powerwall 3 (${fmt(S.kw)} kW CA) · calibre selon le Powerwall 3`, ART] }));
        unites.push(add({ id: `batt${i + 1}`, type: "powerwall", x: disjTesla ? x0 + 44 + 18 : x0, y: Y - 59, w: 62, h: 118, num: i === 0, etq: "b", nom: nomDe(`batt${i + 1}`, `Powerwall 3${nbPw > 1 ? " no " + (i + 1) : ""}`), cote: `${S.kw} kW · ${S.kwh} kWh`, kw: S.kw, kwh: S.kwh,
          leg: [`${nbPw > 1 ? nbPw + " × " : ""}Tesla Powerwall 3`, `Onduleur intégré ${S.kw} kW CA · batterie LFP ${S.kwh} kWh`, S.cert] }));
      }
      disjPw.forEach((d, i) => lier(source, "d", d, i === 0 ? "g" : "b", "principal", nbPw > 1 ? { bus: true } : undefined));
      x += nbPw * PAS - (disjTesla ? 18 : 42) + 50;
    } else if (nbOnd) {
      const kw = kwOnduleur(m); const nomO = sys.onduleur_nom || (ONDULEURS[sys.onduleur] || {}).nom || S.onduleur;
      for (let i = 0; i < nbOnd; i++) unites.push(add({ id: `ond${i + 1}`, type: "onduleur", x: x + i * 140, y: Y - 42, w: 100, h: 84, num: i === 0, nom: nomDe(`ond${i + 1}`, aStock ? (nbOnd > 1 ? `Onduleur hybride no ${i + 1}` : "Onduleur hybride") : (nbOnd > 1 ? `Onduleur no ${i + 1}` : "Onduleur")), cote: /\d\s*kW\b/i.test(nomO) ? nomO : `${nomO} · ${fmt(kw)} kW`, kw,
        leg: [`${nbOnd > 1 ? nbOnd + " × " : ""}${nomO}`, sys.hors_reseau || (ONDULEURS[sys.onduleur] || {}).hors_reseau ? `Onduleur hors réseau ${kw} kW CA · 1 Ø · aucune injection au réseau` : aStock ? `Onduleur hybride ${kw} kW CA · 1 Ø · multimode` : `Onduleur raccordé au réseau ${kw} kW CA · 1 Ø`, S.cert] }));
      x += nbOnd * 140 - 40 + 50;
    }
    // Alimentation CA des unités : par leur disjoncteur cadenassable (Powerwall 3) ; sinon en ligne pour une seule, en barre par le bas pour plusieurs
    if (disjPw.length) disjPw.forEach((d, i) => lier(d, "d", unites[i], "g"));
    else if (unites.length === 1) lier(source, "d", unites[0], "g");
    else unites.forEach(u => lier(source, "d", u, "b", "principal", { bus: true }));
    // Communication : chaque onduleur ou Powerwall ↔ passerelle (barre de communication par le haut)
    if (G) unites.forEach(u => lier(G, "h", u, "h", "comm", { bus: true }));
    if (G && gws[1]) lier(gws[1], "h", G, "b", "comm");

    // 5. Stockage couplé en CC : batteries d'expansion (Tesla) ou pile de modules (autres marques) à droite de la dernière unité
    const uDer = unites[unites.length - 1] || null;
    let ajoutCC = null;
    if (uDer && nbPw && Number(sys.expansion) > 0) {
      const ne = borne(sys.expansion, 1, 3); let prec = uDer;
      for (let i = 0; i < ne; i++) { const e = add({ id: `exp${i + 1}`, type: "expansion", x: x + i * 104, y: Y - 59, w: 62, h: 118, num: i === 0, nom: nomDe(`exp${i + 1}`, `Expansion${ne > 1 ? " no " + (i + 1) : ""}`), cote: `${S.expansion_kwh} kWh`, kwh: S.expansion_kwh, leg: [`${ne > 1 ? ne + " × " : ""}Batterie d'expansion Powerwall 3`, `${S.expansion_kwh} kWh · couplée en CC au Powerwall`, "UL 9540"] }); lier(prec, "d", e, "g"); if (i === 0) ajoutCC = e; prec = e; }
      x += ne * 104 - 42 + GAP;
    } else if (uDer && nbOnd && aStock && Number(sys.nb) > 0) {
      // Chaîne CC : onduleur, busbar (s'il y en a un), batteries ; aucun sectionneur CC entre les batteries et l'onduleur (JF, 5 nov. 2026)
      let prec = uDer;
      const bb = extras("busbar")[0];
      if (bb) { const o = add({ id: "busbar", type: "busbar", x, y: Y - 15, w: 80, h: 30, num: true, nom: nomDe("busbar", "Busbar"), cote: "batteries en parallèle", leg: [bb.nom || "Busbar Volthium", "Mise en parallèle des batteries · câble 4/0 AWG vers l'onduleur", ""] }); lier(prec, "d", o, "g"); prec = o; if (!ajoutCC) ajoutCC = o; x += 80 + 40; }
      const nb = borne(sys.nb, 1, 12); const h = 30 + Math.min(nb, 6) * 12; const kwh = stockageKwh(m);
      const nomPile = Array.isArray(sys.batteries) && sys.batteries.length > 1 ? sys.batteries.map(b => `${b.q} × ${b.nom}`).join(" + ") : `${nb} × ${sys.batterie_nom || S.batterie}`;
      const enceinte = extras("enceinte").map(e => e.nom.replace(/\s*\(.*\)\s*$/, "")).join(", ");
      const pile = add({ id: "batt1", type: "pile", x, y: Y - h / 2, w: 100, h, num: true, cellules: Math.min(nb, 6), nom: nomDe("batt1", nomPile), cote: `${fmt(kwh)} kWh`, kwh,
        leg: [nomPile, `Stockage ${fmt(kwh)} kWh · couplé en CC${enceinte ? " · " + enceinte : " à l'onduleur"}`, /Volthium/i.test(nomPile) ? "UL 1973" : "UL 9540"] });
      lier(prec, "d", pile, "g"); if (!ajoutCC) ajoutCC = pile; x += 100 + GAP;
      // Communication BMS : batteries ↔ onduleur (CAN ou RS485), par le bas
      lier(uDer, "b", pile, "b", "comm");
    }

    // 6. Champ PV, arrêt rapide et bouton d'arrêt : toujours raccordés à l'onduleur (ou au Powerwall 3), jamais à la passerelle
    let pvSerre = false;
    if ((obj === "solaire" || obj === "solaire_batterie") && Number(m.pv.nb) > 0) {
      const nbP = Number(m.pv.nb); const rsd = RSD[m.pv.rsd || "aucun"];
      // plusieurs Powerwall : champ PV rapproché ; rangée trop chargée (entrée 400 A, deux passerelles) : quand son étiquette ne
      // tient plus à droite, le champ PV passe au-dessus de la passerelle, à gauche du premier Powerwall (jamais sous la légende)
      const nomPv = nomDe("pv", `PV ${kwPv(m)} kW CC`), cotePv = `${nbP} × ${m.pv.modele || "panneau"} ${m.pv.watts} W`;
      let cx = uDer ? (ajoutCC ? (uDer.x + uDer.w + ajoutCC.x) / 2 : uDer.x + uDer.w + (disjTesla && nbPw > 1 ? 20 : 56)) : P.x + P.w + 120;
      if (disjTesla && nbPw > 1 && cx + 95 + Math.max(String(nomPv).length * 6.2, cotePv.length * 4.9) > ZONE.x + ZONE.w + 12) { pvSerre = true; cx = unites[0].x - 135; }   // l'étiquette de l'arrêt rapide reste à gauche du lien du routeur
      cx = Math.min(ZONE.x + ZONE.w - 95, cx);
      const yPv = ZONE.y + 14;
      const pv = add({ id: "pv", type: "pv", x: cx - 85, y: yPv, w: 170, h: 78, num: true, nom: nomPv, cote: cotePv, kwc: kwPv(m),
        leg: ["Panneaux photovoltaïques", `${nbP} × ${m.pv.modele || "panneau"} ${m.pv.watts} W = ${kwPv(m)} kW CC`, "CSA C22.2 no 61730"] });
      let dernier = pv;
      if (rsd) {
        const nbRsd = Number(m.pv.nb_rsd) || Math.ceil(nbP / rsd.par);
        const detail = Array.isArray(m.pv.rsd_detail) && m.pv.rsd_detail.length > 1 ? m.pv.rsd_detail.map(d => `${d.q} × ${d.nom}`).join(", ") : "";
        const r = add({ id: "rsd", type: "rsd", x: cx - 65, y: yPv + 112, w: 130, h: 26, num: true, nom: nomDe("rsd", "Arrêt rapide"), cote: detail || `${nbRsd} × ${rsd.nom.split(" (")[0]}`, leg: [rsd.nom, `${nbRsd} unité${nbRsd > 1 ? "s" : ""} · sur les chaînes PV, commandé par l'onduleur`, "Art. 64-218 CSA C22.10:26"] });
        lier(pv, "b", r, "h"); dernier = r;
      }
      if (uDer) lier(dernier, "b", uDer, "d");
      if (m.options.epo && uDer) {
        // plusieurs Powerwall : le lien du routeur descend vers le premier Powerwall à gauche du bouton, son étiquette passe au-dessus
        const multiPw = disjTesla && nbPw > 1;
        const e = add({ id: "epo", type: "epo", x: cx - 65 - 72, y: yPv + 104 + (multiPw ? 10 : 0), w: 34, h: 34, ...(multiPw ? { etq: "h" } : {}), num: true, nom: nomDe("epo", "Bouton d'arrêt"), cote: "", leg: ["Bouton d'arrêt rapide (EPO)", "Raccordé à l'onduleur · déclenche l'arrêt rapide des modules", "Art. 64-218"] });
        lier(e, "b", uDer, "h", "comm");
      }
    }

    // 7. Charges secourues : panneau de charges critiques sous la passerelle (ou sous l'onduleur, sortie de secours)
    const sousU = [];    // rangée sous la première unité : { o, lien: [côté source, côté cible, genre], suite }
    const U0 = unites[0] || null;
    if (secours === "partiel") {
      const pc = Number(sys.panneau_critique) || 100;
      const srcS = gws[1] || G || unites[0];
      const aDroite = !!gws[1];
      if (srcS && srcS === U0) sousU.push({ o: { id: "pcc", type: "pcc", w: 110, h: 80, num: true, nom: nomDe("pcc", "Charges critiques"), cote: `${pc} A · secours partiel`, leg: [`Panneau de charges critiques ${pc} A`, "Alimenté par la sortie de secours (EPS) de l'onduleur", "Alimentation de secours partielle"] }, genre: "principal" });
      else if (srcS) { const pcc = add({ id: "pcc", type: "pcc", x: aDroite ? srcS.x + srcS.w + 70 : srcS.x, y: aDroite ? srcS.y + srcS.h / 2 - 40 : srcS.y + srcS.h + 70, w: 110, h: 80, num: true, nom: nomDe("pcc", "Charges critiques"), cote: `${pc} A · secours partiel`, leg: [`Panneau de charges critiques ${pc} A`, G ? "Alimenté par la sortie de secours de la passerelle" : "Alimenté par la sortie de secours de l'onduleur", "Alimentation de secours partielle"] }); if (aDroite) lier(srcS, "d", pcc, "g"); else lier(srcS, "b", pcc, "h"); }
    }

    // 8. Routeur du client : Tesla, dans le premier Powerwall 3 (un seul lien, même avec plusieurs Powerwall), jamais dans la passerelle ;
    //    autres marques, dans la passerelle. Compteur distant.
    if (nbPw && U0 && m.options.routeur) { const r = add({ id: "routeur", type: "routeur", x: pvSerre ? U0.x + U0.w / 2 - 40 : U0.x - 104, y: Y - 230, w: 80, h: 30, num: true, nom: nomDe("routeur", "Routeur Wi-Fi"), cote: "", leg: ["Routeur du client (Wi-Fi ou Ethernet)", "Communication du Powerwall 3 et surveillance", "Câble de communication (pointillé)"] }); lier(r, pvSerre ? "b" : "d", U0, "h", "comm"); }
    else if (G && m.options.routeur) { const r = add({ id: "routeur", type: "routeur", x: G.x + G.w / 2 - 40, y: Y - 230, w: 80, h: 30, num: true, nom: nomDe("routeur", "Routeur Wi-Fi"), cote: "", leg: ["Routeur du client (Wi-Fi ou Ethernet)", "Communication de la passerelle et surveillance", "Câble de communication (pointillé)"] }); lier(G, "h", r, "b", "comm"); }
    const rm = extras("compteur_distant")[0];
    if (rm && G) { const o = add({ id: "cpt_distant", type: "cpt_distant", x: cpt.x + 15, y: Y - 160, w: 70, h: 34, num: true, nom: nomDe("cpt_distant", "Compteur distant"), cote: "", leg: [rm.nom || "Compteur distant Tesla Remote Meter", "Mesure de la consommation · communication vers la passerelle", ""] }); lier(o, "d", G, "h", "comm"); }
    // Borne V2X Sigenergy (EVDC) : couplée en CC au contrôleur Sigenergy, pas au panneau
    const v2x = U0 && /sigenergy/i.test(sys.marque) ? (m.bornes || []).filter(b => b.v2x).slice(0, 1) : [];
    v2x.forEach((b, i) => sousU.push({ o: { id: `v2x${i + 1}`, type: "borne", w: 52, h: 80, num: true, nom: nomDe(`v2x${i + 1}`, b.modele || "Borne V2X"), cote: `${fmt(b.kw || 25)} kW CC · bidirectionnelle`, leg: [`Borne ${b.modele || "V2X"}`.trim(), `${fmt(b.kw || 25)} kW CC bidirectionnelle · couplée en CC au contrôleur Sigenergy`, "CSA 80175606"] }, genre: "principal" }));
    const nomDongle = (t) => ({ LAN: "Dongle Ethernet", "4G": "Module 4G", WiLAN: "Module WiLAN" })[typeDongle(t)] || "Module Wi-Fi";
    const dongles = U0 ? extras("dongle").slice(0, 2) : [];
    dongles.forEach((d, i) => sousU.push({ o: { id: `dongle${i + 1}`, type: "dongle", w: 60, h: 30, num: true, nom: nomDe(`dongle${i + 1}`, nomDongle(d.nom)), cote: "", leg: [d.nom, "Communication de l'onduleur (surveillance)", ""] }, genre: "comm" }));
    if (U0 && sousU.length) {
      // la rangée commence au milieu de l'unité : le coin inférieur gauche reste libre pour l'étiquette de l'onduleur
      let ux = U0.x + Math.round(U0.w / 2) + 6; const uy = U0.y + U0.h + 70; let dernierDongle = null;
      for (const e of sousU) { const o = add({ ...e.o, x: ux, y: uy + (e.o.type === "dongle" ? 25 : 0) }); ux += e.o.w + 34; lier(U0, "b", o, "h", e.genre); if (e.o.type === "dongle") dernierDongle = o; }
      // Sans passerelle, le module de communication de l'onduleur rejoint le routeur du client
      if (!G && dernierDongle && m.options.routeur) { const r = add({ id: "routeur", type: "routeur", x: ux + 6, y: uy + 25, w: 80, h: 30, num: true, nom: nomDe("routeur", "Routeur Wi-Fi"), cote: "", leg: ["Routeur du client (Wi-Fi ou Ethernet)", "Surveillance de l'onduleur par le portail du fabricant", "Câble de communication (pointillé)"] }); lier(dernierDongle, "d", r, "g", "comm"); }
    }

    // 9. Sous le panneau : mise à la terre, bornes, panneaux secondaires ; génératrice
    const sousP = [];
    const bornesP = (m.bornes || []).filter(b => !(v2x.length && b.v2x));
    bornesP.slice(0, 3).forEach((b, i) => sousP.push({ id: `borne${i + 1}`, type: "borne", w: 52, h: 80, num: i === 0, nom: nomDe(`borne${i + 1}`, b.modele || "Borne VÉ"), cote: b.v2x ? `${fmt(b.kw || 25)} kW CC · bidirectionnelle` : `${b.amperes || 48} A · 240 V`,
      leg: [`${bornesP.length > 1 ? bornesP.length + " × " : ""}Borne de recharge ${b.modele || ""}`.trim(), b.v2x ? `${fmt(b.kw || 25)} kW CC bidirectionnelle` : `${b.amperes || 48} A · 240 V · circuit dédié 2P ${Math.round((b.amperes || 48) * 1.25 / 5) * 5} A`, "Art. 86 CSA C22.10:26"] }));
    extras("panneau_sec").slice(0, 2).forEach((p, i) => sousP.push({ id: `psec${i + 1}`, type: "pcc", w: 110, h: 80, num: true, nom: nomDe(`psec${i + 1}`, p.amperes ? `Panneau secondaire ${p.amperes} A` : "Panneau secondaire"), cote: p.amperes ? `${p.amperes} A · ${tension}` : "", leg: [p.nom || "Panneau secondaire", "Alimenté par le panneau principal", ""] }));
    if (sousP.length) {
      const pan = Pdernier; const larg = sousP.reduce((s, o) => s + o.w, 0) + (sousP.length - 1) * 30;
      // sous le panneau ; à côté quand la place manque en bas (400 A : à gauche du panneau no 2 ; secours complet : à droite du panneau)
      const cote = quatreCents ? "gauche" : secours === "complet" ? "droite" : "bas";
      let bx = cote === "gauche" ? Math.max(ZONE.x + 100, pan.x - 60 - larg) : cote === "droite" ? pan.x + pan.w + 70 : pan.x + pan.w / 2 - larg / 2; const by = cote === "bas" ? pan.y + pan.h + 80 : pan.y + pan.h / 2 - 40;
      for (const o of sousP) { add({ ...o, x: bx, y: by }); bx += o.w + 30; if (cote === "droite") lier(pan, "d", o, "g", "principal", { bus: true }); else lier(pan, "b", o, "h", "principal", { bus: true }); }
    }
    if (m.options.malt && !vide) {
      const xs = sousP.length && !quatreCents && secours !== "complet" ? Math.min(P.x - 10, n.find(o => o.id === sousP[0].id).x - 56) : P.x - 10;
      const malt = add({ id: "malt", type: "malt", x: xs, y: quatreCents ? P.y + P.h + 34 : P.y + P.h + 62, w: 30, h: 26, num: true, nom: nomDe("malt", "MALT"), cote: "", leg: ["Mise à la terre", "Électrode et continuité des masses", "Art. 10 CSA C22.10:26"] });
      lier(P, "b", malt, "h");
    }
    const gen = extras("generatrice")[0], ats = extras("ats")[0], inlet = extras("inlet")[0];
    if (gen || ats) {
      const a = add({ id: "ats", type: "ats", x: cpt.x, y: Y + 140, w: 90, h: 60, num: true, nom: nomDe("ats", "Commutateur de transfert"), cote: "automatique", leg: [(ats && ats.nom) || "Commutateur de transfert automatique", "Bascule réseau ↔ génératrice · interverrouillé", "Art. 14-612"] });
      lier(a, "d", P, "g");
      if (gen) { const gg = add({ id: "generatrice", type: "generatrice", x: hq.x - 5, y: Y + 250, w: 70, h: 70, num: true, nom: nomDe("generatrice", "Génératrice"), cote: "fixe", leg: [gen.nom || "Génératrice fixe", "Source de secours · groupe électrogène", ""] }); lier(gg, "d", a, "b"); }
    } else if (inlet) {
      const o = add({ id: "inlet", type: "inlet", x: cpt.x + 20, y: Y + 150, w: 60, h: 44, num: true, nom: nomDe("inlet", "Prise de génératrice"), cote: "portative", leg: [inlet.nom || "Prise d'entrée de génératrice portative", "Interrupteur de transfert manuel · interverrouillé", "Art. 14-612"] });
      lier(o, "d", P, "g");
    }
    return terminer(m, n, fils, top);
  }

  /** Retouches à la main : composantes ajoutées depuis la palette, masquages, déplacements, tailles, noms, cotes, légendes,
   *  ordre de numérotation, câbles ajoutés ou retirés, annotations. Les identifiants sont stables (ids générés et ajouts aj_n). */
  function terminer(m, n, fils, top) {
    const r = normaliserRetouches(m.retouches);
    for (const a of r.ajouts || []) {
      const t = TAILLES_TYPE[a.type] || [100, 60];
      n.push({ id: a.id, type: a.type, x: Number(a.x) || 0, y: Number(a.y) || 0, w: Number(a.w) || t[0], h: Number(a.h) || t[1], nom: a.nom || "", cote: a.cote || "", leg: a.leg || [a.nom || "", "", ""], num: a.num !== false, ajout: true, cle: a.cle });
    }
    const masques = new Set(r.masques || []);
    const noeuds = n.filter(x => !masques.has(x.id)).map(x => {
      const p = (r.positions || {})[x.id], t = (r.tailles || {})[x.id];
      return { ...x, x0: x.x, y0: x.y, x: x.x + (p ? p.dx || 0 : 0), y: x.y + (p ? p.dy || 0 : 0), w: t && t.w ? t.w : x.w, h: t && t.h ? t.h : x.h,
        nom: (r.noms || {})[x.id] != null ? r.noms[x.id] : x.nom, cote: (r.cotes || {})[x.id] != null ? r.cotes[x.id] : x.cote, leg: (r.legendes || {})[x.id] || x.leg };
    });
    const rang = new Map((r.ordre || []).map((id, i) => [id, i]));
    const numerotes = noeuds.filter(x => x.num).map((x, i) => ({ x, i })).sort((a, b) => (rang.has(a.x.id) ? rang.get(a.x.id) : 1000 + a.i) - (rang.has(b.x.id) ? rang.get(b.x.id) : 1000 + b.i));
    for (const x of noeuds) if (x.num) x.num = null;
    numerotes.forEach((o, k) => { o.x.num = k + 1; });
    const retires = new Set(r.cables_retires || []);
    const ids = new Set(noeuds.map(x => x.id));
    const filsF = fils.map(f => ({ ...f, cle: `${f.de}>${f.a}${f.genre === "comm" ? "~comm" : ""}` })).filter(f => !retires.has(f.cle) && ids.has(f.de) && ids.has(f.a));
    for (const c of r.cables || []) if (ids.has(c.de) && ids.has(c.a)) filsF.push({ ...c, genre: c.genre === "comm" ? "comm" : "principal", cle: c.id, manuel: true });
    const vide = (m.systeme || {}).objectif === "vide" && !(r.ajouts || []).length;
    return { noeuds, fils: filsF, top, annotations: (r.annotations || []).slice(), vide, avertissements: ((m.source || {}).avertissements || []).slice() };
  }

  // ───────────────────────── Câblage orthogonal : routeur en canaux ─────────────────────────
  // Chaque câble part d'un port précis (côté + position répartie sur le côté), sort d'un court tronçon perpendiculaire, puis
  // le routeur essaie des tracés en L, en Z et en U sur des canaux (bords des appareils + marge) et garde le moins coûteux :
  // traverser un appareil est interdit, chevaucher un autre circuit aussi ; un croisement coûte cher (pont en demi-cercle s'il reste).
  const DIRS = { g: { x: -1, y: 0 }, d: { x: 1, y: 0 }, h: { x: 0, y: -1 }, b: { x: 0, y: 1 } };
  const STUB = 16, MARGE = 7;
  const centre = (o) => ({ x: o.x + o.w / 2, y: o.y + o.h / 2 });
  const port = (o, cote, t = 0.5) => cote === "d" ? { x: o.x + o.w, y: o.y + o.h * t } : cote === "g" ? { x: o.x, y: o.y + o.h * t } : cote === "h" ? { x: o.x + o.w * t, y: o.y } : { x: o.x + o.w * t, y: o.y + o.h };
  /** Côté par défaut selon la position relative (câbles manuels anciens). */
  const coteAuto = (a, b) => { const ca = centre(a), cb = centre(b); const dx = cb.x - ca.x, dy = cb.y - ca.y; return Math.abs(dx) >= Math.abs(dy) ? (dx >= 0 ? ["d", "g"] : ["g", "d"]) : (dy >= 0 ? ["b", "h"] : ["h", "b"]); };
  const horiz = (a, b) => Math.abs(a.y - b.y) < 0.5;
  const simplifier = (pts) => {
    const p = [];
    for (const q of pts) { const r = { x: Math.round(q.x * 2) / 2, y: Math.round(q.y * 2) / 2 }; const l = p[p.length - 1]; if (l && Math.abs(l.x - r.x) < 0.5 && Math.abs(l.y - r.y) < 0.5) continue; p.push(r); }
    for (let i = 1; i < p.length - 1;) { const a = p[i - 1], b = p[i], c = p[i + 1]; if ((Math.abs(a.x - b.x) < 0.5 && Math.abs(b.x - c.x) < 0.5) || (Math.abs(a.y - b.y) < 0.5 && Math.abs(b.y - c.y) < 0.5)) p.splice(i, 1); else i++; }
    return p;
  };
  const segments = (pts) => { const s = []; for (let i = 1; i < pts.length; i++) s.push([pts[i - 1], pts[i]]); return s; };
  const touche = (s, r) => { const [a, b] = s; const x1 = Math.min(a.x, b.x), x2 = Math.max(a.x, b.x), y1 = Math.min(a.y, b.y), y2 = Math.max(a.y, b.y); return x2 > r.x1 && x1 < r.x2 && y2 > r.y1 && y1 < r.y2; };
  /** Croisement strict d'un segment horizontal et d'un segment vertical ; renvoie le point. */
  const croise = (s, t) => {
    const hs = horiz(s[0], s[1]), ht = horiz(t[0], t[1]); if (hs === ht) return null;
    const H = hs ? s : t, V = hs ? t : s; const y = H[0].y, xv = V[0].x;
    const hx1 = Math.min(H[0].x, H[1].x), hx2 = Math.max(H[0].x, H[1].x), vy1 = Math.min(V[0].y, V[1].y), vy2 = Math.max(V[0].y, V[1].y);
    return xv > hx1 + 0.5 && xv < hx2 - 0.5 && y > vy1 + 0.5 && y < vy2 - 0.5 ? { x: xv, y } : null;
  };
  /** Chevauchement colinéaire (longueur commune) de deux segments. */
  const recouvre = (s, t, tol) => {
    const hs = horiz(s[0], s[1]), ht = horiz(t[0], t[1]); if (hs !== ht) return 0;
    if (hs) { if (Math.abs(s[0].y - t[0].y) > tol) return 0; return Math.min(Math.max(s[0].x, s[1].x), Math.max(t[0].x, t[1].x)) - Math.max(Math.min(s[0].x, s[1].x), Math.min(t[0].x, t[1].x)); }
    if (Math.abs(s[0].x - t[0].x) > tol) return 0; return Math.min(Math.max(s[0].y, s[1].y), Math.max(t[0].y, t[1].y)) - Math.max(Math.min(s[0].y, s[1].y), Math.min(t[0].y, t[1].y));
  };
  const surSegment = (p, s) => { const [a, b] = s; return p.x >= Math.min(a.x, b.x) - 0.5 && p.x <= Math.max(a.x, b.x) + 0.5 && p.y >= Math.min(a.y, b.y) - 0.5 && p.y <= Math.max(a.y, b.y) + 0.5; };

  /** Tracé brut sans demi-tour (sinon null), puis simplifié. */
  function brut(pts) {
    const p = [];
    for (const q of pts) { const l = p[p.length - 1]; if (l && Math.abs(l.x - q.x) < 0.5 && Math.abs(l.y - q.y) < 0.5) continue; p.push(q); }
    for (let i = 1; i < p.length; i++) if (Math.abs(p[i].x - p[i - 1].x) > 0.5 && Math.abs(p[i].y - p[i - 1].y) > 0.5) return null;   // jamais de segment oblique
    for (let i = 2; i < p.length; i++) { const a = p[i - 2], b = p[i - 1], c = p[i]; const d0x = Math.sign(b.x - a.x), d0y = Math.sign(b.y - a.y), d1x = Math.sign(c.x - b.x), d1y = Math.sign(c.y - b.y); if (d0x === -d1x && d0y === -d1y) return null; }
    return simplifier(p);
  }
  function routerUn(p, dp, q, dq, ctx, reseau) {
    const a = { x: p.x + dp.x * STUB, y: p.y + dp.y * STUB }, b = { x: q.x + dq.x * STUB, y: q.y + dq.y * STUB };
    const xs = new Set([a.x, b.x, Math.round((a.x + b.x) / 2)]), ys = new Set([a.y, b.y, Math.round((a.y + b.y) / 2)]);
    const xmin = Math.min(a.x, b.x) - 160, xmax = Math.max(a.x, b.x) + 160, ymin = Math.min(a.y, b.y) - 160, ymax = Math.max(a.y, b.y) + 160;
    for (const r of ctx.obstacles) { if (r.mou) continue; for (const v of [r.x1 - 6, r.x2 + 6]) if (v > xmin && v < xmax) xs.add(Math.round(v)); for (const v of [r.y1 - 6, r.y2 + 6]) if (v > ymin && v < ymax) ys.add(Math.round(v)); }
    for (const v of ctx.canauxX) if (v > xmin && v < xmax) xs.add(v);
    for (const v of ctx.canauxY) if (v > ymin && v < ymax) ys.add(v);
    const evaluer = (pts) => {
      const segs = segments(pts); let c = 0, L = 0;
      segs.forEach((s, i) => {
        L += Math.abs(s[1].x - s[0].x) + Math.abs(s[1].y - s[0].y);
        for (const r of ctx.obstacles) {
          if (i === 0 && (r.id === ctx.de || r.id === ctx.de + ":etq")) continue; if (i === segs.length - 1 && (r.id === ctx.a || r.id === ctx.a + ":etq")) continue;
          if (touche(s, r)) c += r.mou ? 260 : 20000;
        }
        for (const o of ctx.poses) {
          if (o.reseaux.some(k => reseau.includes(k))) continue;
          for (const t of o.segs) {
            if (croise(s, t)) c += ctx.comm ? 90 : 140;
            const rc = recouvre(s, t, 0.5); if (rc > 0.5) c += 8000;
            else { const pr = recouvre(s, t, 7); if (pr > 0.5) c += 220; }
          }
        }
      });
      const inter = pts.slice(1, -1);
      for (const o of ctx.poses) { if (o.reseaux.some(k => reseau.includes(k))) continue; for (const t of o.segs) { for (const v of inter) if (surSegment(v, t)) c += 4000; for (const v of [t[0], t[1]]) for (const s of segs) if (surSegment(v, s)) c += 4000; } }
      return c + L + (pts.length - 2) * 14;
    };
    let best = null, bestC = Infinity;
    const essayer = (mil) => { const pts = brut([p, a, ...mil, b, q]); if (!pts) return; const c = evaluer(pts); if (c < bestC) { bestC = c; best = pts; } };
    // ports face à face sur la même ligne, plus proches que deux tronçons de sortie : segment direct (disjoncteur collé à son Powerwall)
    const face = dp.x === -dq.x && dp.y === -dq.y && (Math.abs(p.y - q.y) < 0.5 && dp.y === 0 && (q.x - p.x) * dp.x > 0 || Math.abs(p.x - q.x) < 0.5 && dp.x === 0 && (q.y - p.y) * dp.y > 0);
    if (face) { const pts = simplifier([p, q]); const c = evaluer(pts); if (c < bestC) { bestC = c; best = pts; } }
    if (Math.abs(a.x - b.x) < 0.5 || Math.abs(a.y - b.y) < 0.5) essayer([]);
    essayer([{ x: b.x, y: a.y }]); essayer([{ x: a.x, y: b.y }]);
    for (const X of xs) essayer([{ x: X, y: a.y }, { x: X, y: b.y }]);
    for (const Yc of ys) essayer([{ x: a.x, y: Yc }, { x: b.x, y: Yc }]);
    if (bestC >= 2000) {
      // Tracés en U (deux canaux) quand aucun tracé simple n'est propre : canaux les plus proches seulement
      const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
      const xl = [...xs].sort((u, v) => Math.abs(u - mx) - Math.abs(v - mx)).slice(0, 18), yl = [...ys].sort((u, v) => Math.abs(u - my) - Math.abs(v - my)).slice(0, 18);
      for (const X of xl) for (const Yc of yl) { essayer([{ x: a.x, y: Yc }, { x: X, y: Yc }, { x: X, y: b.y }]); essayer([{ x: X, y: a.y }, { x: X, y: Yc }, { x: b.x, y: Yc }]); }
    }
    return best || simplifier([p, a, b, q]);
  }

  /** Câble manuel avec coudes imposés : passe par chaque coude (segments horizontaux et verticaux). */
  function tracerCoudes(p, dp, q, dq, coudes) {
    const a = { x: p.x + dp.x * STUB, y: p.y + dp.y * STUB }, b = { x: q.x + dq.x * STUB, y: q.y + dq.y * STUB };
    const pts = [p, a]; let cur = a;
    for (const c of [...coudes, b]) { if (Math.abs(c.x - cur.x) > 0.5 && Math.abs(c.y - cur.y) > 0.5) pts.push({ x: c.x, y: cur.y }); pts.push(c); cur = c; }
    pts.push(q); return simplifier(pts);
  }

  /** Câblage complet : ports répartis, tracés, jonctions (points) et ponts (croisements). */
  function cabler(noeuds, fils) {
    const parId = Object.fromEntries(noeuds.map(x => [x.id, x]));
    const F = fils.filter(f => parId[f.de] && parId[f.a]).map(f => {
      const A = parId[f.de], B = parId[f.a]; const auto = coteAuto(A, B);
      return { ...f, dc: f.deCote || auto[0], ac: f.aCote || auto[1] };
    });
    // Groupes de port : les câbles d'une même barre (bus) partagent le port de départ
    for (const f of F) { f.gDe = f.bus ? `${f.de}:${f.dc}:${f.genre}` : `${f.cle}:de`; f.gA = `${f.cle}:a`; }
    const parCote = {};
    const inscrire = (id, cote, g, autre) => { const k = `${id}:${cote}`; (parCote[k] = parCote[k] || new Map()); const m = parCote[k]; const e = m.get(g) || { n: 0, s: 0 }; e.n++; e.s += autre; m.set(g, e); };
    for (const f of F) {
      const A = parId[f.de], B = parId[f.a]; const ca = centre(A), cb = centre(B);
      inscrire(f.de, f.dc, f.gDe, f.dc === "h" || f.dc === "b" ? cb.x : cb.y);
      inscrire(f.a, f.ac, f.gA, f.ac === "h" || f.ac === "b" ? ca.x : ca.y);
    }
    // Position de chaque port sur son côté : face à l'autre extrémité quand c'est possible (tracé droit), ordre conservé, écart minimal 14 px
    const posPorts = {};
    for (const [k, m] of Object.entries(parCote)) {
      const id = k.slice(0, k.lastIndexOf(":")), cote = k.slice(k.lastIndexOf(":") + 1); const nd = parId[id]; const vert = cote === "h" || cote === "b";
      const debut = vert ? nd.x : nd.y, long = vert ? nd.w : nd.h; const ecart = Math.min(14 / long, 0.76 / Math.max(1, m.size - 1));
      const l = [...m.entries()].map(([g, e]) => { const t = (e.s / e.n - debut) / long; return { g, t: m.size === 1 && (t < 0 || t > 1) ? 0.5 : Math.max(0.12, Math.min(0.88, t)) }; }).sort((u, v) => u.t - v.t);
      for (let i = 1; i < l.length; i++) l[i].t = Math.max(l[i].t, l[i - 1].t + ecart);
      const deb = l.length ? l[l.length - 1].t - 0.88 : 0; if (deb > 0) for (const e of l) e.t -= deb;
      for (let i = l.length - 2; i >= 0; i--) l[i].t = Math.min(l[i].t, l[i + 1].t - ecart);
      posPorts[k] = Object.fromEntries(l.map(e => [e.g, e.t]));
    }
    const tPort = (id, cote, g) => { const m = posPorts[`${id}:${cote}`]; return m && m[g] != null ? m[g] : 0.5; };
    const portsUtilises = {};
    for (const k of Object.keys(parCote)) { const [id, cote] = [k.slice(0, k.lastIndexOf(":")), k.slice(k.lastIndexOf(":") + 1)]; (portsUtilises[id] = portsUtilises[id] || new Set()).add(cote); }
    // Étiquettes : du côté libre (bas de préférence) ; leurs zones sont des obstacles mous pour le routage
    const etiquette = (nd, cote, decal = 0, dx = 0) => {
      const lw = Math.max(String(nd.nom || "").length * 6.2, String(nd.cote || "").length * 4.9, 20); const lh = nd.cote ? 30 : 18; const dy = nd.cote ? 2 : -4;
      const e = cote === "b" ? { x: nd.x + nd.w / 2, y: nd.y + nd.h + 16 + decal, anchor: "middle", r: { x1: nd.x + nd.w / 2 - lw / 2, x2: nd.x + nd.w / 2 + lw / 2, y1: nd.y + nd.h + 4 + decal, y2: nd.y + nd.h + 5 + lh + decal } }
        : cote === "bd" ? { x: nd.x + nd.w / 2 + 7, y: nd.y + nd.h + 16 + decal, anchor: "start", r: { x1: nd.x + nd.w / 2 + 4, x2: nd.x + nd.w / 2 + 9 + lw, y1: nd.y + nd.h + 4 + decal, y2: nd.y + nd.h + 5 + lh + decal } }
        : cote === "bg" ? { x: nd.x + nd.w / 2 - 7, y: nd.y + nd.h + 16 + decal, anchor: "end", r: { x1: nd.x + nd.w / 2 - 9 - lw, x2: nd.x + nd.w / 2 - 4, y1: nd.y + nd.h + 4 + decal, y2: nd.y + nd.h + 5 + lh + decal } }
        : cote === "d" ? { x: nd.x + nd.w + 8, y: nd.y + nd.h / 2 - dy + decal, anchor: "start", r: { x1: nd.x + nd.w + 5, x2: nd.x + nd.w + 10 + lw, y1: nd.y + nd.h / 2 - 13 + decal, y2: nd.y + nd.h / 2 + 15 + decal } }
        : cote === "g" ? { x: nd.x - 8, y: nd.y + nd.h / 2 - dy + decal, anchor: "end", r: { x1: nd.x - 10 - lw, x2: nd.x - 5, y1: nd.y + nd.h / 2 - 13 + decal, y2: nd.y + nd.h / 2 + 15 + decal } }
        : { x: nd.x + nd.w / 2, y: nd.y - (nd.cote ? 20 : 8) - decal, anchor: "middle", r: { x1: nd.x + nd.w / 2 - lw / 2, x2: nd.x + nd.w / 2 + lw / 2, y1: nd.y - 33 - decal, y2: nd.y - 4 - decal } };
      // décalage horizontal (sous ou au-dessus de l'appareil) : l'étiquette se range à côté d'un câble qui descend
      if (dx) { e.x += dx; e.r = { ...e.r, x1: e.r.x1 + dx, x2: e.r.x2 + dx }; }
      e.cote = cote; return e;
    };
    const etiquettes = {};
    const obstacles = [];
    for (const nd of noeuds) {
      const u = portsUtilises[nd.id] || new Set(); const cote = (nd.etq && !u.has(nd.etq) ? nd.etq : null) || ["b", "d", "g", "h"].find(c => !u.has(c)) || "b";
      const e = etiquette(nd, cote); etiquettes[nd.id] = e;
      obstacles.push({ id: nd.id, x1: nd.x - MARGE, x2: nd.x + nd.w + MARGE, y1: nd.y - MARGE, y2: nd.y + nd.h + MARGE });
      if (nd.nom || nd.cote) obstacles.push({ id: nd.id + ":etq", mou: true, ...e.r });
    }
    const canauxX = [], canauxY = [];
    for (const nd of noeuds) { canauxX.push(Math.round(nd.x - 22), Math.round(nd.x + nd.w + 22)); canauxY.push(Math.round(nd.y - 24), Math.round(nd.y + nd.h + 24), Math.round(nd.y + nd.h + 44)); }
    // Ordre : puissance d'abord (barres groupées), communication ensuite
    const ordre = F.slice().sort((u, v) => (estComm(u) - estComm(v)) || (u.manuel ? 1 : 0) - (v.manuel ? 1 : 0));
    const poses = [];
    for (const f of ordre) {
      const A = parId[f.de], B = parId[f.a];
      const p = port(A, f.dc, tPort(f.de, f.dc, f.gDe)), q = port(B, f.ac, tPort(f.a, f.ac, f.gA));
      const reseau = [f.gDe, f.gA];
      const pts = f.manuel && (f.coudes || []).length ? tracerCoudes(p, DIRS[f.dc], q, DIRS[f.ac], f.coudes)
        : routerUn(p, DIRS[f.dc], q, DIRS[f.ac], { obstacles, poses, canauxX, canauxY, de: f.de, a: f.a, comm: estComm(f) }, reseau);
      f.pts = pts; f.reseaux = reseau; poses.push({ segs: segments(pts), reseaux: reseau, f });
    }
    // Ponts : un segment horizontal saute chaque segment vertical d'un autre circuit qu'il croise
    for (const o of poses) {
      o.f.ponts = [];
      for (const s of o.segs) {
        if (!horiz(s[0], s[1])) continue;
        for (const t of poses) { if (t === o || t.reseaux.some(k => o.reseaux.includes(k))) continue; for (const u of t.segs) { const c = croise(s, u); if (c && horiz(u[0], u[1]) === false) o.f.ponts.push(c); } }
      }
    }
    // Placement final des étiquettes : première position qui ne touche ni câble, ni appareil, ni autre étiquette
    const tousSegs = poses.flatMap(o => o.segs);
    const inter = (a, b) => a.x1 < b.x2 && a.x2 > b.x1 && a.y1 < b.y2 && a.y2 > b.y1;
    const boites = noeuds.map(nd => ({ id: nd.id, x1: nd.x - 2, x2: nd.x + nd.w + 2, y1: nd.y - 2, y2: nd.y + nd.h + 2 }));
    const posees = [];
    for (const nd of noeuds) {
      if (!nd.nom && !nd.cote) continue;
      const ini = etiquettes[nd.id];
      const cands = [ini, etiquette(nd, "b"), etiquette(nd, "b", 22), etiquette(nd, "b", 42), etiquette(nd, "d"), etiquette(nd, "g"), etiquette(nd, "h"), etiquette(nd, "h", 16), etiquette(nd, "d", 30), etiquette(nd, "g", 30), etiquette(nd, "bd"), etiquette(nd, "bg"), etiquette(nd, "bd", 22), etiquette(nd, "bg", 22),
        etiquette(nd, "b", 0, 24), etiquette(nd, "b", 0, -24), etiquette(nd, "b", 0, 44), etiquette(nd, "b", 0, -44)];
      const libre = (e) => !tousSegs.some(sg => touche(sg, e.r)) && !boites.some(q => q.id !== nd.id && inter(q, e.r)) && !posees.some(q => inter(q, e.r)) && e.r.x1 >= ZONE.x - 4 && e.r.x2 <= ZONE.x + ZONE.w + 12 && e.r.y1 >= ZONE.y - 4 && e.r.y2 <= ZONE.y + ZONE.h + 14;
      // aucune position libre (schéma chargé) : la moins mauvaise ; hors de la zone de dessin (sous la légende) ou sur un appareil
      // coûte le plus cher, puis une autre étiquette, puis chaque câble traversé
      const cout = (e) => (e.r.x1 >= ZONE.x - 4 && e.r.x2 <= ZONE.x + ZONE.w + 12 && e.r.y1 >= ZONE.y - 4 && e.r.y2 <= ZONE.y + ZONE.h + 14 ? 0 : 1000)
        + (boites.some(q => q.id !== nd.id && inter(q, e.r)) ? 100 : 0) + (posees.some(q => inter(q, e.r)) ? 30 : 0) + tousSegs.filter(sg => touche(sg, e.r)).length * 5;
      const ch = cands.find(libre) || cands.reduce((b, e) => (cout(e) < cout(b) ? e : b), ini); etiquettes[nd.id] = ch; posees.push(ch.r);
    }
    // Jonctions : un point partout où au moins trois branches d'un même circuit se rejoignent
    const jonctions = [];
    const vus = new Set();
    for (const o of poses) {
      for (const v of o.f.pts) {
        const k = `${v.x},${v.y}`; if (vus.has(k)) continue;
        const dirs = new Set();
        for (const t of poses) {
          if (!t.reseaux.some(r => o.reseaux.includes(r))) continue;
          for (const [a, b] of t.segs) {
            if (!surSegment(v, [a, b])) continue;
            const ea = Math.abs(a.x - v.x) < 0.5 && Math.abs(a.y - v.y) < 0.5, eb = Math.abs(b.x - v.x) < 0.5 && Math.abs(b.y - v.y) < 0.5;
            const d = horiz(a, b) ? ["g", "d"] : ["h", "b"];
            const vers = (p) => horiz(a, b) ? (p.x < v.x ? "g" : "d") : (p.y < v.y ? "h" : "b");
            if (!ea && !eb) { dirs.add(d[0]); dirs.add(d[1]); } else dirs.add(vers(ea ? b : a));
          }
        }
        if (dirs.size >= 3) { vus.add(k); jonctions.push(v); }
      }
    }
    return { fils: F, jonctions, etiquettes };
  }
  /** Chemin SVG d'un câble, avec un pont en demi-cercle à chaque croisement. */
  function cheminPonts(pts, ponts) {
    const R = 5; let d = `M${pts[0].x} ${pts[0].y}`;
    for (let i = 1; i < pts.length; i++) {
      const a = pts[i - 1], b = pts[i];
      if (horiz(a, b) && ponts && ponts.length) {
        const s = Math.sign(b.x - a.x); const sur = ponts.filter(c => Math.abs(c.y - a.y) < 0.5 && (c.x - a.x) * s > R && (b.x - c.x) * s > R).sort((u, v) => (u.x - v.x) * s);
        for (const c of sur) d += ` L${c.x - R * s} ${a.y} A${R} ${R} 0 0 ${s > 0 ? 1 : 0} ${c.x + R * s} ${a.y}`;
      }
      d += ` L${b.x} ${b.y}`;
    }
    return d;
  }
  const chemin = (pts) => pts.map((p, i) => `${i ? "L" : "M"}${p.x.toFixed(1)} ${p.y.toFixed(1)}`).join(" ");
  // ───────────────────────── Symboles ─────────────────────────
  const T = ({ x, y, size = 11, w = "500", fill = COULEUR.trait, anchor = "middle", children, italic }) => <text x={x} y={y} fontSize={size} fontWeight={w} fill={fill} textAnchor={anchor} fontFamily="Helvetica, Arial, sans-serif" fontStyle={italic ? "italic" : "normal"}>{children}</text>;
  function Symbole({ n }) {
    const c = centre(n); const stroke = COULEUR.trait;
    const boite = (extra) => <rect x={n.x} y={n.y} width={n.w} height={n.h} rx={4} fill={COULEUR.boite} stroke={stroke} strokeWidth={1.8} {...extra} />;
    switch (n.type) {
      case "hq": return <g><circle cx={c.x} cy={c.y} r={28} fill="#fff" stroke={stroke} strokeWidth={2.2} /><T x={c.x} y={c.y + 5} size={15} w="800">HQ</T></g>;
      case "compteur": return <g>{boite()}<circle cx={n.x + 30} cy={c.y} r={17} fill="#fff" stroke={stroke} strokeWidth={1.6} /><T x={n.x + 30} y={c.y + 4} size={9} w="700">kWh</T><line x1={n.x + 56} y1={n.y + 14} x2={n.x + 56} y2={n.y + n.h - 14} stroke={stroke} strokeWidth={1} /><rect x={n.x + 64} y={c.y - 12} width={26} height={24} rx={2} fill="none" stroke={stroke} strokeWidth={1.4} /><line x1={n.x + 70} y1={c.y + 6} x2={n.x + 84} y2={c.y - 6} stroke={stroke} strokeWidth={2} /></g>;
      case "coffret": return <g>{boite()}<rect x={c.x - 28} y={c.y - 9} width={56} height={18} rx={3} fill="none" stroke={stroke} strokeWidth={1.6} /><line x1={c.x - 40} y1={c.y} x2={c.x - 28} y2={c.y} stroke={stroke} strokeWidth={1.6} /><line x1={c.x + 28} y1={c.y} x2={c.x + 40} y2={c.y} stroke={stroke} strokeWidth={1.6} /></g>;
      case "panneau": case "pcc": {
        const nb = n.type === "pcc" ? 4 : 6; const x0 = n.x + 16, y0 = n.y + 30;
        return <g>{boite()}<rect x={n.x + 10} y={n.y + 8} width={n.w - 20} height={12} rx={2} fill={stroke} />{Array.from({ length: nb }).map((_, i) => <g key={i}><rect x={x0 + (i % 2) * ((n.w - 32) / 2 + 4)} y={y0 + Math.floor(i / 2) * 18} width={(n.w - 36) / 2} height={11} rx={2} fill="none" stroke={stroke} strokeWidth={1.2} /><line x1={x0 + (i % 2) * ((n.w - 32) / 2 + 4) + 4} y1={y0 + Math.floor(i / 2) * 18 + 9} x2={x0 + (i % 2) * ((n.w - 32) / 2 + 4) + 14} y2={y0 + Math.floor(i / 2) * 18 + 2} stroke={stroke} strokeWidth={1.4} /></g>)}</g>;
      }
      case "gateway": return <g>{boite()}<rect x={n.x + 10} y={n.y + 10} width={n.w - 20} height={n.h - 20} rx={2} fill="none" stroke={stroke} strokeWidth={1} strokeDasharray="3 3" /><circle cx={n.x + n.w - 22} cy={c.y - 10} r={3} fill={stroke} /><rect x={n.x + 22} y={c.y - 6} width={34} height={12} rx={2} fill="none" stroke={stroke} strokeWidth={1.4} /><line x1={n.x + 26} y1={c.y + 4} x2={n.x + 40} y2={c.y - 3} stroke={stroke} strokeWidth={1.6} /><T x={c.x} y={n.y + n.h - 14} size={8} fill={COULEUR.gris}>DIM</T></g>;
      case "hub": return <g>{boite()}<rect x={n.x + 22} y={c.y - 8} width={34} height={14} rx={2} fill="none" stroke={stroke} strokeWidth={1.4} /><line x1={n.x + 26} y1={c.y + 4} x2={n.x + 40} y2={c.y - 4} stroke={stroke} strokeWidth={1.6} /><T x={c.x} y={n.y + n.h - 10} size={8} fill={COULEUR.gris}>DIM</T></g>;
      case "powerwall": return <g>{boite({ rx: 8 })}<rect x={n.x + 8} y={n.y + 10} width={n.w - 16} height={n.h - 42} rx={4} fill="none" stroke={stroke} strokeWidth={1} /><T x={c.x} y={n.y + n.h / 2 - 2} size={9} w="700">PW3</T><T x={c.x} y={n.y + n.h - 24} size={8}>≈ ~</T><T x={c.x} y={n.y + n.h - 10} size={7.5} fill={COULEUR.gris}>onduleur</T></g>;
      case "expansion": return <g>{boite({ rx: 8, strokeDasharray: "4 3" })}<rect x={n.x + 8} y={n.y + 10} width={n.w - 16} height={n.h - 42} rx={4} fill="none" stroke={stroke} strokeWidth={1} /><T x={c.x} y={n.y + n.h / 2} size={8} w="700">EXP</T><T x={c.x} y={n.y + n.h - 10} size={7.5} fill={COULEUR.gris}>batterie</T></g>;
      case "onduleur": return <g>{boite()}<line x1={n.x + 14} y1={n.y + n.h - 14} x2={n.x + n.w - 14} y2={n.y + 14} stroke={stroke} strokeWidth={1} /><T x={n.x + 26} y={n.y + 26} size={13} w="700">=</T><T x={n.x + n.w - 24} y={n.y + n.h - 14} size={13} w="700">~</T></g>;
      case "pile": { const k = n.cellules || 3; const hc = (n.h - 16) / k; return <g>{boite({ rx: 4 })}{Array.from({ length: k }).map((_, i) => <g key={i}><rect x={n.x + 8} y={n.y + 8 + i * hc} width={n.w - 16} height={hc - 3} rx={2} fill="none" stroke={stroke} strokeWidth={1} /><line x1={n.x + 14} y1={n.y + 8 + i * hc + (hc - 3) / 2} x2={n.x + 22} y2={n.y + 8 + i * hc + (hc - 3) / 2} stroke={stroke} strokeWidth={1.6} /><line x1={n.x + 26} y1={n.y + 8 + i * hc + 2} x2={n.x + 26} y2={n.y + 8 + i * hc + hc - 5} stroke={stroke} strokeWidth={1.6} /></g>)}</g>; }
      case "cpt_distant": return <g>{boite({ rx: 4 })}<circle cx={n.x + 16} cy={c.y} r={9} fill="none" stroke={stroke} strokeWidth={1.2} /><T x={n.x + 16} y={c.y + 3} size={7} w="700">CT</T><T x={n.x + 44} y={c.y + 4} size={9} w="700">RM</T></g>;
      case "module": return <g>{boite({ rx: 3 })}<line x1={n.x + 10} y1={c.y} x2={n.x + 22} y2={c.y} stroke={stroke} strokeWidth={2.2} /><line x1={n.x + 16} y1={c.y - 6} x2={n.x + 16} y2={c.y + 6} stroke={stroke} strokeWidth={2.2} /><line x1={n.x + 30} y1={c.y - 5} x2={n.x + 30} y2={c.y + 5} stroke={stroke} strokeWidth={2.2} /></g>;
      case "pv": return <g>{boite({ fill: "#0f172a" })}{Array.from({ length: 24 }).map((_, i) => <rect key={i} x={n.x + 8 + (i % 8) * 19.5} y={n.y + 8 + Math.floor(i / 8) * 21} width={16} height={17} fill="#1e3a8a" stroke="#93c5fd" strokeWidth={0.6} />)}</g>;
      case "rsd": return <g><rect x={n.x} y={n.y} width={n.w} height={n.h} rx={3} fill="#fff" stroke={stroke} strokeWidth={1.6} /><T x={c.x} y={c.y + 4} size={9} w="700">ARRÊT RAPIDE</T></g>;
      case "epo": return <g><circle cx={c.x} cy={c.y} r={15} fill="#fee2e2" stroke="#b91c1c" strokeWidth={1.8} /><circle cx={c.x} cy={c.y} r={7} fill="#b91c1c" /></g>;
      case "borne": return <g>{boite({ rx: 10 })}<rect x={n.x + 12} y={n.y + 12} width={n.w - 24} height={22} rx={3} fill="#e2e8f0" stroke={stroke} strokeWidth={1} /><path d={`M${c.x} ${n.y + n.h - 8} q 0 -16 12 -16`} fill="none" stroke={stroke} strokeWidth={2} /><circle cx={c.x + 14} cy={n.y + n.h - 24} r={4} fill="none" stroke={stroke} strokeWidth={1.6} /></g>;
      case "malt": return <g><line x1={c.x} y1={n.y} x2={c.x} y2={n.y + 8} stroke={stroke} strokeWidth={1.8} /><line x1={c.x - 14} y1={n.y + 8} x2={c.x + 14} y2={n.y + 8} stroke={stroke} strokeWidth={2} /><line x1={c.x - 9} y1={n.y + 14} x2={c.x + 9} y2={n.y + 14} stroke={stroke} strokeWidth={2} /><line x1={c.x - 4} y1={n.y + 20} x2={c.x + 4} y2={n.y + 20} stroke={stroke} strokeWidth={2} /></g>;
      case "routeur": return <g>{boite({ rx: 6, stroke: stroke })}<T x={c.x} y={c.y + 4} size={10} w="700" fill={stroke}>)))</T></g>;
      case "sectionneur": return <g>{boite()}<line x1={n.x + 8} y1={c.y} x2={n.x + n.w * 0.38} y2={c.y} stroke={stroke} strokeWidth={1.8} /><line x1={n.x + n.w * 0.38} y1={c.y} x2={n.x + n.w * 0.66} y2={c.y - 11} stroke={stroke} strokeWidth={1.8} /><line x1={n.x + n.w * 0.66} y1={c.y} x2={n.x + n.w - 8} y2={c.y} stroke={stroke} strokeWidth={1.8} />{/fus/i.test(n.nom || "") && <rect x={n.x + n.w * 0.66} y={c.y - 4} width={n.w * 0.2} height={8} fill="#fff" stroke={stroke} strokeWidth={1.2} />}</g>;
      case "disjoncteur": return <g>{boite()}<line x1={n.x + 6} y1={c.y + 5} x2={n.x + n.w - 8} y2={c.y - 6} stroke={stroke} strokeWidth={1.8} /><circle cx={n.x + 6} cy={c.y + 5} r={2} fill={stroke} /><circle cx={n.x + n.w - 8} cy={c.y - 6} r={2} fill={stroke} /></g>;
      case "transfo": return <g><circle cx={c.x - 10} cy={c.y} r={n.w * 0.3} fill="#fff" stroke={stroke} strokeWidth={1.8} /><circle cx={c.x + 10} cy={c.y} r={n.w * 0.3} fill="none" stroke={stroke} strokeWidth={1.8} /><T x={c.x} y={n.y - 4} size={8} fill={COULEUR.gris}>HT / BT</T></g>;
      case "ats": return <g>{boite()}<line x1={n.x + 10} y1={n.y + 14} x2={c.x - 6} y2={c.y} stroke={stroke} strokeWidth={1.8} /><line x1={n.x + 10} y1={n.y + n.h - 14} x2={c.x - 10} y2={c.y + 4} stroke={stroke} strokeWidth={1.4} strokeDasharray="3 2" /><line x1={c.x - 6} y1={c.y} x2={n.x + n.w - 10} y2={c.y} stroke={stroke} strokeWidth={1.8} /><T x={c.x} y={n.y + n.h - 6} size={8} w="700">ATS</T></g>;
      case "generatrice": return <g><circle cx={c.x} cy={c.y} r={Math.min(n.w, n.h) / 2 - 2} fill="#fff" stroke={stroke} strokeWidth={2} /><T x={c.x} y={c.y + 5} size={14} w="800">G</T><T x={c.x} y={c.y + 17} size={7} fill={COULEUR.gris}>~</T></g>;
      case "inlet": return <g>{boite({ rx: 8 })}<circle cx={c.x} cy={c.y} r={10} fill="none" stroke={stroke} strokeWidth={1.6} />{[0, 1, 2, 3].map(i => <circle key={i} cx={c.x + (i % 2 ? 5 : -5)} cy={c.y + (i < 2 ? -4 : 4)} r={1.6} fill={stroke} />)}</g>;
      case "parafoudre": return <g>{boite({ rx: 6 })}<path d={`M${c.x - 6} ${n.y + 6} l-4 10 h8 l-6 12 l12 -14 h-8 l4 -8 z`} fill={stroke} /></g>;
      case "jonction": return <g>{boite()}<line x1={n.x + 10} y1={n.y + 12} x2={n.x + n.w - 10} y2={n.y + 12} stroke={stroke} strokeWidth={1.6} /><line x1={n.x + 10} y1={n.y + n.h - 12} x2={n.x + n.w - 10} y2={n.y + n.h - 12} stroke={stroke} strokeWidth={1.6} /><line x1={c.x} y1={n.y + 12} x2={c.x} y2={n.y + n.h - 12} stroke={stroke} strokeWidth={1.6} /><T x={c.x} y={c.y + 3} size={7} fill={COULEUR.gris}>PV</T></g>;
      case "dongle": return <g>{boite({ rx: 6, stroke: stroke })}<T x={c.x} y={c.y + 4} size={9} w="700" fill={stroke}>{typeDongle(n.nom)}</T></g>;
      case "busbar": return <g>{boite({ rx: 3 })}<rect x={n.x + 8} y={c.y - 3} width={n.w - 16} height={6} fill={stroke} />{[0.25, 0.5, 0.75].map(k => <line key={k} x1={n.x + n.w * k} y1={n.y + 4} x2={n.x + n.w * k} y2={c.y - 3} stroke={stroke} strokeWidth={1.4} />)}</g>;
      case "armoire_bat": return <g>{boite()}<rect x={n.x + 8} y={n.y + 8} width={n.w - 16} height={n.h - 16} rx={2} fill="none" stroke={stroke} strokeWidth={1} strokeDasharray="3 2" />{[0, 1, 2].map(i => <rect key={i} x={n.x + 16} y={n.y + 14 + i * 15} width={n.w - 32} height={10} rx={2} fill="none" stroke={stroke} strokeWidth={1.1} />)}</g>;
      case "cable_comm": return <g><rect x={n.x} y={n.y} width={n.w} height={n.h} rx={3} fill="#fff" stroke={stroke} strokeWidth={1.2} /><line x1={n.x + 8} y1={c.y + 3} x2={n.x + n.w - 8} y2={c.y + 3} stroke={stroke} strokeWidth={1.2} strokeDasharray={FIL.tirets} /><T x={c.x} y={c.y - 5} size={7.5} fill={stroke}>comm.</T></g>;
      case "antenne": return <g><line x1={c.x} y1={n.y + 12} x2={c.x} y2={n.y + n.h} stroke={stroke} strokeWidth={1.8} /><path d={`M${c.x - 12} ${n.y + 4} q12 -10 24 0`} fill="none" stroke={stroke} strokeWidth={1.4} /><path d={`M${c.x - 7} ${n.y + 9} q7 -6 14 0`} fill="none" stroke={stroke} strokeWidth={1.4} /><T x={c.x} y={n.y + n.h + 10} size={7.5} fill={stroke}>LTE</T></g>;
      case "auget": return <g>{boite()}<rect x={n.x + 10} y={c.y - 4} width={n.w - 20} height={8} fill={stroke} /><T x={c.x} y={n.y + n.h - 8} size={7.5} fill={COULEUR.gris}>barre commune</T></g>;
      case "armoire": return <g>{boite()}<rect x={n.x + 12} y={n.y + 12} width={n.w - 24} height={n.h - 24} rx={2} fill="none" stroke={stroke} strokeWidth={1} /><circle cx={c.x - 14} cy={c.y} r={7} fill="none" stroke={stroke} strokeWidth={1.4} /><circle cx={c.x + 14} cy={c.y} r={7} fill="none" stroke={stroke} strokeWidth={1.4} /><T x={c.x} y={n.y + n.h - 6} size={7} fill={COULEUR.gris}>TC</T></g>;
      default: return boite();
    }
  }
  /** Texte du symbole d'un module de communication : LAN (Ethernet), 4G (cellulaire) ou Wi-Fi. */
  const typeDongle = (nom) => /ethernet|\bLAN\b/i.test(nom || "") && !/wi-?fi ou lan|wilan/i.test(nom || "") ? "LAN" : /4G|LTE|cellulaire/i.test(nom || "") ? "4G" : /wilan/i.test(nom || "") ? "WiLAN" : "Wi-Fi";
  const EnTeteLogo = ({ x, y }) => <g transform={`translate(${x}, ${y})`}><path d="M18 0 L6 24 L15 24 L10 46 L28 18 L19 18 L24 0 Z" fill="#0a6fc8" /><T x={38} y={22} size={20} w="900" anchor="start" fill={COULEUR.bleu}>RAYCOM</T><T x={39} y={38} size={9.5} w="700" anchor="start" fill={COULEUR.gris}>ÉLECTRIQUE inc.</T></g>;
  const Numero = ({ x, y, n }) => <g><circle cx={x} cy={y} r={9} fill={COULEUR.bleu} stroke="#fff" strokeWidth={1.5} /><T x={x} y={y + 3.5} size={9.5} w="800" fill="#fff">{n}</T></g>;
  const Grip = ({ x, y }) => <g className="rc-sch-ui rc-sch-grip" pointerEvents="none">{[0, 1, 2].map(i => [0, 1].map(j => <circle key={i + "-" + j} cx={x + j * 4} cy={y + i * 4} r={1.2} fill={COULEUR.ui} />))}</g>;

  // ───────────────────────── Page SVG complète ─────────────────────────
  function Page({ modele: m, construit, editable, onDrag, selection, onSelect, svgRef, logoData, outil, onPort, portEnAttente, onResize, selectionFil, onFilSelect, onCoudeDrag, onAjouterCoude, onAnnotationDrag, onAnnotationSelect, glisse }) {
    const { noeuds, fils, annotations = [] } = construit || construire(m);
    const sel = new Set(Array.isArray(selection) ? selection : selection ? [selection] : []);
    const cab = useMemo(() => cabler(noeuds, fils), [noeuds, fils]);
    const legende = noeuds.filter(x => x.num).sort((a, b) => a.num - b.num);
    const c = m.client || {}, hq = m.hq || {};
    const meta = [m.meta.dossier ? `Dossier ${m.meta.dossier}` : "Dossier à attribuer", `Version ${m.meta.version || "v1"}`, `Date ${m.meta.date || ""}`];
    return (
      <svg ref={svgRef} viewBox={`0 0 ${PAGE.w} ${PAGE.h}`} width="100%" xmlns="http://www.w3.org/2000/svg" fontFamily="Helvetica, Arial, sans-serif" className={editable ? "rc-sch-scene" + (glisse ? " glisse" : "") : undefined}>
        <rect x={0} y={0} width={PAGE.w} height={PAGE.h} fill="#fff" />
        {/* Bandeau générique, identique pour tous les schémas */}
        <g data-bandeau="1">
          {logoData ? <image href={logoData} x={36} y={22} width={210} height={70} preserveAspectRatio="xMinYMid meet" /> : <EnTeteLogo x={36} y={30} />}
          <T x={PAGE.w / 2} y={58} size={28} w="800" fill={COULEUR.bleu}>SCHÉMA UNIFILAIRE</T>
          <T x={PAGE.w / 2} y={86} size={12} w="700" fill={COULEUR.secours}>Conforme à la norme E.12-07 d'Hydro-Québec · CSA C22.10:26 (CÉQ 2026)</T>
          {meta.map((t, i) => <T key={i} x={PAGE.w - 36} y={44 + i * 20} size={i ? 11 : 13} w={i ? "600" : "800"} anchor="end" fill={i ? COULEUR.gris : COULEUR.trait}>{t}</T>)}
          <line x1={36} y1={116} x2={PAGE.w - 36} y2={116} stroke={COULEUR.bleu} strokeWidth={2.5} />
        </g>
        {/* Câbles : une seule couleur, tracé orthogonal continu, ponts aux croisements */}
        <g data-cablage="1">
          {cab.fils.map((f, i) => {
            const comm = estComm(f); const d = cheminPonts(f.pts, f.ponts); const s = editable && selectionFil === f.cle;
            return <g key={f.cle || i} data-fil={f.cle} data-de={f.de} data-a={f.a} data-genre={comm ? "comm" : "puissance"} style={editable ? { cursor: "pointer" } : undefined}
              onClick={editable && onFilSelect ? (e) => { e.stopPropagation(); onFilSelect(f.cle); } : undefined}
              onDoubleClick={editable && f.manuel && onAjouterCoude ? (e) => { e.stopPropagation(); onAjouterCoude(e, f.cle); } : undefined}>
              {editable && <path className="rc-sch-ui" d={d} fill="none" stroke="transparent" strokeWidth={12} />}
              {s && <path className="rc-sch-ui" d={d} fill="none" stroke="#93c5fd" strokeWidth={7} opacity={0.7} />}
              <path className="rc-fil" d={d} fill="none" stroke={FIL.couleur} strokeWidth={comm ? FIL.comm : FIL.puissance} strokeDasharray={comm ? FIL.tirets : undefined} strokeLinejoin="miter" strokeLinecap="butt" />
              {f.manuel && f.calibre && (() => { const mi = milieu(f.pts); return <g><rect x={mi.x - 30} y={mi.y - 17} width={60} height={12} rx={2} fill="#fff" /><T x={mi.x} y={mi.y - 8} size={7.5}>{f.calibre}</T></g>; })()}
              {s && f.manuel && (f.coudes || []).map((p, k) => <circle key={k} className="rc-sch-ui" cx={p.x} cy={p.y} r={5} fill="#fff" stroke={COULEUR.ui} strokeWidth={1.6} style={{ cursor: "move" }} onMouseDown={onCoudeDrag ? (e) => { e.stopPropagation(); onCoudeDrag(e, f.cle, k); } : undefined} />)}
            </g>;
          })}
          {cab.jonctions.map((p, i) => <circle key={i} className="rc-sch-jonction" cx={p.x} cy={p.y} r={3.2} fill={FIL.couleur} />)}
        </g>
        {/* Appareils : tout le corps est saisissable */}
        <g>
          {noeuds.map(n => { const e = cab.etiquettes[n.id] || { x: n.x + n.w / 2, y: n.y + n.h + 16, anchor: "middle" }; const s = sel.has(n.id); return (
            <g key={n.id} data-id={n.id} data-type={n.type} data-box={`${n.x},${n.y},${n.w},${n.h}`} className={editable ? "rc-sch-noeud" + (s ? " sel" : "") : undefined} style={editable ? { cursor: outil === "cable" ? "crosshair" : undefined } : undefined}
              onMouseDown={editable && onDrag && outil !== "cable" ? (ev) => onDrag(ev, n.id) : undefined} onClick={editable && onSelect ? (ev) => { ev.stopPropagation(); onSelect(n.id, ev); } : undefined}>
              {editable && <rect className="rc-sch-ui rc-sch-prise" x={n.x - 4} y={n.y - 4} width={n.w + 8} height={n.h + 8} rx={5} fill="#fff" fillOpacity={0.001} />}
              {s && <rect className="rc-sch-ui" x={n.x - 6} y={n.y - 6} width={n.w + 12} height={n.h + 12} rx={6} fill="none" stroke={COULEUR.ui} strokeWidth={1.5} strokeDasharray="4 3" />}
              <Symbole n={n} />
              {n.nom && <T x={e.x} y={e.y} size={n.type === "module" ? 9 : 10.5} w="700" anchor={e.anchor}>{n.nom}</T>}
              {n.cote && <T x={e.x} y={e.y + 13} size={8.5} fill={COULEUR.gris} anchor={e.anchor}>{n.cote}</T>}
              {n.num && <Numero x={n.x + n.w - 2} y={n.y + 2} n={n.num} />}
              {editable && outil !== "cable" && <Grip x={n.x + 3} y={n.y + 3} />}
              {editable && outil === "cable" && ["g", "d", "h", "b"].map(cote => { const q = port(n, cote); const att = portEnAttente && portEnAttente.id === n.id && portEnAttente.cote === cote; return <circle key={cote} className="rc-sch-ui rc-sch-port" cx={q.x} cy={q.y} r={att ? 7 : 5} fill={att ? COULEUR.ui : "#fff"} stroke={COULEUR.ui} strokeWidth={1.6} style={{ cursor: "crosshair" }} onMouseDown={(ev) => { ev.stopPropagation(); ev.preventDefault(); }} onClick={(ev) => { ev.stopPropagation(); onPort && onPort(n.id, cote); }} />; })}
              {editable && s && sel.size === 1 && outil !== "cable" && onResize && <rect className="rc-sch-ui rc-sch-poignee" x={n.x + n.w - 5} y={n.y + n.h - 5} width={10} height={10} fill={COULEUR.ui} stroke="#fff" strokeWidth={1.2} style={{ cursor: "nwse-resize" }} onMouseDown={(ev) => { ev.stopPropagation(); ev.preventDefault(); onResize(ev, n.id); }} />}
            </g>); })}
        </g>
        {/* Annotations */}
        <g>
          {annotations.map(a => (
            <g key={a.id} data-annotation={a.id} className={editable ? "rc-sch-noeud" : undefined} onMouseDown={editable && onAnnotationDrag ? (e) => onAnnotationDrag(e, a.id) : undefined} onClick={editable && onAnnotationSelect ? (e) => { e.stopPropagation(); onAnnotationSelect(a.id); } : undefined}>
              {sel.has(a.id) && <rect className="rc-sch-ui" x={a.x - 6} y={a.y - (a.taille || 11) - 4} width={Math.max(40, String(a.texte || "").length * (a.taille || 11) * 0.58) + 12} height={(a.taille || 11) + 12} rx={4} fill="none" stroke={COULEUR.ui} strokeWidth={1.2} strokeDasharray="4 3" />}
              <T x={a.x} y={a.y} size={a.taille || 11} w="600" anchor="start" fill={a.couleur || COULEUR.trait}>{a.texte || ""}</T>
            </g>
          ))}
        </g>
        {/* Légende */}
        <g>
          <rect x={LEG.x} y={LEG.y} width={LEG.w} height={LEG.h} rx={6} fill="#fff" stroke={COULEUR.bleu} strokeWidth={1.5} />
          <rect x={LEG.x} y={LEG.y} width={LEG.w} height={30} rx={6} fill={COULEUR.bleu} />
          <T x={LEG.x + LEG.w / 2} y={LEG.y + 20} size={11.5} w="800" fill="#fff">LÉGENDE · IDENTIFICATION DES COMPOSANTS</T>
          {legende.map((n, i) => { const pas = legende.length > 12 ? Math.floor(540 / legende.length) : 44; const y = LEG.y + 54 + i * pas; return <g key={n.id}><Numero x={LEG.x + 20} y={y - 4} n={n.num} /><T x={LEG.x + 38} y={y} size={10} w="700" anchor="start">{String((n.leg || [n.nom])[0] || n.nom || "").slice(0, 62)}</T>{(n.leg || [])[1] && pas >= 30 && <T x={LEG.x + 38} y={y + 13} size={8.5} anchor="start" fill={COULEUR.gris}>{String(n.leg[1]).slice(0, 72)}</T>}{(n.leg || [])[2] && pas >= 40 && <T x={LEG.x + 38} y={y + 25} size={8} anchor="start" fill={COULEUR.gris} italic>{n.leg[2]}</T>}</g>; })}
          <g transform={`translate(${LEG.x + 16}, ${LEG.y + LEG.h - 40})`}>
            <line x1={0} y1={0} x2={34} y2={0} stroke={FIL.couleur} strokeWidth={FIL.puissance} /><T x={42} y={4} size={8.5} anchor="start" fill={COULEUR.gris}>Conducteurs (CA et CC)</T>
            <line x1={170} y1={0} x2={204} y2={0} stroke={FIL.couleur} strokeWidth={FIL.comm} strokeDasharray={FIL.tirets} /><T x={212} y={4} size={8.5} anchor="start" fill={COULEUR.gris}>Communication</T>
            <circle cx={17} cy={18} r={3.2} fill={FIL.couleur} /><line x1={0} y1={18} x2={34} y2={18} stroke={FIL.couleur} strokeWidth={FIL.puissance} /><line x1={17} y1={18} x2={17} y2={28} stroke={FIL.couleur} strokeWidth={FIL.puissance} /><T x={42} y={22} size={8.5} anchor="start" fill={COULEUR.gris}>Jonction</T>
            <path d="M170 18 L182 18 A5 5 0 0 1 192 18 L204 18" fill="none" stroke={FIL.couleur} strokeWidth={FIL.puissance} /><line x1={187} y1={8} x2={187} y2={28} stroke={FIL.couleur} strokeWidth={FIL.puissance} /><T x={212} y={22} size={8.5} anchor="start" fill={COULEUR.gris}>Croisement sans contact</T>
          </g>
        </g>
        {/* Cartouche : populée selon les composantes du schéma */}
        <g data-cartouche="1">
          <rect x={CART.x} y={CART.y} width={CART.w} height={CART.h} fill="#fff" stroke={COULEUR.bleu} strokeWidth={1.5} />
          {[0, 1, 2].map(i => <line key={i} x1={CART.x + CART.w / 4 * (i + 1)} y1={CART.y} x2={CART.x + CART.w / 4 * (i + 1)} y2={CART.y + CART.h} stroke={COULEUR.bleu} strokeWidth={1} />)}
          <Bloc x={CART.x} y={CART.y} titre="CLIENT" lignes={[["Nom", c.nom], ["Adresse", c.adresse1], ["", c.adresse2], ["Tél.", c.telephone], ["Courriel", c.courriel]]} />
          <Bloc x={CART.x + CART.w / 4} y={CART.y} titre="IDENTIFICATION HYDRO-QUÉBEC" lignes={[["N° client", hq.numero_client || "à confirmer"], ["N° contrat", hq.numero_contrat || "à confirmer"], ["N° compteur", hq.numero_compteur || "à confirmer"], ["Titulaire", hq.titulaire || c.nom], ["Tarif", hq.tarif], ["N° dossier", hq.dossier || m.meta.dossier], ["Norme", "E.12-07 · CSA C22.10:26 (CÉQ 2026)"]]} />
          <Bloc x={CART.x + CART.w / 2} y={CART.y} titre="CARACTÉRISTIQUES DU SYSTÈME" lignes={caracteristiques(m, noeuds)} />
          <BlocEntrepreneur x={CART.x + CART.w * 3 / 4} y={CART.y} />
        </g>
      </svg>
    );
  }
  const milieu = (pts) => { let L = 0; const seg = []; for (let i = 1; i < pts.length; i++) { const d = Math.abs(pts[i].x - pts[i - 1].x) + Math.abs(pts[i].y - pts[i - 1].y); seg.push(d); L += d; } let t = L / 2; for (let i = 1; i < pts.length; i++) { if (t <= seg[i - 1]) { const k = seg[i - 1] ? t / seg[i - 1] : 0; return { x: pts[i - 1].x + (pts[i].x - pts[i - 1].x) * k, y: pts[i - 1].y + (pts[i].y - pts[i - 1].y) * k }; } t -= seg[i - 1]; } return pts[0]; };
  /** Caractéristiques dérivées des composantes réellement présentes sur le schéma (une ligne absente quand la composante n'y est pas). */
  // Valeurs d'un appareil pour la cartouche : d'abord celles du générateur (kw, kwh), sinon la cote saisie (prioritaire, c'est la
  // correction de l'électricien), sinon le nom ; une plage ou un choix (« 6/9 kWh », « 5.0 / 8.0 / 11.4 kW », « 440-460 W ») ne donne
  // aucune valeur plutôt qu'une fausse (JF, 5 nov. 2026 : attention aux erreurs).
  const nombreCart = (t) => Number(String(t).replace(",", "."));
  function valeurDans(textes, re) {
    for (const t of textes) {
      const txt = String(t || "");
      const mm = txt.match(re);
      if (!mm) continue;
      const avant = txt.slice(Math.max(0, mm.index - 2), mm.index), apres = txt.slice(mm.index + mm[0].length, mm.index + mm[0].length + 2);
      if (/[\/–-]\s*$/.test(avant) || /^\s*[\/–-]/.test(apres)) return null; // plage ou choix : on ne devine pas
      return nombreCart(mm[1]);
    }
    return null;
  }
  const ONDULEUR_CLES = new Set(["foxess_h1", "foxess_aio_h1", "sigen_inverter", "solark", "solis_s6", "luxpower_lxp12k", "fronius_primo", "enphase_micro", "powerwall_3"]);
  function valeursAppareil(n) {
    const textes = [n.cote, n.nom, ...(Array.isArray(n.leg) ? n.leg.slice(0, 2) : [])];
    const pv = n.type === "pv" ? (() => {
      const t = [n.cote, n.nom].map(x => String(x || ""));
      for (const x of t) { const mm = x.match(/(\d+)\s*[×x]\s*(\d{3})\s*W\b/i); if (mm) return { nb: Number(mm[1]), w: Number(mm[2]), kw: r1(Number(mm[1]) * Number(mm[2]) / 1000) }; }
      const kwc = valeurDans([n.cote], /(\d+(?:[.,]\d+)?)\s*kW(?!h)/i); return kwc ? { kw: kwc } : null;
    })() : null;
    const kw = Number(n.kw) > 0 ? Number(n.kw) : (n.type === "powerwall" || n.type === "onduleur" || ONDULEUR_CLES.has(n.cle)) ? (valeurDans(textes, /(\d+(?:[.,]\d+)?)\s*kW(?!h)/i) || valeurDans(textes, /\b(\d{1,2})\s*K\b/)) : null;
    const kwh = Number(n.kwh) > 0 ? Number(n.kwh) : valeurDans(textes, /(\d+(?:[.,]\d+)?)\s*kWh/i);
    return { pv, kw: kw || 0, kwh: kwh || 0 };
  }
  // Libellé d'un appareil pour la cartouche : appareil ajouté = son nom (sans la parenthèse descriptive) ; appareil généré par le
  // devis = le titre de sa légende (« 2 × Tesla Powerwall 3 · … » → « Tesla Powerwall 3 »), jamais « no 1 », « no 2 ».
  const libelleCourt = (n) => {
    const nettoie = (t) => String(t || "").replace(/^\d+ × /, "").replace(/\s+no\s+\d+$/i, "").replace(/\s*\([^)]*\)\s*$/, "").trim();
    if (n.ajout) return nettoie(n.nom || (n.leg || [])[0]);
    const tete = nettoie(String((n.leg || [])[0] || "").split(" · ")[0]);
    return tete && !/^DIM$/i.test(tete) ? tete : nettoie(n.nom);
  };

  /** Caractéristiques dérivées des composantes réellement présentes sur le schéma, générées par le devis OU ajoutées depuis la
   *  palette (une ligne absente quand la composante n'y est pas). Les valeurs inconnues ne sont jamais inventées : le nom suffit. */
  function caracteristiques(m, noeuds) {
    const de = (types, cles) => noeuds.filter(n => types.includes(n.type) || (cles && cles.has(n.cle)));
    // Regroupe par libellé ; les appareils générés d'un même type (Powerwall no 1, no 2…) prennent le libellé du premier.
    const grouper = (liste) => {
      const c = new Map(); const premier = {};
      for (const n of liste) { const cle = n.ajout ? "aj:" + libelleCourt(n) : "gen:" + n.type; if (!premier[cle]) premier[cle] = libelleCourt(n); c.set(cle, (c.get(cle) || 0) + 1); }
      return [...c.entries()].filter(([k]) => premier[k]).map(([k, q]) => (q > 1 ? `${q} × ${premier[k]}` : premier[k])).join(", ");
    };
    const l = [["Service", `${m.service.calibre} A · ${m.service.tension} · 1 Ø${m.service.embase === "meter_main" ? " · embase avec disjoncteur" : ""}`]];
    // Puissance CC : champ PV généré par le devis + modules ajoutés (cote « 16 × 500 W » ou « 8 kW »)
    const pv = de(["pv"]);
    if (pv.length) {
      let kw = 0, nb = 0, w = 0, inconnus = [];
      for (const n of pv) {
        if (n.id === "pv" && Number(m.pv.nb) > 0) { kw += kwPv(m); nb += Number(m.pv.nb); w = Number(m.pv.watts) || w; continue; }
        const v = valeursAppareil(n).pv; if (v && v.kw) { kw += v.kw; if (v.nb) { nb += v.nb; w = v.w; } } else inconnus.push(n);
      }
      const txt = kw ? `${fmt(r1(kw))} kW${nb ? ` (${nb} × ${w} W)` : ""}${inconnus.length ? " + " + grouper(inconnus) : ""}` : grouper(pv);
      l.push(["Puissance CC", txt]);
    }
    // Puissance CA : onduleurs et Powerwall (générés ou ajoutés)
    const ond = de(["powerwall", "onduleur"], ONDULEUR_CLES);
    if (ond.length) {
      const vals = ond.map(valeursAppareil); const kw = r1(vals.reduce((s, v) => s + v.kw, 0)); const tous = vals.every(v => v.kw > 0);
      l.push(["Puissance CA", kw ? `${fmt(kw)} kW${tous ? "" : " et plus"} (${grouper(ond)})` : grouper(ond)]);
    }
    // Stockage : Powerwall, expansions, piles et modules de batterie (hors onduleurs classés « module » dans la palette)
    const st = de(["powerwall", "expansion", "pile", "module"]).filter(n => n.cle !== "foxess_h1");
    if (st.length) {
      const vals = st.map(valeursAppareil); const kwh = r1(vals.reduce((s, v) => s + v.kwh, 0)); const tous = vals.every(v => v.kwh > 0);
      l.push(["Stockage", kwh ? `${fmt(kwh)} kWh${tous ? "" : " et plus"}` : grouper(st)]);
    }
    const dim = de(["gateway", "hub"]);
    if (dim.length) l.push(["DIM", grouper(dim)]);
    // Secours : panneau de charges critiques présent (généré ou ajouté) = partiel ; sinon ce que dit le devis
    const pcc = de(["pcc"]);
    const sec = pcc.length ? "partiel" : (m.systeme || {}).secours;
    if (sec && sec !== "aucun" && (dim.length || pcc.length)) {
      const amp = pcc.length ? (valeurDans([pcc[0].cote, pcc[0].nom], /(\d{2,3})\s*A\b/i) || m.systeme.panneau_critique || 100) : (m.systeme.panneau_critique || 100);
      // Petit kit Tesla : la Gateway 3 contient les charges critiques et sert de panneau de secours
      const dansGw = dim.some(n => n.type === "gateway");
      l.push(["Secours", sec === "complet" ? "maison complète" : sec === "partiel" ? `partiel · charges critiques ${amp} A` : dansGw ? "partiel, charges critiques dans la passerelle" : "de base (circuits de la passerelle)"]);
    }
    // Arrêt rapide : la cote porte la quantité (« 6 × MCI Tesla ») ; sinon le libellé regroupé
    const rsd = de(["rsd"]);
    if (rsd.length) { const avecQte = rsd.filter(n => /\d+\s*×/.test(String(n.cote || ""))); const autres = rsd.filter(n => !avecQte.includes(n)); l.push(["Arrêt rapide", `${[...avecQte.map(n => n.cote), grouper(autres)].filter(Boolean).join(", ")} · art. 64-218`]); }
    // Bornes : nombre × modèle, avec la cote (ampérage) quand elle est connue
    const bo = de(["borne"]);
    // (nom court de l'appareil : la ligne de la cartouche est limitée à 52 caractères)
    if (bo.length) { const cote = (bo.find(n => n.cote) || {}).cote; const nom = String(bo[0].nom || libelleCourt(bo[0])).replace(/\s*\([^)]*\)\s*$/, "").replace(/\s+no\s+\d+$/i, ""); l.push(["Bornes", `${bo.length} × ${nom}${cote ? " · " + cote : ""}`]); }
    return l;
  }
  const Bloc = ({ x, y, titre, lignes }) => <g><T x={x + 14} y={y + 24} size={11} w="800" anchor="start" fill={COULEUR.bleu}>{titre}</T><line x1={x + 14} y1={y + 32} x2={x + CART.w / 4 - 14} y2={y + 32} stroke={COULEUR.secours} strokeWidth={1.5} />{lignes.filter(l => l && (l[1] || l[0])).slice(0, 8).map((l, i) => <g key={i}><T x={x + 14} y={y + 54 + i * 24} size={9} anchor="start" fill={COULEUR.gris}>{l[0] ? l[0] + " :" : ""}</T><T x={x + 92} y={y + 54 + i * 24} size={10} w={i === 0 && titre === "CLIENT" ? "800" : "600"} anchor="start">{String(l[1] || "").slice(0, 52)}</T></g>)}</g>;
  /** Sceau du maître électricien, relevé tel quel du « TAMPON » de l'ancien Raycom Schema Builder (02_Templates,
   *  Raycom_Schema_Builder.html : cercle r 55 trait 2,5, cercle intérieur r 48, textes en arc sur r 42), avec l'éclair Raycom
   *  officiel (eclair-raycom.svg) au centre. Vectoriel : net dans l'aperçu, le PDF et le PNG. Copie autonome : assets/sceau-maitre-electricien.svg */
  // Texte en arc, lettre par lettre (rendu identique partout, sans dépendre de textPath dans l'export image)
  const LARG = { " ": 0.3, I: 0.3, "-": 0.36, ".": 0.3, M: 0.8, W: 0.86 };
  function TexteArc({ texte, r, taille, poids, espace = 0, haut }) {
    const lettres = [...texte]; const larg = lettres.map(ch => (LARG[ch] != null ? LARG[ch] : /[0-9]/.test(ch) ? 0.56 : 0.64) * taille + espace);
    const total = larg.reduce((a, b) => a + b, 0) - espace; let cumul = -total / 2;
    return <g data-texte={texte}>{lettres.map((ch, i) => {
      const milieu = cumul + (larg[i] - espace) / 2; cumul += larg[i];
      const a = haut ? -Math.PI / 2 + milieu / r : Math.PI / 2 - milieu / r;
      const deg = a * 180 / Math.PI + (haut ? 90 : -90);
      return <text key={i} x={0} y={0} transform={`translate(${(r * Math.cos(a)).toFixed(2)}, ${(r * Math.sin(a)).toFixed(2)}) rotate(${deg.toFixed(2)})`} textAnchor="middle" fill="#0a2540" fontSize={taille} fontWeight={poids} fontFamily="Helvetica, Arial, sans-serif">{ch}</text>;
    })}</g>;
  }
  function Sceau({ x, y, r = 55 }) {
    const k = r / 55;
    return <g transform={`translate(${x}, ${y}) scale(${k})`} className="rc-sch-sceau" data-sceau="maitre-electricien">
      <circle cx={0} cy={0} r={55} fill="#fff" stroke="#0a2540" strokeWidth={2.5} />
      <circle cx={0} cy={0} r={48} fill="none" stroke="#0a2540" strokeWidth={0.8} />
      <TexteArc texte="MAÎTRE ÉLECTRICIEN" r={42} taille={8} poids="700" espace={0.6} haut />
      <TexteArc texte="RBQ 5590-9402-01" r={42} taille={7} poids="600" espace={0.5} />
      <text x={0} y={-3} textAnchor="middle" fill="#0a2540" fontSize={9} fontWeight="700" fontFamily="Helvetica, Arial, sans-serif">JEAN-FRANÇOIS</text>
      <text x={0} y={9} textAnchor="middle" fill="#0a2540" fontSize={9} fontWeight="700" fontFamily="Helvetica, Arial, sans-serif">RAYLE</text>
      <g transform="translate(-6.3, 13) scale(0.026)"><polygon points="300,0 195,288 389,288 78,696 184,406 0,405" fill="#0a6fc8" /></g>
    </g>;
  }
  const BlocEntrepreneur = ({ x, y }) => { const w = CART.w / 4; return <g>
    <T x={x + 14} y={y + 24} size={11} w="800" anchor="start" fill={COULEUR.bleu}>ENTREPRENEUR ÉLECTRICIEN</T>
    <line x1={x + 14} y1={y + 32} x2={x + w - 14} y2={y + 32} stroke={COULEUR.secours} strokeWidth={1.5} />
    <T x={x + 14} y={y + 54} size={10.5} w="800" anchor="start">{ENTREPRISE.nom}</T>
    <T x={x + 14} y={y + 72} size={9.5} anchor="start">3321 av. de la Gare, bureau 112</T>
    <T x={x + 14} y={y + 86} size={9.5} anchor="start">Mascouche (Québec) J7K 0X7</T>
    <T x={x + 14} y={y + 104} size={9.5} anchor="start">{ENTREPRISE.tel} · {ENTREPRISE.courriel}</T>
    <T x={x + 14} y={y + 118} size={9.5} w="700" anchor="start" fill={COULEUR.secours}>{ENTREPRISE.site}</T>
    <T x={x + 14} y={y + 138} size={10} w="800" anchor="start">{ENTREPRISE.rbq}</T>
    <T x={x + 14} y={y + 152} size={9} anchor="start" fill={COULEUR.gris}>Jean-François Rayle, maître électricien (CMEQ)</T>
    <Sceau x={x + w - 74} y={y + 104} />
  </g>; };

  // ───────────────────────── Génération depuis la soumission : le schéma représente le devis ─────────────────────────
  /** Lignes du devis (quantité > 0) avec leur nom d'article et leur groupe (CALC_RE.compute). Aucune valeur par défaut du parcours. */
  function lignesDuDevis(state) {
    const cat = window.CatalogueRE && window.CatalogueRE._cache && window.CatalogueRE._cache();
    const byId = cat && cat.byId && typeof cat.byId.get === "function" ? cat.byId : new Map();
    let calc = null; try { if (window.CALC_RE && window.CALC_RE.compute) calc = window.CALC_RE.compute(state, cat || { byId }); } catch (e) { calc = null; }
    const src = state.lignes || [];
    return src.map((l, i) => {
      const a = byId.get(l.qbo_id) || null; const c = calc && calc.lignes ? calc.lignes[i] : null;
      return { qbo_id: l.qbo_id, qty: Number(l.qty) || 0, nom: (a && a.nom) || l.nom || "", article: a || {}, groupe: (c && c.groupe) || l.groupe || "" };
    }).filter(l => l.qty > 0 && l.nom);
  }
  const SERVICE_RE = /^(Installation|Câblage|Cablage|Mise en service|Préfilage|Prefilage|Branchement|Levage|Raccordement|Info|Promotion|Déplacement|Manutention|Démolition|Hébergement|Service|Travail|Harnais|Hub de conduit|Kit|Rack|Support|Busbar|Armoire|Manteau|Boîtier|Capteur|Tesla (CT|extension|harnais|kit|sangles|PW3|chariot|Powerwall 2|Gateway 2|Gateway 3 (kit|porte)|Neurio W2 (deux|extensions|séparateur)))/i;
  const nombre = (s) => { const v = parseFloat(String(s).replace(",", ".")); return isFinite(v) ? v : 0; };
  /** Classe chaque ligne du devis par le nom de l'article et en tire le système : quantités = quantités des lignes. */
  function depuisLignes(lignes) {
    const L = (lignes || []).map(l => ({ nom: String(l.nom || "").trim(), q: Number(l.qty) || 0, a: l.article || {} })).filter(l => l.q > 0 && l.nom);
    const equip = L.filter(l => !SERVICE_RE.test(l.nom));
    const de = (re, liste = equip) => liste.filter(l => re.test(l.nom));
    const som = (l) => l.reduce((s, x) => s + x.q, 0);
    const av = [];
    const pwBat = som(de(/^Batterie Tesla Powerwall 3/i)), pwOnd = som(de(/^Onduleur Tesla Powerwall 3/i)), nbPw = Math.max(pwBat, pwOnd);
    const exp = som(de(/^Batterie d'expansion Tesla/i));
    const passerelles = de(/^Passerelle/i); const nbGw = som(passerelles);
    const onds = de(/^Onduleur (?!Tesla)/i); const nbOnd = som(onds);
    const batts = de(/^Batterie (?!Tesla|d'expansion)/i); const nbBatt = som(batts);
    const pans = L.filter(l => l.a.est_panneau || /^Panneau solaire/i.test(l.nom)); const nbPan = som(pans);
    const rsds = de(/^(Arrêt rapide|Optimiseur|Interrupteur MCI|Tesla MCI)/i);
    const bornesEq = de(/^Borne|Wall Connector|^FLO Home|^Wallbox|^EV Duty/i);
    const bornesInst = L.filter(l => /borne/i.test(l.nom) && /^(Installation|Installation et raccordement)/i.test(l.nom));
    const txt = (l) => l.map(x => x.nom).join(" | ");
    const tout = txt(L);
    const marque = nbPw || /Tesla Gateway/i.test(txt(passerelles)) ? "tesla" : /Fox/i.test(txt(onds) + txt(batts) + txt(passerelles)) ? "fox" : /Sigenergy/i.test(txt(onds) + txt(batts) + txt(passerelles)) ? "sigenergy" : /Lux|Volthium/i.test(txt(onds) + txt(batts)) ? "lux" : "tesla";
    const aStock = nbPw > 0 || nbBatt > 0, aPv = nbPan > 0;
    const s = { objectif: "vide", marque, nb: 0, nb_gateways: Math.min(2, nbGw), expansion: exp, secours: "aucun", panneau_critique: 100, onduleur: "auto", nb_onduleurs: marque === "tesla" ? 0 : nbOnd, onduleur_nom: "", onduleur_kw: 0, batterie_nom: "", kwh: 0 };
    s.objectif = aStock && aPv ? "solaire_batterie" : aStock ? "batterie" : aPv ? "solaire" : (bornesEq.length || bornesInst.length) ? "borne" : L.length ? "service" : "vide";
    if (marque === "tesla") s.nb = nbPw;
    else {
      s.nb = nbBatt;
      s.kwh = r1(batts.reduce((t, b) => t + b.q * (Number(b.a.kwh) || nombre((/(\d+(?:[.,]\d+)?)\s*kWh/i.exec(b.nom) || [])[1])), 0));
      const court = (n) => n.replace(/^Batterie\s+/i, "").replace(/\s*\(.*\)\s*$/, "").replace(/,\s*\d+(?:[.,]\d+)?\s*kWh.*$/i, "");
      if (batts[0]) s.batterie_nom = court(batts[0].nom);
      // Plusieurs sortes de batteries (ex. Fox CM4000 maître + CS4000 esclave) : chacune avec sa quantité
      const sortes = new Map(); for (const b of batts) sortes.set(court(b.nom), (sortes.get(court(b.nom)) || 0) + b.q);
      if (sortes.size > 1) s.batteries = [...sortes.entries()].map(([nom, q]) => ({ nom, q }));
    }
    if (onds[0] && marque !== "tesla") {
      const o = onds[0]; s.onduleur_nom = o.nom.replace(/^Onduleur\s+/i, "").replace(/,\s.*$/, "");
      s.onduleur_kw = Number(o.a.kw) || nombre((/(\d+(?:[.,]\d+)?)\s*kW\b/i.exec(o.nom) || [])[1]) || nombre((/(\d+)\s*K\b/.exec(o.nom) || [])[1]);
      const neuf = /9[,.]6\s*kW/i.test(o.nom);
      s.onduleur = /AIO/i.test(o.nom) ? (neuf ? "fox_aio_96" : "fox_aio") : /Fox/i.test(o.nom) ? (neuf ? "fox_h1_96" : "fox_h1") : /Sigenergy/i.test(o.nom) ? "sig_ctrl"
        : /GEN-LB/i.test(o.nom) ? (/16K/i.test(o.nom) ? "lux_gen16" : "lux_gen13") : /SNA/i.test(o.nom) ? (/\b6K/i.test(o.nom) ? "lux_sna6" : "lux_sna12") : /10K/i.test(o.nom) ? "lux_lxp10" : /Lux/i.test(o.nom) ? "lux_lxp" : "auto";
      // Onduleur hors réseau (Lux Power SNA-US) : aucune injection au réseau
      s.hors_reseau = /hors r[ée]seau|\bSNA-/i.test(o.nom);
    }
    // Tesla : secours partiel seulement si le panneau de charges critiques (ou la section de secours) est une ligne du devis ; la
    // main-d'œuvre seule (« Raccordement source de secours, backup partiel ») n'invente pas de panneau : sans panneau ni embase
    // combinée, la Gateway 3 contient les charges critiques (petit kit, secours « base »).
    const panneauCC = L.find(l => /charges critiques|section de secours/i.test(l.nom) && !/^Raccordement/i.test(l.nom));
    if (/maison complète|embase de compteur combinée/i.test(tout)) s.secours = "complet";
    else if (marque === "tesla" ? panneauCC : /charges critiques|backup partiel|section de secours/i.test(tout)) { s.secours = "partiel"; const pc = panneauCC || L.find(l => /charges critiques|section de secours/i.test(l.nom)); s.panneau_critique = pc && /\b60 A\b/.test(pc.nom) ? 60 : 100; }
    else if (nbGw) s.secours = "base";
    const pv = { nb: nbPan, watts: 500, modele: "", rsd: "aucun", nb_rsd: 0 };
    if (pans.length) { const p = pans.slice().sort((u, v) => v.q - u.q)[0]; pv.watts = Number(p.a.watts) || nombre((/(\d{3})\s*W\b/.exec(p.nom) || [])[1]) || 500; pv.modele = p.nom.replace(/^Panneau solaire\s+/i, "").replace(/,\s.*$/, "").replace(/\s*\d{3}\s*W\b.*$/, "").trim();
      // Modèle exact installé (JF, 5 nov. 2026 : ce sont des LR8 500 W) : pris dans la description QuickBooks de l'article
      // (« modèle LR8-54HGBB-500M »), sinon dans le nom ; la marque est gardée devant.
      const code = (/mod[eè]le\s+([A-Z]{2,}[0-9][\w-]+)/i.exec(String((p.a && p.a.description) || "")) || /\b(LR\d-[\w-]+)/i.exec(p.nom) || [])[1];
      if (code) { const marque = (/^(\S+)/.exec(pv.modele) || [])[1] || ""; pv.modele = `${marque && !code.toUpperCase().startsWith(marque.toUpperCase()) ? marque + " " : ""}${code.toUpperCase()}`; } }
    if (rsds.length) {
      const t = txt(rsds); pv.rsd = /ProJoy/i.test(t) ? "projoy" : /MCI/i.test(t) ? "mci" : /Optimiseur/i.test(t) ? "optimiseur" : /Tigo/i.test(t) ? "tigo" : "projoy"; pv.nb_rsd = som(rsds);
      // Détail par sorte quand le devis en mélange (ex. 1 ProJoy + 3 optimiseurs Tigo) : la cote les nomme chacune
      const lib = (n) => /ProJoy/i.test(n) ? "ProJoy RSD" : /MCI/i.test(n) ? "MCI Tesla" : /Optimiseur/i.test(n) ? "Optimiseur Tigo TS4-A-O" : /Tigo/i.test(n) ? "Tigo TS4-A-2F" : "Arrêt rapide";
      const sortes = new Map(); for (const r of rsds) sortes.set(lib(r.nom), (sortes.get(lib(r.nom)) || 0) + r.q);
      if (sortes.size > 1) pv.rsd_detail = [...sortes.entries()].map(([nom, q]) => ({ nom, q }));
    }
    const bornes = [];
    for (const b of bornesEq) for (let i = 0; i < b.q && bornes.length < 3; i++) {
      const amp = /(?<![\d,.])(\d{2})\s?A\b/.exec(b.nom) || /(?<![\d,.])(\d{2})\s?A\b/.exec(String((b.a && b.a.description) || "")); const kw = nombre((/(\d+(?:[.,]\d+)?)\s*kW\b/i.exec(b.nom) || [])[1]);
      const v2x = /EVDC|V2X|bidirectionnel/i.test(b.nom);
      let modele = b.nom.replace(/^Borne( de recharge)?\s*/i, "").replace(/\s*\(.*\)\s*$/, "").replace(/\s+bidirectionnelle$/i, "").trim();
      if (/^(VE|VÉ)?$/i.test(modele)) modele = "Borne VÉ niveau 2"; if (v2x) modele = `${modele.replace(/\s*\(V2X\)$/, "")} (V2X)`;
      bornes.push({ modele: modele.slice(0, 34), amperes: amp ? Number(amp[1]) : kw && !v2x ? Math.round(kw * 1000 / 240) : 48, ...(kw ? { kw } : {}), ...(v2x ? { v2x: true } : {}) });
    }
    if (!bornes.length && bornesInst.length) { const nb = Math.max(...bornesInst.map(b => b.q)); for (let i = 0; i < Math.min(3, nb); i++) bornes.push({ modele: "Borne VÉ (fournie par le client)", amperes: 48 }); }
    const extras = [];
    const ajoute = (cle, re, liste = equip) => { for (const l of de(re, liste)) extras.push({ cle, nom: l.nom, qty: l.q, amperes: Number((/(\d{2,3})\s*A\b/.exec(l.nom) || [])[1]) || 0 }); };
    // (aucun sectionneur CC entre les batteries et l'onduleur sur le schéma ; la composante reste dans la palette pour un ajout manuel)
    ajoute("sect_ext", /^Sectionneur extérieur/i); ajoute("sect_ac", /^Sectionneur AC/i);
    ajoute("panneau_sec", /^(Panneau secondaire|Sous-panneau)/i);
    ajoute("generatrice", /^(Génératrice|Installation génératrice)|génératrice fixe avec transfert/i, L); ajoute("ats", /^Commutateur de transfert automatique/i);
    ajoute("inlet", /génératrice portative|^Interrupteur de transfert manuel/i, L);
    ajoute("dongle", /^(Module (Fox|Sigenergy)|Dongle)/i); ajoute("compteur_distant", /^(Compteur distant|Tesla Remote Meter|Tesla Neurio W2 Meter)/i);
    // Volthium : barre omnibus (nœud du circuit CC) et enceinte des batteries (armoire, rack ou support, nommés dans la légende de la pile)
    ajoute("busbar", /^Busbar/i, L); ajoute("enceinte", /^(Armoire extérieure|Rack au sol|Support mural) Volthium/i, L);
    // Embase de compteur combinée (secours maison complète) : compteur et disjoncteur principal dans la même embase
    const service = /embase de compteur combinée/i.test(tout) ? { embase: "meter_main" } : {};
    if (aPv && !nbPw && !nbOnd) av.push("Panneaux solaires sans onduleur dans la soumission : ajoute l'onduleur depuis la palette");
    if (nbBatt && !nbOnd && marque !== "tesla") av.push("Batteries sans onduleur dans la soumission : ajoute l'onduleur depuis la palette");
    if (nbPw && !nbGw) av.push("Powerwall 3 sans passerelle dans la soumission : ajoute la Tesla Gateway 3 depuis la palette");
    return { systeme: s, pv, bornes, extras, service, avertissements: av, lignes: L.length };
  }
  function depuisSoumission(state) {
    const m = DEFAUT(); const c = state.client || {};
    Object.assign(m.client, { nom: c.name || "", adresse1: c.address_full ? c.address_full.split(",")[0] : [c.address_civic, c.address_street].filter(Boolean).join(" "), adresse2: [c.address_city, c.address_postal].filter(Boolean).join("  "), telephone: c.phone || "", courriel: c.email || "" });
    m.hq.tarif = c.hq_tariff || "D"; m.hq.titulaire = c.name || "";
    if (c.hq_numero_client) m.hq.numero_client = c.hq_numero_client; if (c.hq_numero_contrat) m.hq.numero_contrat = c.hq_numero_contrat; if (c.hq_numero_compteur) m.hq.numero_compteur = c.hq_numero_compteur;
    m.meta.dossier = state.number || state.numero || (c.name ? `${c.name.split(" ").slice(-1)[0]}-${new Date().getFullYear()}`.toUpperCase() : "");
    if (c.service_amperes) m.service.calibre = Number(c.service_amperes) || 200;
    const d = depuisLignes(lignesDuDevis(state));
    Object.assign(m.systeme, d.systeme); Object.assign(m.pv, d.pv); Object.assign(m.service, d.service || {}); m.bornes = d.bornes; m.extras = d.extras;
    m.source = { lignes: d.lignes, avertissements: d.avertissements };
    const sv = state.schema_unifilaire;
    if (sv && sv.retouches) { m.retouches = normaliserRetouches(sv.retouches); Object.assign(m.hq, sv.hq || {}); Object.assign(m.service, sv.service || {}); m.meta.version = sv.meta && sv.meta.version ? suivante(sv.meta.version) : "v1"; }
    if (sv && sv.options) Object.assign(m.options, sv.options);
    if (sv && sv.meta && sv.meta.fichier) m.meta.fichier = sv.meta.fichier;
    return m;
  }
  const suivante = (v) => { const n = parseInt(String(v).replace(/\D/g, ""), 10); return `v${isFinite(n) ? n + 1 : 2}`; };
  function depuisFiche(prefill) {
    const m = DEFAUT(); const c = prefill || {};
    Object.assign(m.client, { nom: c.name || "", adresse1: c.address_full ? c.address_full.split(",")[0] : (c.address_street || ""), adresse2: [c.address_city, c.address_postal].filter(Boolean).join("  "), telephone: c.phone || "", courriel: c.email || "" });
    m.hq.titulaire = c.name || ""; m.meta.dossier = c.name ? `${c.name.split(" ").slice(-1)[0]}-${new Date().getFullYear()}`.toUpperCase() : "";
    return m;
  }
  /** Ancien préréglage du Raycom Schema Builder ({ fields, components, labels }) → modèle. Meilleur effort. */
  function depuisPreset(j) {
    const m = DEFAUT(); const f = (j && j.fields) || {}; const comps = (j && j.components) || []; const labels = (j && j.labels) || {};
    Object.assign(m.client, { nom: f.i_client_nom || "", adresse1: f.i_client_adresse1 || "", adresse2: f.i_client_adresse2 || "", telephone: f.i_client_tel || "", courriel: f.i_client_courriel || "" });
    Object.assign(m.hq, { numero_client: f.i_hq_client || "", numero_contrat: f.i_hq_contrat || "", numero_compteur: f.i_hq_compteur || "", dossier: (f.i_hq_dossier || "").split("·")[0].trim(), titulaire: f.i_client_nom || "" });
    m.meta.date = f.i_date || m.meta.date; m.meta.version = (f.i_version || "v1").split(" ")[0]; m.meta.dossier = m.hq.dossier;
    const svc = /(\d{3})\s*A/.exec(f.i_sys_service || ""); if (svc) m.service.calibre = Number(svc[1]); if (/embase.*disj|meter.?main/i.test((f.i_sys_service || "") + (labels.comp_2 || ""))) m.service.embase = "meter_main";
    const types = comps.map(c => String(c.type || "")); const nbType = (re) => types.filter(t => re.test(t)).length;
    const pw = nbType(/powerwall/i), gw = nbType(/gateway/i), exp = nbType(/expansion/i), pcc = nbType(/charges_critiques|backup|critique/i), fox = nbType(/fox|aio|h1/i), sig = nbType(/sig/i), lux = nbType(/lux|volthium/i), ond = nbType(/onduleur|inverter|h1/i), borne = nbType(/borne|wall_connector|ev/i);
    m.systeme.marque = pw ? "tesla" : fox ? "fox" : sig ? "sigenergy" : lux ? "lux" : "tesla";
    m.systeme.nb = Math.max(1, pw || nbType(/batterie|module_batt|eq4000|sigenstor/i) || 1); m.systeme.nb_gateways = Math.max(1, gw); m.systeme.expansion = exp ? 1 : 0; if (m.systeme.marque !== "tesla") { m.systeme.nb_onduleurs = Math.max(1, ond); m.systeme.nb_gateways = gw || (fox || sig ? 1 : 0); }
    const pvLabel = Object.values(labels).concat([f.i_sys_cc || ""]).find(t => /(\d+)\s*[×x]\s*.*?(\d{3})\s*W/i.test(t)) || "";
    const pvM = /(\d+)\s*[×x]\s*(.*?)\s*(\d{3})\s*W/i.exec(pvLabel);
    if (pvM) { m.pv.nb = Number(pvM[1]); m.pv.watts = Number(pvM[3]); m.pv.modele = pvM[2].replace(/[^\w\s-]/g, "").trim().slice(0, 24) || "panneau"; } else { const kw = /([\d.,]+)\s*kW/.exec(f.i_sys_cc || ""); m.pv.nb = kw ? Math.round(parseFloat(kw[1].replace(",", ".")) * 2) : 0; }
    const sansStock = /aucun|mesurage net/i.test(f.i_sys_stockage || "") && !pw && !m.systeme.nb;
    m.systeme.objectif = borne && !pw && !ond && !m.pv.nb ? "borne" : (sansStock || (!pw && !fox && !sig && !lux && ond)) ? "solaire" : m.pv.nb ? "solaire_batterie" : "batterie";
    if (m.systeme.objectif === "solaire") { m.systeme.nb_onduleurs = Math.max(1, Math.min(3, ond)); m.systeme.onduleur = "fox_h1"; m.pv.rsd = "projoy"; }
    m.systeme.secours = m.systeme.objectif === "solaire" ? "aucun" : pcc ? "partiel" : /complet|whole/i.test((f.i_topologie || "") + (f.i_sys_type || "")) ? "complet" : "base";
    m.pv.rsd = (MARQUES[m.systeme.marque] || MARQUES.tesla).rsd; if (m.systeme.objectif === "solaire") m.pv.rsd = "projoy";
    m.options.epo = nbType(/epo/i) > 0; m.options.routeur = nbType(/routeur|wifi/i) > 0; m.options.malt = nbType(/malt/i) > 0;
    m.source = { lignes: comps.length, avertissements: [] }; m.version = 3;
    if (borne) m.bornes = Array.from({ length: borne }, () => ({ modele: "Borne VÉ", amperes: 48 }));
    return m;
  }

  // ───────────────────────── Modèles intégrés (non supprimables) ─────────────────────────
  // Configurations les plus soumises et vendues de mai à novembre 2026 (devis et factures QuickBooks, lignes d'articles seulement ;
  // « ventes » = clients facturés, une vente par client). Chaque modèle est une liste de lignes du catalogue RE : le schéma, le câblage
  // et la cartouche en sont tirés par depuisLignes, exactement comme pour une soumission.
  const LONGI_500 = ["509", "Panneau solaire LONGi Hi-MO 7, 500 W", "modèle LR8-54HGBB-500M"];
  const PW3 = [["478", "Batterie Tesla Powerwall 3, 13,5 kWh"], ["570", "Onduleur Tesla Powerwall 3, 11,5 kW"]];
  const GW3 = ["480", "Passerelle Tesla Gateway 3, 200 A"], PCC100 = ["553", "Backup partiel, panneau de charges critiques 100 A installé"], MCI = ["481", "Interrupteur MCI Tesla, par chaîne solaire"];
  const ligne = (q, [id, nom, description]) => ({ qbo_id: id, qty: q, nom, article: description ? { description } : {} });
  const MODELES_INTEGRES = [
    // Le plus petit kit (JF, 5 nov. 2026) : la Gateway 3 contient les charges critiques et sert de panneau de secours. Fréquence :
    // devis et factures Tesla de mai à novembre 2026 SANS panneau de charges critiques (553, 586, 555) ni embase combinée ou maison complète.
    { id: "tesla_pw3_gateway", nom: "Tesla · 1 Powerwall 3 + Gateway 3, charges critiques dans la passerelle", devis: 34, ventes: 19, factures: 22, description: "1 Powerwall 3 (11,5 kW, 13,5 kWh) et Gateway 3 qui contient les charges critiques et sert de panneau de secours, sans panneau de charges critiques",
      lignes: [...PW3.map(a => ligne(1, a)), ligne(1, GW3)] },
    { id: "tesla_1pw_partiel", nom: "Tesla · 1 Powerwall 3, secours partiel", devis: 20, ventes: 9, factures: 10, description: "1 Powerwall 3 (11,5 kW, 13,5 kWh), Gateway 3, panneau de charges critiques 100 A",
      lignes: [...PW3.map(a => ligne(1, a)), ligne(1, GW3), ligne(1, PCC100)] },
    { id: "tesla_2pw_complet", nom: "Tesla · 2 Powerwall 3, maison complète", devis: 5, ventes: 3, factures: 3, description: "2 Powerwall 3 (23 kW, 27 kWh), Gateway 3 en amont du panneau, embase de compteur combinée 200 A",
      lignes: [...PW3.map(a => ligne(2, a)), ligne(1, GW3), ligne(1, ["560", "Backup maison complète, embase de compteur combinée 200 A installée"])] },
    { id: "tesla_1pw_solaire", nom: "Tesla · 1 Powerwall 3 + solaire 9 kW", devis: 15, ventes: 6, factures: 8, description: "1 Powerwall 3, Gateway 3, charges critiques 100 A, 18 panneaux LONGi 500 W, 6 MCI",
      lignes: [...PW3.map(a => ligne(1, a)), ligne(1, GW3), ligne(1, PCC100), ligne(18, LONGI_500), ligne(6, MCI)] },
    { id: "tesla_2pw_solaire", nom: "Tesla · 2 Powerwall 3 + solaire 12 kW", devis: 4, ventes: 3, factures: 3, description: "2 Powerwall 3, Gateway 3, charges critiques 100 A, 24 panneaux LONGi 500 W, 8 MCI",
      lignes: [...PW3.map(a => ligne(2, a)), ligne(1, GW3), ligne(1, PCC100), ligne(24, LONGI_500), ligne(8, MCI)] },
    { id: "fox_aio_solaire", nom: "Fox ESS · AIO 11,4 kW + 3 EQ4000 + solaire", devis: 4, ventes: 3, factures: 12, description: "Fox ESS AIO 11,4 kW sur 3 EQ4000 (11,9 kWh), Hub G2, 12 panneaux LONGi 500 W, ProJoy, module WiLAN",
      lignes: [ligne(1, ["525", "Onduleur Fox ESS AIO 11,4 kW, sur pile EQ4000"]), ligne(3, ["492", "Batterie Fox ESS EQ4000, 3,97 kWh (pile AIO)"]), ligne(1, ["493", "Passerelle Fox ESS Hub G2, 200 A"]), ligne(12, LONGI_500), ligne(1, ["494", "Arrêt rapide ProJoy RSD, par unité"]), ligne(1, ["530", "Module Fox ESS Smart WiLAN (Wi-Fi ou LAN)"])] },
    { id: "lux_volthium", nom: "Lux Power GEN 13K + Volthium 16,1 kWh", devis: 4, ventes: 0, factures: 0, description: "Lux Power GEN-LB-US 13K, Volthium 314 Ah (16,1 kWh) couplée en CC à l'onduleur, charges critiques 100 A, dongle Ethernet",
      lignes: [ligne(1, ["587", "Onduleur Lux Power GEN-LB-US 13K, raccordé au réseau"]), ligne(1, ["506", "Batterie Volthium 314 Ah, 16,1 kWh, armoire au sol"]), ligne(1, PCC100), ligne(1, ["549", "Dongle Lux Power Ethernet"])] },
    { id: "sigenergy_solaire", nom: "Sigenergy · 11,5 kW + 2 BAT 9 + solaire", devis: 1, ventes: 0, factures: 0, description: "Sigenergy Energy Controller 11,5 kW, 2 × BAT 9.0 (18,1 kWh), LoadHub, 15 panneaux LONGi 500 W, Tigo TS4-A-2F",
      lignes: [ligne(1, ["495", "Onduleur Sigenergy Energy Controller 11,5 kW"]), ligne(2, ["496", "Batterie Sigenergy BAT 9.0, 9,04 kWh"]), ligne(1, ["498", "Passerelle Sigenergy LoadHub 200 A"]), ligne(15, LONGI_500), ligne(8, ["550", "Arrêt rapide Tigo TS4-A-2F, 1 par 2 panneaux"])] },
    { id: "borne_seule", nom: "Borne de recharge seule (48 A)", devis: 56, ventes: 32, factures: 33, description: "Borne VÉ niveau 2, 48 A, circuit dédié 2P 60 A au panneau principal",
      lignes: [ligne(1, ["360", "Borne de Recharge VE"])] },
  ].map(md => ({ ...md, integre: true, frequence: `${md.devis} devis et ${md.ventes} ventes de mai à novembre 2026` }));
  /** Schéma complet d'un modèle intégré (sans client) : système, service et options tirés de ses lignes. */
  function depuisModeleIntegre(id) {
    const md = MODELES_INTEGRES.find(x => x.id === id); if (!md) return null;
    const m = DEFAUT(); const d = depuisLignes(md.lignes);
    Object.assign(m.systeme, d.systeme); Object.assign(m.pv, d.pv); Object.assign(m.service, d.service || {}); m.bornes = d.bornes; m.extras = d.extras;
    m.source = { lignes: d.lignes, avertissements: d.avertissements, modele: md.id };
    return m;
  }

  // ───────────────────────── Export ─────────────────────────
  async function rendu(svgEl, echelle) {
    // Copie propre : les éléments d'édition (sélection, ports, poignées, zones de saisie) ne sortent jamais dans l'export
    const clone = svgEl.cloneNode(true); clone.querySelectorAll(".rc-sch-ui").forEach(e => e.remove()); clone.removeAttribute("class");
    const xml = new XMLSerializer().serializeToString(clone);
    const url = URL.createObjectURL(new Blob([xml], { type: "image/svg+xml;charset=utf-8" }));
    try {
      const img = await new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = () => rej(new Error("rendu SVG impossible")); i.src = url; });
      const cv = document.createElement("canvas"); cv.width = Math.round(PAGE.w * echelle); cv.height = Math.round(PAGE.h * echelle);
      const ctx = cv.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, cv.width, cv.height); ctx.drawImage(img, 0, 0, cv.width, cv.height);
      return cv;
    } finally { URL.revokeObjectURL(url); }
  }
  async function exporterPNG(svgEl, echelle = 2) { const cv = await rendu(svgEl, echelle); return new Promise(res => cv.toBlob(res, "image/png")); }
  /** PDF paysage 11 × 17 (tabloïd) ou lettre : la page entière est posée en image, lisible en noir et blanc. */
  async function exporterPDF(svgEl, format = "tabloid") {
    if (!window.jspdf || !window.jspdf.jsPDF) throw new Error("jsPDF non chargé");
    const cv = await rendu(svgEl, 2.2);
    const dims = format === "letter" ? [279.4, 215.9] : [431.8, 279.4];
    const pdf = new window.jspdf.jsPDF({ orientation: "landscape", unit: "mm", format: dims });
    try { pdf.setProperties({ title: "Schéma unifilaire", author: ENTREPRISE.nom, creator: ENTREPRISE.nom, subject: "Schéma unifilaire · norme E.12-07 d'Hydro-Québec" }); } catch (e) { /* propriétés facultatives */ }
    const w = dims[0], h = w * PAGE.h / PAGE.w; const y = Math.max(0, (dims[1] - h) / 2);
    pdf.addImage(cv.toDataURL("image/jpeg", 0.92), "JPEG", 0, y, w, h);
    return pdf.output("blob");
  }
  const nomFichierBase = (m, ext) => `Schema_unifilaire_${(m.client.nom || "client").normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^\w]+/g, "_").replace(/^_|_$/g, "")}_${m.meta.date}.${ext}`;
  // Le nom du fichier est fixé au premier enregistrement (meta.fichier) et ne change plus : une mise à jour remplace le même PDF
  // dans le dossier du client (JF, 5 nov. 2026).
  const nomFichier = (m, ext) => (m.meta && m.meta.fichier ? m.meta.fichier.replace(/\.pdf$/i, "." + ext) : nomFichierBase(m, ext));
  /** Schémas déjà enregistrés pour ce client (table schemas_unifilaires), du plus récent au plus ancien. */
  async function schemasDuClient(cle) {
    if (!cle || !window.RAYCAST_SUPABASE) return [];
    try { const { data } = await window.RAYCAST_SUPABASE.from("schemas_unifilaires").select("id,fichier,version,updated_at,modele").eq("client_key", cle).order("updated_at", { ascending: false }).limit(20); return data || []; } catch (e) { return []; }
  }
  const telecharger = (blob, nom) => { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = nom; document.body.appendChild(a); a.click(); setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1500); };
  async function jwt() { try { const { data } = await window.RAYCAST_SUPABASE.auth.getSession(); return data && data.session ? data.session.access_token : null; } catch (e) { return null; } }
  async function workerPost(path, fd) {
    const t = await jwt(); if (!t) throw new Error("Session expirée, reconnecte-toi");
    const r = await fetch(`${window.CatalogueRE.WORKER_URL}${path}`, { method: "POST", headers: { Authorization: `Bearer ${t}` }, body: fd });
    const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); return j;
  }
  const cleClient = (m) => { const d = String(m.client.telephone || "").replace(/\D/g, ""); const t = d.length === 11 && d[0] === "1" ? d.slice(1) : d; return t.length === 10 ? t : String(m.client.courriel || "").trim().toLowerCase() || null; };

  // ───────────────────────── Studio (plein écran) ─────────────────────────
  const Champ = ({ label, children, faible }) => <label className={"rc-sch-champ" + (faible ? " faible" : "")}><span>{label}</span>{children}</label>;
  function Studio({ initial, onFermer, onEnregistrer, titreContexte, regenererDepuis }) {
    const [m, setM] = useState(() => { const x = JSON.parse(JSON.stringify(initial || DEFAUT())); x.retouches = normaliserRetouches(x.retouches); return x; });
    const [bloc, setBloc] = useState("client");
    const [sel, setSel] = useState([]);                                // sélection multiple (Maj + clic)
    const selection = sel.length ? sel[sel.length - 1] : null;
    const setSelection = (id) => setSel(id ? [id] : []);
    const [glisse, setGlisse] = useState(false);
    const [selectionFil, setSelectionFil] = useState(null);
    const [toast, setToast] = useState(null);
    const [confiance, setConfiance] = useState({});
    const [occupe, setOccupe] = useState(null);
    const [deposer, setDeposer] = useState(true);
    const [outil, setOutil] = useState("selection");                 // selection | cable
    const [genreCable, setGenreCable] = useState("principal");
    const [calibreCable, setCalibreCable] = useState("");
    const [portEnAttente, setPortEnAttente] = useState(null);         // { id, cote }
    const [logoData, setLogoData] = useState(null);
    const [modeles, setModeles] = useState([]);
    const [nomModele, setNomModele] = useState("");
    const [modeleChoisi, setModeleChoisi] = useState("");
    const [recherche, setRecherche] = useState("");
    const [fantome, setFantome] = useState(null);                       // composante de la palette en cours de glisser-déposer
    const palDrag = useRef(null);
    const [texteAnnotation, setTexteAnnotation] = useState("");
    const [deplie, setDeplie] = useState({});
    const [panneauDroit, setPanneauDroit] = useState("composantes"); // composantes | cables | annotations
    const svgRef = useRef(null); const drag = useRef(null); const factureRef = useRef(null); const presetRef = useRef(null);
    const mRef = useRef(m); mRef.current = m;
    const hist = useRef({ past: [], future: [] });
    const construit = useMemo(() => { try { return construire(m); } catch (e) { console.error(e); return { noeuds: [], fils: [], top: topologie(m), annotations: [], vide: false, avertissements: ["Erreur de construction : " + e.message] }; } }, [m]);
    // Historique : chaque modification passe par commettre() (annuler et rétablir, Ctrl+Z et Ctrl+Y)
    const commettre = () => { const h = hist.current; h.past.push(JSON.stringify(mRef.current)); if (h.past.length > 80) h.past.shift(); h.future = []; };
    const annuler = () => { const h = hist.current; if (!h.past.length) return; h.future.push(JSON.stringify(mRef.current)); setM(JSON.parse(h.past.pop())); };
    const retablir = () => { const h = hist.current; if (!h.future.length) return; h.past.push(JSON.stringify(mRef.current)); setM(JSON.parse(h.future.pop())); };
    const up = (chemin, val) => { commettre(); setM(prev => { const n = JSON.parse(JSON.stringify(prev)); const parts = chemin.split("."); let o = n; for (let i = 0; i < parts.length - 1; i++) o = o[parts[i]]; o[parts[parts.length - 1]] = val; return n; }); };
    const upR = (fn, sansHistorique) => { if (!sansHistorique) commettre(); setM(prev => { const n = JSON.parse(JSON.stringify(prev)); n.retouches = normaliserRetouches(n.retouches); fn(n.retouches, n); return n; }); };
    useEffect(() => { if (!toast) return; const t = setTimeout(() => setToast(null), 3500); return () => clearTimeout(t); }, [toast]);
    // Logo officiel Raycom (version recadrée de raycom-logo-official.png) en data URI : présent dans l'aperçu, le PDF et le PNG
    useEffect(() => { let vivant = true; (async () => { try { let r = await fetch("raycom-assets/raycom-logo-cropped.png"); if (!r.ok) r = await fetch("raycom-assets/raycom-logo-official.png"); if (!r.ok) return; const b = await r.blob(); const fr = new FileReader(); fr.onload = () => { if (vivant) setLogoData(String(fr.result)); }; fr.readAsDataURL(new Blob([b], { type: "image/png" })); } catch (e) { /* logo vectoriel de repli */ } })(); return () => { vivant = false; }; }, []);
    // Modèles de schémas (app_settings.schema_modeles)
    useEffect(() => { (async () => { try { const v = window.RaycastDB && window.RaycastDB.getAppSetting ? await window.RaycastDB.getAppSetting("schema_modeles") : null; if (v && Array.isArray(v.modeles)) setModeles(v.modeles); } catch (e) { /* pas de modèles */ } })(); }, []);
    const dansChamp = (e) => { const t = e.target; return t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable); };
    useEffect(() => {
      const k = (e) => {
        if (e.key === "Escape") { if (palDrag.current) { palDrag.current = null; setFantome(null); return; } if (portEnAttente) { setPortEnAttente(null); return; } if (sel.length || selectionFil) { setSel([]); setSelectionFil(null); return; } onFermer && onFermer(); return; }
        if (dansChamp(e)) return;
        if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") { e.preventDefault(); e.shiftKey ? retablir() : annuler(); return; }
        if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") { e.preventDefault(); retablir(); return; }
        if (e.key === "Delete" || e.key === "Backspace") { if (selectionFil) { e.preventDefault(); retirerCable(selectionFil); } else if (sel.length) { e.preventDefault(); const ids = sel.slice(); ids.forEach(id => retirerComposante(id)); setSel([]); } return; }
        // Flèches : déplace la sélection de 1 px (Maj : 10 px)
        const fl = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
        if (fl && sel.length) { e.preventDefault(); const k = e.shiftKey ? 10 : 1; deplacerSelection(fl[0] * k, fl[1] * k); }
      };
      window.addEventListener("keydown", k); return () => window.removeEventListener("keydown", k);
    }); // eslint-disable-line

    // ── Glisser (appareil, annotation, coude) et redimensionner : un seul écouteur souris ──
    const svgPoint = (ev) => { const svg = svgRef.current; const pt = svg.createSVGPoint(); pt.x = ev.clientX; pt.y = ev.clientY; return pt.matrixTransform(svg.getScreenCTM().inverse()); };
    // Glisser : la sélection entière suit la souris ; mise à jour par requestAnimationFrame, aimantation à la grille de 10 px
    const G10 = (v) => Math.round(v / 10) * 10;
    const noeudDe = (id) => construit.noeuds.find(x => x.id === id);
    const onDrag = (ev, id) => {
      if (ev.button !== undefined && ev.button !== 0) return;
      ev.preventDefault(); ev.stopPropagation();
      if (ev.shiftKey) { setSel(s0 => s0.includes(id) ? s0.filter(x => x !== id) : s0.concat(id)); setSelectionFil(null); drag.current = { genre: "aucun" }; return; }
      const ids = sel.includes(id) ? sel.slice() : [id]; if (!sel.includes(id)) setSel([id]); setSelectionFil(null);
      const p = svgPoint(ev); const depart = {};
      for (const k of ids) { const n = noeudDe(k); if (n) depart[k] = { x: n.x, y: n.y, x0: n.x0 != null ? n.x0 : n.x, y0: n.y0 != null ? n.y0 : n.y }; const a = (mRef.current.retouches.annotations || []).find(x => x.id === k); if (a) depart[k] = { annotation: true, x: a.x, y: a.y }; }
      drag.current = { genre: "noeud", ids, saisi: id, x0: p.x, y0: p.y, depart, commis: false };
    };
    const deplacerSelection = (dx, dy) => {
      const ids = sel.slice(); if (!ids.length) return;
      upR(r => { for (const k of ids) { const a = r.annotations.find(x => x.id === k); if (a) { a.x += dx; a.y += dy; continue; } const p = r.positions[k] || { dx: 0, dy: 0 }; r.positions[k] = { dx: (p.dx || 0) + dx, dy: (p.dy || 0) + dy }; } });
    };
    const onResize = (ev, id) => { const p = svgPoint(ev); const n = construit.noeuds.find(x => x.id === id); if (!n) return; commettre(); drag.current = { genre: "taille", id, x0: p.x, y0: p.y, w0: n.w, h0: n.h }; };
    const onCoudeDrag = (ev, cle, k) => { ev.preventDefault(); commettre(); drag.current = { genre: "coude", cle, k }; };
    const onAnnotationDrag = (ev, id) => { ev.preventDefault(); ev.stopPropagation(); const p = svgPoint(ev); const a = (mRef.current.retouches.annotations || []).find(x => x.id === id); if (!a) return; drag.current = { genre: "annotation", id, x0: p.x, y0: p.y, ax: a.x, ay: a.y, commis: false }; setSelection(id); setSelectionFil(null); };
    useEffect(() => {
      let raf = 0, dernier = null;
      const appliquer = () => {
        raf = 0; const d = drag.current; if (!d || !dernier || !svgRef.current) return; const p = svgPoint(dernier);
        const bouge = Math.abs(p.x - (d.x0 || 0)) > 1 || Math.abs(p.y - (d.y0 || 0)) > 1;
        if ((d.genre === "noeud" || d.genre === "annotation") && !d.commis) { if (!bouge) return; commettre(); d.commis = true; setGlisse(true); }
        if (d.genre === "noeud") {
          // l'appareil saisi s'aimante à la grille ; les autres gardent leur écart avec lui (même déplacement)
          const o0 = d.depart[d.saisi] || Object.values(d.depart)[0]; if (!o0) return;
          const ddx = G10(o0.x + p.x - d.x0) - o0.x, ddy = G10(o0.y + p.y - d.y0) - o0.y;
          upR(r => { for (const k of d.ids) { const o = d.depart[k]; if (!o) continue; if (o.annotation) { const a = r.annotations.find(x => x.id === k); if (a) { a.x = o.x + ddx; a.y = o.y + ddy; } continue; } r.positions[k] = { dx: o.x + ddx - o.x0, dy: o.y + ddy - o.y0 }; } }, true);
        }
        else if (d.genre === "taille") { const w = Math.max(24, Math.round((d.w0 + p.x - d.x0) / 2) * 2), h = Math.max(20, Math.round((d.h0 + p.y - d.y0) / 2) * 2); upR(r => { r.tailles[d.id] = { w, h }; }, true); }
        else if (d.genre === "coude") { upR(r => { const c = r.cables.find(x => x.id === d.cle); if (c && c.coudes[d.k]) c.coudes[d.k] = { x: G10(p.x), y: G10(p.y) }; }, true); }
        else if (d.genre === "annotation") { upR(r => { const a = r.annotations.find(x => x.id === d.id); if (a) { a.x = G10(d.ax + p.x - d.x0); a.y = G10(d.ay + p.y - d.y0); } }, true); }
      };
      const move = (ev) => { if (palDrag.current) { const pd = palDrag.current; if (!pd.actif && Math.hypot(ev.clientX - pd.cx, ev.clientY - pd.cy) > 4) pd.actif = true; if (pd.actif) setFantome({ cle: pd.cle, x: ev.clientX, y: ev.clientY }); return; } if (!drag.current) return; dernier = { clientX: ev.clientX, clientY: ev.clientY }; if (!raf) raf = requestAnimationFrame(appliquer); };
      const fin = (ev) => {
        if (palDrag.current) {
          const pd = palDrag.current; palDrag.current = null; setFantome(null);
          if (!pd.actif) { ajouterComposante(pd.cle); return; }
          const svg = svgRef.current; if (!svg) return; const b = svg.getBoundingClientRect();
          if (ev.clientX >= b.left && ev.clientX <= b.right && ev.clientY >= b.top && ev.clientY <= b.bottom) ajouterComposante(pd.cle, svgPoint(ev));
          return;
        }
        if (raf) { cancelAnimationFrame(raf); raf = 0; appliquer(); }
        drag.current = null; dernier = null; setGlisse(false);
      };
      window.addEventListener("mousemove", move); window.addEventListener("mouseup", fin); return () => { if (raf) cancelAnimationFrame(raf); window.removeEventListener("mousemove", move); window.removeEventListener("mouseup", fin); };
    }, []); // eslint-disable-line
    const debutPalette = (ev, cle) => { if (ev.button !== 0) return; ev.preventDefault(); palDrag.current = { cle, cx: ev.clientX, cy: ev.clientY, actif: false }; };

    // ── Composantes ──
    const tous = useMemo(() => { try { const sans = { ...m, retouches: { ...normaliserRetouches(m.retouches), masques: [] } }; return construire(sans).noeuds; } catch (e) { return []; } }, [m]);
    const masques = new Set(m.retouches.masques || []);
    const masquer = (id) => upR(r => { const set = new Set(r.masques); set.has(id) ? set.delete(id) : set.add(id); r.masques = [...set]; });
    const renommer = (id, nom) => upR(r => { r.noms[id] = nom; });
    const coter = (id, cote) => upR(r => { r.cotes[id] = cote; });
    const legender = (id, k, texte) => upR(r => { const n = tous.find(x => x.id === id); const base = r.legendes[id] || (n && n.leg) || [n ? n.nom : "", "", ""]; const l = [base[0] || "", base[1] || "", base[2] || ""]; l[k] = texte; r.legendes[id] = l; });
    const retirerComposante = (id) => { if (String(id).startsWith("aj_")) upR(r => { r.ajouts = r.ajouts.filter(a => a.id !== id); r.cables = r.cables.filter(c => c.de !== id && c.a !== id); }); else if (String(id).startsWith("an_")) upR(r => { r.annotations = r.annotations.filter(a => a.id !== id); }); else masquer(id); setSelection(null); };
    const ordreCourant = () => construit.noeuds.filter(x => x.num).sort((a, b) => a.num - b.num).map(x => x.id);
    const deplacerOrdre = (id, sens) => { const o = ordreCourant(); const i = o.indexOf(id); const j = i + sens; if (i < 0 || j < 0 || j >= o.length) return; o.splice(i, 1); o.splice(j, 0, id); upR(r => { r.ordre = o; }); };
    const ajouterComposante = (cle, pos) => {
      const d = PALETTE.find(x => x.cle === cle); if (!d) return;
      if (d.type === "texte") { setPanneauDroit("annotations"); return; }
      const k = (mRef.current.retouches.ajouts || []).length;
      const id = `aj_${Date.now().toString(36)}_${k}`;
      const x = pos ? Math.round((pos.x - d.w / 2) / 10) * 10 : ZONE.x + 60 + (k % 7) * 150, y = pos ? Math.round((pos.y - d.h / 2) / 10) * 10 : ZONE.y + ZONE.h - 150;
      upR(r => { r.ajouts.push({ id, cle: d.cle, type: d.type, x, y, w: d.w, h: d.h, nom: d.nom, cote: "", leg: d.leg || [d.nom, "", ""] }); });
      setSelection(id); setToast({ ok: pos ? `${d.nom} déposé : relie-le avec l'outil Câble` : `${d.nom} ajouté : glisse-le à sa place, puis relie-le avec l'outil Câble` });
    };
    const ajouterAnnotation = () => { const t = texteAnnotation.trim(); if (!t) return; const id = `an_${Date.now().toString(36)}`; upR(r => { r.annotations.push({ id, x: ZONE.x + 60, y: ZONE.y + 40, texte: t, taille: 11 }); }); setTexteAnnotation(""); setSelection(id); };
    const majAnnotation = (id, champ, val) => upR(r => { const a = r.annotations.find(x => x.id === id); if (a) a[champ] = val; });

    // ── Câbles ──
    const onPort = (id, cote) => {
      if (!portEnAttente) { setPortEnAttente({ id, cote }); return; }
      if (portEnAttente.id === id && portEnAttente.cote === cote) { setPortEnAttente(null); return; }
      const cid = `cab_${Date.now().toString(36)}`;
      const de = portEnAttente; setPortEnAttente(null);
      upR(r => { r.cables.push({ id: cid, de: de.id, deCote: de.cote, a: id, aCote: cote, genre: genreCable, calibre: calibreCable.trim(), coudes: [] }); });
      setSelectionFil(cid); setPanneauDroit("cables"); setToast({ ok: "Câble ajouté : double-clic dessus pour un coude, Suppr pour le retirer" });
    };
    const retirerCable = (cle) => { if (!cle) return; upR(r => { if (r.cables.some(c => c.id === cle)) r.cables = r.cables.filter(c => c.id !== cle); else if (!r.cables_retires.includes(cle)) r.cables_retires.push(cle); }); setSelectionFil(null); };
    const restaurerCable = (cle) => upR(r => { r.cables_retires = r.cables_retires.filter(x => x !== cle); });
    const onAjouterCoude = (ev, cle) => { const p = svgPoint(ev); upR(r => { const c = r.cables.find(x => x.id === cle); if (c) c.coudes.push({ x: Math.round(p.x / 10) * 10, y: Math.round(p.y / 10) * 10 }); }); };
    const majCable = (cle, champ, val) => upR(r => { const c = r.cables.find(x => x.id === cle); if (c) c[champ] = val; });
    const filSel = construit.fils.find(f => f.cle === selectionFil) || null;

    // ── Régénérer, modèles ──
    const regenerer = () => {
      commettre();
      setM(prev => {
        let frais = null; try { frais = regenererDepuis ? regenererDepuis() : null; } catch (e) { frais = null; }
        if (!frais) return { ...prev, retouches: retouchesDefaut() };
        const n = JSON.parse(JSON.stringify(frais));
        // les numéros Hydro-Québec saisis ou lus sur la facture et la version restent ; le reste repart de la soumission
        n.hq = { ...n.hq, ...Object.fromEntries(Object.entries(prev.hq || {}).filter(([, v]) => v)) };
        n.meta = { ...n.meta, ...prev.meta }; n.retouches = retouchesDefaut(); return n;
      }); setSelection(null); setSelectionFil(null); setToast({ ok: "Schéma régénéré depuis la soumission ; sceau et logos conservés" }); };
    const enregistrerModele = async () => {
      const nom = nomModele.trim(); if (!nom) { setToast({ err: "Donne un nom au modèle" }); return; }
      if (MODELES_INTEGRES.some(x => x.nom === nom)) { setToast({ err: "Ce nom est celui d'un modèle intégré : choisis un autre nom" }); return; }
      const gabarit = JSON.parse(JSON.stringify(m)); gabarit.client = { nom: "", adresse1: "", adresse2: "", telephone: "", courriel: "" }; gabarit.hq = { ...gabarit.hq, numero_client: "", numero_contrat: "", numero_compteur: "", dossier: "", titulaire: "" }; gabarit.meta = { dossier: "", version: "v1", date: "" };
      const liste = modeles.filter(x => x.nom !== nom).concat([{ nom, date: auj(), modele: gabarit }]);
      try { if (window.RaycastDB && window.RaycastDB.saveAppSetting) await window.RaycastDB.saveAppSetting("schema_modeles", { modeles: liste }); setModeles(liste); setNomModele(""); setToast({ ok: `Modèle « ${nom} » enregistré` }); }
      catch (e) { setToast({ err: "Modèle non enregistré : " + e.message }); }
    };
    // Modèle intégré : le système vient du modèle, le calibre et la tension de l'entrée restent ceux du client ; modèle enregistré : tel quel
    const appliquerModele = (md) => {
      if (!md) return;
      const base = md.integre ? depuisModeleIntegre(md.id) : JSON.parse(JSON.stringify(md.modele)); if (!base) return;
      commettre(); setM(prev => { const n = base; n.client = prev.client; n.hq = { ...n.hq, ...prev.hq }; if (md.integre) { n.service = { ...prev.service, embase: base.service.embase || "standard" }; n.options = { ...prev.options }; } n.meta = { ...prev.meta, version: prev.meta.version || "v1", date: prev.meta.date || auj() }; n.retouches = normaliserRetouches(n.retouches); return n; });
      setSelection(null); setSelectionFil(null); setToast({ ok: `Schéma reparti du modèle « ${md.nom} »` });
    };
    const partirDuModele = () => appliquerModele(modeleChoisi.startsWith("int:") ? MODELES_INTEGRES.find(x => "int:" + x.id === modeleChoisi) : modeles.find(x => x.nom === modeleChoisi));
    const supprimerModele = async () => { if (modeleChoisi.startsWith("int:")) { setToast({ err: "Un modèle intégré ne se supprime pas" }); return; } const md = modeles.find(x => x.nom === modeleChoisi); if (!md) return; const liste = modeles.filter(x => x.nom !== md.nom); try { if (window.RaycastDB && window.RaycastDB.saveAppSetting) await window.RaycastDB.saveAppSetting("schema_modeles", { modeles: liste }); setModeles(liste); setModeleChoisi(""); setToast({ ok: "Modèle supprimé" }); } catch (e) { setToast({ err: e.message }); } };

    const pdf = async (format) => { try { setOccupe("pdf"); const blob = await exporterPDF(svgRef.current, format); telecharger(blob, nomFichier(m, "pdf")); setToast({ ok: `PDF ${format === "letter" ? "lettre" : "11 × 17"} téléchargé` }); } catch (e) { setToast({ err: e.message }); } finally { setOccupe(null); } };
    const png = async () => { try { setOccupe("png"); const blob = await exporterPNG(svgRef.current, 2); telecharger(blob, nomFichier(m, "png")); setToast({ ok: "PNG téléchargé" }); } catch (e) { setToast({ err: e.message }); } finally { setOccupe(null); } };
    const enregistrer = async () => {
      try {
        setOccupe("save");
        // Nom fixé au premier enregistrement ; chaque enregistrement suivant met à jour le même fichier
        const fichier = (m.meta && m.meta.fichier) || nomFichierBase(m, "pdf");
        const m2 = JSON.parse(JSON.stringify(m)); m2.meta.fichier = fichier;
        if (!(m.meta && m.meta.fichier)) setM(prev => ({ ...prev, meta: { ...prev.meta, fichier } }));
        if (onEnregistrer) onEnregistrer(m2);
        const cle = cleClient(m2);
        if (cle && window.RAYCAST_SUPABASE) {
          try {
            const { data: u } = await window.RAYCAST_SUPABASE.auth.getUser(); const uid = u && u.user ? u.user.id : null;
            await window.RAYCAST_SUPABASE.from("schemas_unifilaires").upsert({ client_key: cle, fichier, version: m2.meta.version || "v1", modele: m2, updated_by: uid, created_by: uid }, { onConflict: "client_key,fichier" });
          } catch (e) { /* sauvegarde du modèle facultative : le PDF reste la référence */ }
        }
        if (cle && window.CatalogueRE && window.CatalogueRE.WORKER_URL && window.RAYCAST_SUPABASE) {
          const blob = await exporterPDF(svgRef.current, "tabloid"); const fd = new FormData(); fd.append("client_key", cle); fd.append("remplacer", "1"); fd.append("fichier", new File([blob], fichier, { type: "application/pdf" }), fichier);
          await workerPost("/raycast/dossier/fichier", fd); setToast({ ok: `Schéma enregistré et mis à jour dans le dossier client : ${fichier} (${m2.meta.version || "v1"})` });
        } else setToast({ ok: onEnregistrer ? "Schéma enregistré dans la soumission (pas de téléphone ni de courriel : dossier client non mis à jour)" : "Aucun dossier client identifiable (téléphone ou courriel manquant)" });
      } catch (e) { setToast({ err: "Dossier client : " + e.message }); } finally { setOccupe(null); }
    };
    const analyserFacture = async (f) => {
      if (!f) return;
      try {
        setOccupe("hq"); const fd = new FormData(); fd.append("fichier", f, f.name);
        const j = await workerPost("/raycast/hq/analyser", fd);
        const ch = j.champs || {}; setM(prev => { const n = JSON.parse(JSON.stringify(prev)); if (ch.numero_client) n.hq.numero_client = ch.numero_client; if (ch.numero_contrat) n.hq.numero_contrat = ch.numero_contrat; if (ch.numero_compteur) n.hq.numero_compteur = ch.numero_compteur; if (ch.nom_titulaire) n.hq.titulaire = ch.nom_titulaire; if (ch.tarif) n.hq.tarif = ch.tarif; if (ch.adresse_service && !n.client.adresse1) { const parts = String(ch.adresse_service).split(","); n.client.adresse1 = parts[0].trim(); n.client.adresse2 = parts.slice(1).join(",").trim(); } return n; });
        setConfiance(j.confiance || {});
        const faibles = Object.entries(j.confiance || {}).filter(([k, v]) => ch[k] && v < 0.6).length;
        setToast({ ok: `Facture lue : ${Object.values(ch).filter(v => v !== "" && v !== null).length} champs remplis${faibles ? `, ${faibles} à vérifier (surlignés)` : ""}` });
        const cle = cleClient(m);
        if (deposer && cle) { const fd2 = new FormData(); fd2.append("client_key", cle); fd2.append("fichier", f, f.name); workerPost("/raycast/dossier/fichier", fd2).catch(() => null); }
      } catch (e) { setToast({ err: "Analyse impossible (" + e.message + ") : saisis les numéros à la main" }); } finally { setOccupe(null); if (factureRef.current) factureRef.current.value = ""; }
    };
    const importerPreset = async (f) => { if (!f) return; try { const j = JSON.parse(await f.text()); const n = depuisPreset(j); commettre(); setM(n); setBloc("systeme"); setToast({ ok: "Préréglage importé : vérifie le système et le service" }); } catch (e) { setToast({ err: "Préréglage illisible" }); } finally { if (presetRef.current) presetRef.current.value = ""; } };


    const S = MARQUES[m.systeme.marque] || MARQUES.tesla; const top = construit.top;
    const resultats = chercherPalette(recherche);
    const faible = (k) => confiance[k] != null && confiance[k] < 0.6 && m.hq[k === "nom_titulaire" ? "titulaire" : k];
    const liste = construit.noeuds.filter(x => x.num).sort((a, b) => a.num - b.num).concat(construit.noeuds.filter(x => !x.num), tous.filter(x => masques.has(x.id)).map(x => ({ ...x, num: null })));
    const cablesManuels = (m.retouches.cables || []);
    const annotations = (m.retouches.annotations || []);
    const nbRetouches = Object.keys(m.retouches.positions || {}).length + Object.keys(m.retouches.tailles || {}).length + (m.retouches.masques || []).length + (m.retouches.ajouts || []).length + cablesManuels.length + (m.retouches.cables_retires || []).length + annotations.length;
    return (
      <div className="rc-sch" role="dialog" aria-label="Schéma unifilaire">
        <div className="rc-sch-top">
          <div className="rc-sch-brand">{window.EclairRaycom ? <window.EclairRaycom size={22} /> : null}<div><b>Schéma unifilaire</b><span>{titreContexte || "Édition du schéma"}</span></div></div>
          <div className="rc-sch-outils">
            <button className={"re-btn small" + (outil === "selection" ? " primary" : "")} onClick={() => { setOutil("selection"); setPortEnAttente(null); }} title="Sélectionner, glisser, redimensionner">Sélection</button>
            <button className={"re-btn small" + (outil === "cable" ? " primary" : "")} onClick={() => { setOutil(outil === "cable" ? "selection" : "cable"); setPortEnAttente(null); }} title="Clic sur un port de sortie, puis sur un port d'entrée">Câble</button>
            {outil === "cable" && <>
              <select value={genreCable} onChange={e => setGenreCable(e.target.value)} className="rc-sch-sel">{GENRES_CABLE.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>
              <input value={calibreCable} onChange={e => setCalibreCable(e.target.value)} placeholder="calibre (ex. 2 × 6 AWG)" className="rc-sch-cal" />
              <span className="rc-sch-indice">{portEnAttente ? "Clique maintenant le port d'arrivée" : "Clique un port de départ"}</span>
            </>}
            <span className="rc-sch-sep" />
            <button className="re-btn small ghost" onClick={annuler} disabled={!hist.current.past.length} title="Ctrl+Z">Annuler</button>
            <button className="re-btn small ghost" onClick={retablir} disabled={!hist.current.future.length} title="Ctrl+Y">Rétablir</button>
            <button className="re-btn small ghost" onClick={regenerer} title="Repart de la soumission : efface les retouches à la main, garde le sceau et les logos">Régénérer</button>
          </div>
          <div className="rc-sch-top-actions">
            <button className="re-btn small" onClick={() => presetRef.current && presetRef.current.click()}>Importer un préréglage</button>
            <input ref={presetRef} type="file" accept="application/json,.json" style={{ display: "none" }} onChange={e => importerPreset(e.target.files && e.target.files[0])} />
            <button className="re-btn small ghost" onClick={onFermer}>Fermer</button>
          </div>
        </div>
        <div className="rc-sch-corps">
          <aside className="rc-sch-form">
            <div className="rc-sch-onglets">{[["client", "Client"], ["hq", "Hydro-Québec"], ["service", "Service"], ["systeme", "Système"], ["options", "Options"]].map(([id, l]) => <button key={id} className={bloc === id ? "on" : ""} onClick={() => setBloc(id)}>{l}</button>)}</div>
            {bloc === "client" && <div className="rc-sch-bloc">
              <Champ label="Nom"><input value={m.client.nom} onChange={e => up("client.nom", e.target.value)} /></Champ>
              <Champ label="Adresse"><input value={m.client.adresse1} onChange={e => up("client.adresse1", e.target.value)} placeholder="numéro et rue" /></Champ>
              <Champ label="Ville, code postal"><input value={m.client.adresse2} onChange={e => up("client.adresse2", e.target.value)} /></Champ>
              <Champ label="Téléphone"><input value={m.client.telephone} onChange={e => up("client.telephone", e.target.value)} /></Champ>
              <Champ label="Courriel"><input value={m.client.courriel} onChange={e => up("client.courriel", e.target.value)} /></Champ>
              <Champ label="N° de dossier"><input value={m.meta.dossier} onChange={e => up("meta.dossier", e.target.value)} placeholder="NOM-2026" /></Champ>
              <div className="rc-sch-ligne"><Champ label="Version"><input value={m.meta.version} onChange={e => up("meta.version", e.target.value)} /></Champ><Champ label="Date"><input value={m.meta.date} onChange={e => up("meta.date", e.target.value)} /></Champ></div>
            </div>}
            {bloc === "hq" && <div className="rc-sch-bloc">
              <div className="rc-sch-analyse">
                <button className="re-btn primary small" disabled={occupe === "hq"} onClick={() => factureRef.current && factureRef.current.click()}>{occupe === "hq" ? "Lecture en cours…" : "Analyser une facture Hydro-Québec"}</button>
                <input ref={factureRef} type="file" accept="image/*,application/pdf" style={{ display: "none" }} onChange={e => analyserFacture(e.target.files && e.target.files[0])} />
                <label className="rc-sch-check"><input type="checkbox" checked={deposer} onChange={e => setDeposer(e.target.checked)} /> Déposer la facture dans le dossier client</label>
                <p className="re-muted">Photo ou PDF de la facture : les numéros de client, de contrat et de compteur, le titulaire, le tarif et l'adresse de service se remplissent. Les champs incertains sont surlignés.</p>
              </div>
              <Champ label="N° de client" faible={faible("numero_client")}><input value={m.hq.numero_client} onChange={e => up("hq.numero_client", e.target.value)} placeholder="9 chiffres" /></Champ>
              <Champ label="N° de contrat" faible={faible("numero_contrat")}><input value={m.hq.numero_contrat} onChange={e => up("hq.numero_contrat", e.target.value)} placeholder="9 chiffres" /></Champ>
              <Champ label="N° de compteur" faible={faible("numero_compteur")}><input value={m.hq.numero_compteur} onChange={e => up("hq.numero_compteur", e.target.value)} placeholder="ex. G8SJ0000000" /></Champ>
              <Champ label="Titulaire du compte" faible={faible("nom_titulaire")}><input value={m.hq.titulaire} onChange={e => up("hq.titulaire", e.target.value)} /></Champ>
              <Champ label="Tarif" faible={faible("tarif")}><select value={m.hq.tarif} onChange={e => up("hq.tarif", e.target.value)}>{["D", "Flex D", "DT", "DM", "G", "M"].map(t => <option key={t}>{t}</option>)}</select></Champ>
              <Champ label="N° de dossier HQ"><input value={m.hq.dossier} onChange={e => up("hq.dossier", e.target.value)} placeholder="si déjà attribué" /></Champ>
            </div>}
            {bloc === "service" && <div className="rc-sch-bloc">
              <Champ label="Calibre de l'entrée"><select value={m.service.calibre} onChange={e => up("service.calibre", Number(e.target.value))}>{[100, 200, 320, 400].map(a => <option key={a} value={a}>{a} A</option>)}</select></Champ>
              <Champ label="Tension"><select value={m.service.tension} onChange={e => up("service.tension", e.target.value)}>{["120/240 V", "120/208 V"].map(t => <option key={t}>{t}</option>)}</select></Champ>
              <Champ label="Embase"><select value={m.service.embase} onChange={e => up("service.embase", e.target.value)}><option value="standard">Compteur et panneau</option><option value="meter_main">Embase avec disjoncteur intégré (meter main)</option></select></Champ>
              <p className="re-muted">À 320 A ou 400 A : coffret à fusibles cadenassable et deux panneaux 200 A, une passerelle possible sur chacun.</p>
              <Champ label="Mise à la terre"><input type="checkbox" checked={!!m.options.malt} onChange={e => up("options.malt", e.target.checked)} /></Champ>
            </div>}
            {bloc === "systeme" && <div className="rc-sch-bloc">
              <Champ label="Projet"><select value={m.systeme.objectif} onChange={e => up("systeme.objectif", e.target.value)}><option value="vide">Aucune composante</option><option value="service">Entrée électrique seulement</option><option value="solaire_batterie">Solaire + stockage</option><option value="batterie">Stockage seul</option><option value="solaire">Solaire seul (mesurage net)</option><option value="borne">Borne seule</option></select></Champ>
              {["batterie", "solaire_batterie"].includes(m.systeme.objectif) && <>
                <Champ label="Marque"><select value={m.systeme.marque} onChange={e => { up("systeme.marque", e.target.value); up("pv.rsd", MARQUES[e.target.value].rsd); }}>{Object.entries(MARQUES).map(([k, v]) => <option key={k} value={k}>{v.nom}</option>)}</select></Champ>
                <div className="rc-sch-ligne"><Champ label={m.systeme.marque === "tesla" ? "Powerwall 3" : "Modules"}><input type="number" min={0} max={12} value={m.systeme.nb} onChange={e => up("systeme.nb", Number(e.target.value))} /></Champ>{m.systeme.marque === "tesla" && <Champ label="Passerelles"><input type="number" min={0} max={2} value={m.systeme.nb_gateways} onChange={e => up("systeme.nb_gateways", Number(e.target.value))} /></Champ>}</div>
                {m.systeme.marque === "tesla" ? <Champ label="Expansions"><input type="number" min={0} max={3} value={m.systeme.expansion || 0} onChange={e => up("systeme.expansion", Number(e.target.value) || 0)} /></Champ> : <div className="rc-sch-ligne"><Champ label="Onduleurs"><input type="number" min={0} max={4} value={m.systeme.nb_onduleurs || 0} onChange={e => up("systeme.nb_onduleurs", Number(e.target.value) || 0)} /></Champ><Champ label="Passerelle"><input type="number" min={0} max={1} value={m.systeme.nb_gateways || 0} onChange={e => up("systeme.nb_gateways", Number(e.target.value) || 0)} /></Champ></div>}
                {m.systeme.marque !== "tesla" && <Champ label="Onduleur"><select value={m.systeme.onduleur} onChange={e => { commettre(); const k = e.target.value; setM(prev => ({ ...prev, systeme: { ...prev.systeme, onduleur: k, onduleur_nom: "", onduleur_kw: 0, hors_reseau: !!(ONDULEURS[k] || {}).hors_reseau } })); }}><option value="auto">{(MARQUES[m.systeme.marque] || {}).onduleur || "Onduleur"}</option>{Object.entries(ONDULEURS).filter(([k]) => k.startsWith({ fox: "fox_", lux: "lux_", sigenergy: "sig_" }[m.systeme.marque] || "?")).map(([k, v]) => <option key={k} value={k}>{v.nom}</option>)}</select></Champ>}
                <Champ label="Secours"><select value={m.systeme.secours} onChange={e => up("systeme.secours", e.target.value)}><option value="aucun">Aucun</option><option value="base">Dans la passerelle (charges critiques intégrées)</option><option value="partiel">Partiel (panneau de charges critiques)</option><option value="complet">Complet (toute la maison)</option></select></Champ>
                {m.systeme.secours === "partiel" && <Champ label="Panneau critique"><select value={m.systeme.panneau_critique} onChange={e => up("systeme.panneau_critique", Number(e.target.value))}><option value={100}>100 A</option><option value={60}>60 A</option></select></Champ>}
              </>}
              {m.systeme.objectif === "solaire" && <>
                <Champ label="Onduleur"><select value={m.systeme.onduleur} onChange={e => up("systeme.onduleur", e.target.value)}>{Object.entries(ONDULEURS).map(([k, v]) => <option key={k} value={k}>{v.nom}</option>)}</select></Champ>
                <Champ label="Nombre d'onduleurs"><input type="number" min={1} max={3} value={m.systeme.nb_onduleurs} onChange={e => up("systeme.nb_onduleurs", Number(e.target.value))} /></Champ>
              </>}
              {["solaire", "solaire_batterie"].includes(m.systeme.objectif) && <>
                <div className="rc-sch-ligne"><Champ label="Panneaux"><input type="number" min={0} max={120} value={m.pv.nb} onChange={e => up("pv.nb", Number(e.target.value))} /></Champ><Champ label="Watts"><input type="number" min={300} max={800} step={5} value={m.pv.watts} onChange={e => up("pv.watts", Number(e.target.value))} /></Champ></div>
                <Champ label="Modèle"><input value={m.pv.modele} onChange={e => up("pv.modele", e.target.value)} /></Champ>
                <Champ label="Arrêt rapide"><select value={m.pv.rsd} onChange={e => up("pv.rsd", e.target.value)}><option value="mci">MCI Tesla</option><option value="projoy">ProJoy RSD</option><option value="tigo">Tigo TS4</option><option value="optimiseur">Optimiseurs</option><option value="aucun">Aucun</option></select></Champ>
              </>}
              <div className="rc-sch-resume">{top.sous} · {kwPv(m) ? `PV ${kwPv(m)} kW CC · ` : ""}{m.systeme.objectif !== "solaire" && m.systeme.objectif !== "borne" ? `stockage ${stockageKwh(m)} kWh · ` : ""}{S.dim}</div>
            </div>}
            {bloc === "options" && <div className="rc-sch-bloc">
              <Champ label="Bornes de recharge"><input type="number" min={0} max={3} value={m.bornes.length} onChange={e => { const n = Math.max(0, Math.min(3, Number(e.target.value) || 0)); up("bornes", Array.from({ length: n }, (_, i) => m.bornes[i] || { modele: "Borne VÉ", amperes: 48 })); }} /></Champ>
              {m.bornes.map((b, i) => <div className="rc-sch-ligne" key={i}><Champ label={`Borne ${i + 1}`}><input value={b.modele} onChange={e => { const l = m.bornes.slice(); l[i] = { ...b, modele: e.target.value }; up("bornes", l); }} /></Champ><Champ label="A"><input type="number" min={16} max={80} value={b.amperes} onChange={e => { const l = m.bornes.slice(); l[i] = { ...b, amperes: Number(e.target.value) }; up("bornes", l); }} /></Champ></div>)}
              <Champ label="Bouton EPO"><input type="checkbox" checked={!!m.options.epo} onChange={e => up("options.epo", e.target.checked)} /></Champ>
              <Champ label="Routeur et communication"><input type="checkbox" checked={!!m.options.routeur} onChange={e => up("options.routeur", e.target.checked)} /></Champ>
              <Champ label="Compteur bidirectionnel"><input type="checkbox" checked={!!m.options.mesurage_net} onChange={e => up("options.mesurage_net", e.target.checked)} /></Champ>
            </div>}
          </aside>
          <main className="rc-sch-apercu" onClick={() => { setSel([]); setSelectionFil(null); }}>
            {(construit.vide || construit.avertissements.length > 0) && <div className="rc-sch-avert" role="status">{construit.vide ? "Aucune composante dans la soumission. Ajoute les composantes depuis la palette (recherche, clic ou glisser-déposer sur la scène)." : construit.avertissements.join(" · ")}</div>}
            <div className="rc-sch-feuille"><Page modele={m} construit={construit} editable glisse={glisse} onDrag={onDrag} selection={sel} onSelect={(id, ev) => { if (ev && ev.shiftKey) return; if (!sel.includes(id) || sel.length < 2) setSelection(id); setSelectionFil(null); }} svgRef={svgRef} logoData={logoData} outil={outil} onPort={onPort} portEnAttente={portEnAttente} onResize={onResize} selectionFil={selectionFil} onFilSelect={(c) => { setSelectionFil(c); setSelection(null); setPanneauDroit("cables"); }} onCoudeDrag={onCoudeDrag} onAjouterCoude={onAjouterCoude} onAnnotationDrag={onAnnotationDrag} onAnnotationSelect={(id) => { setSelection(id); setPanneauDroit("annotations"); }} /></div>
            <div className="rc-sch-aide">{outil === "cable" ? "Outil Câble : clique un port (cercle) de départ puis un port d'arrivée · double-clic sur un câble pour un coude, glisse les coudes · Suppr retire le câble sélectionné" : "Glisse un appareil par son corps (le câblage suit, grille de 10 px) · Maj + clic pour en sélectionner plusieurs et les déplacer ensemble · flèches (Maj : 10 px) · poignée en bas à droite pour redimensionner · Suppr retire · Ctrl+Z annule · Échap"}{nbRetouches ? ` · ${nbRetouches} retouche${nbRetouches > 1 ? "s" : ""} à la main` : ""}</div>
          </main>
          <aside className="rc-sch-droite">
            <div className="rc-sch-actions">
              <button className="re-btn primary" disabled={!!occupe} onClick={() => pdf("tabloid")}>{occupe === "pdf" ? "Export…" : "Exporter PDF 11 × 17"}</button>
              <div className="rc-sch-ligne"><button className="re-btn" disabled={!!occupe} onClick={() => pdf("letter")}>PDF lettre</button><button className="re-btn" disabled={!!occupe} onClick={png}>PNG</button></div>
              <button className="re-btn" disabled={!!occupe} onClick={enregistrer}>{occupe === "save" ? "Enregistrement…" : "Enregistrer (soumission + dossier)"}</button>
            </div>
            <div className="rc-sch-modeles">
              <b>Partir d'un modèle</b>
              <div className="rc-sch-modeles-integres" role="list" aria-label="Modèles Raycom">
                {MODELES_INTEGRES.map(md => <button key={md.id} type="button" role="listitem" className="rc-sch-modele-int" data-modele={md.id} title={`${md.description}. ${md.frequence}.`} onClick={() => appliquerModele(md)}><span>{md.nom}</span><em>{md.devis} devis · {md.ventes} ventes</em></button>)}
              </div>
              <b>Mes modèles</b>
              <div className="rc-sch-ligne"><input value={nomModele} onChange={e => setNomModele(e.target.value)} placeholder="nom du modèle" /><button className="re-btn small" onClick={enregistrerModele} disabled={!nomModele.trim()}>Enregistrer comme modèle</button></div>
              <div className="rc-sch-ligne"><select value={modeleChoisi} onChange={e => setModeleChoisi(e.target.value)}><option value="">Partir d'un modèle…</option><optgroup label="Modèles Raycom">{MODELES_INTEGRES.map(md => <option key={md.id} value={"int:" + md.id}>{md.nom}</option>)}</optgroup>{modeles.length > 0 && <optgroup label="Mes modèles">{modeles.map(md => <option key={md.nom} value={md.nom}>{md.nom}</option>)}</optgroup>}</select><div className="rc-sch-ligne"><button className="re-btn small" onClick={partirDuModele} disabled={!modeleChoisi}>Appliquer</button><button className="re-btn small ghost" onClick={supprimerModele} disabled={!modeleChoisi || modeleChoisi.startsWith("int:")} title={modeleChoisi.startsWith("int:") ? "Modèle intégré : non supprimable" : "Supprimer ce modèle"}>✕</button></div></div>
            </div>
            <div className="rc-sch-onglets">{[["composantes", `Composantes (${liste.length})`], ["cables", `Câbles (${cablesManuels.length})`], ["annotations", `Annotations (${annotations.length})`]].map(([id, l]) => <button key={id} className={panneauDroit === id ? "on" : ""} onClick={() => setPanneauDroit(id)}>{l}</button>)}</div>
            {panneauDroit === "composantes" && <div className="rc-sch-legende">
              <div className="rc-sch-palette">
                <input className="rc-sch-recherche" type="search" value={recherche} onChange={e => setRecherche(e.target.value)} placeholder="Rechercher une composante (ex. passerelle, RSD, borne 48 A)" aria-label="Rechercher une composante" />
                <div className="rc-sch-pal-liste">
                  {resultats.map(g => <div key={g.groupe} className="rc-sch-pal-groupe"><b>{g.groupe} <span>{g.items.length}</span></b>{g.items.map(x => <div key={x.cle} className="rc-sch-pal-item" data-cle={x.cle} role="button" tabIndex={0} title="Clic pour ajouter, ou glisse sur la scène à l'endroit voulu" onMouseDown={e => debutPalette(e, x.cle)} onKeyDown={e => { if (e.key === "Enter") ajouterComposante(x.cle); }}>{x.nom}</div>)}</div>)}
                  {!resultats.length && <p className="re-muted">Aucune composante pour « {recherche} ».</p>}
                </div>
              </div>
              {liste.map(n => { const masque = masques.has(n.id); const ouvert = !!deplie[n.id]; const leg = n.leg || [n.nom, "", ""]; return <div key={n.id} className={"rc-sch-item" + (selection === n.id ? " sel" : "") + (masque ? " off" : "")}>
                <button className="rc-sch-num" onClick={() => setSelection(n.id)} title="Sélectionner">{n.num || "·"}</button>
                <div className="rc-sch-item-corps">
                  <input value={n.nom || ""} onChange={e => renommer(n.id, e.target.value)} onFocus={() => setSelection(n.id)} placeholder="nom" />
                  <input className="rc-sch-cote" value={n.cote || ""} onChange={e => coter(n.id, e.target.value)} placeholder="cote (A, kW, kWh)" />
                  <span className="rc-sch-type">{n.type}</span>
                  {ouvert && <div className="rc-sch-leg-edit"><input value={leg[0] || ""} onChange={e => legender(n.id, 0, e.target.value)} placeholder="légende : nom" /><input value={leg[1] || ""} onChange={e => legender(n.id, 1, e.target.value)} placeholder="légende : détail" /><input value={leg[2] || ""} onChange={e => legender(n.id, 2, e.target.value)} placeholder="légende : norme" /></div>}
                </div>
                <div className="rc-sch-item-btn">
                  <button title="Légende" onClick={() => setDeplie(d => ({ ...d, [n.id]: !ouvert }))}>{ouvert ? "▴" : "▾"}</button>
                  {n.num && <button title="Monter" onClick={() => deplacerOrdre(n.id, -1)}>▲</button>}
                  {n.num && <button title="Descendre" onClick={() => deplacerOrdre(n.id, 1)}>▼</button>}
                  <button className="rc-sch-oeil" title={masque ? "Afficher" : "Masquer"} onClick={() => masquer(n.id)}>{masque ? "◌" : "●"}</button>
                  <button title={String(n.id).startsWith("aj_") ? "Retirer" : "Masquer"} onClick={() => retirerComposante(n.id)}>✕</button>
                </div>
              </div>; })}
            </div>}
            {panneauDroit === "cables" && <div className="rc-sch-legende">
              {filSel ? <div className="rc-sch-cable-sel">
                <b>Câble sélectionné</b>
                <div>{(construit.noeuds.find(x => x.id === filSel.de) || {}).nom || filSel.de} → {(construit.noeuds.find(x => x.id === filSel.a) || {}).nom || filSel.a}</div>
                {filSel.manuel ? <>
                  <Champ label="Type"><select value={filSel.genre} onChange={e => majCable(filSel.cle, "genre", e.target.value)}>{GENRES_CABLE.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></Champ>
                  <Champ label="Calibre"><input value={filSel.calibre || ""} onChange={e => majCable(filSel.cle, "calibre", e.target.value)} placeholder="ex. 2 × 6 AWG + MALT" /></Champ>
                  <p className="re-muted">{(filSel.coudes || []).length} coude(s) · double-clic sur le câble pour en ajouter un</p>
                </> : <p className="re-muted">Câble automatique : il suit les appareils.</p>}
                <button className="re-btn small" onClick={() => retirerCable(filSel.cle)}>Retirer ce câble</button>
              </div> : <p className="re-muted">Clique un câble sur le dessin pour le modifier, ou prends l'outil Câble pour en tracer un entre deux ports.</p>}
              {cablesManuels.length > 0 && <div><b>Câbles ajoutés</b>{cablesManuels.map(c => <div key={c.id} className={"rc-sch-item rc-sch-item-cable" + (selectionFil === c.id ? " sel" : "")}><button className="rc-sch-num" onClick={() => setSelectionFil(c.id)}>↔</button><div className="rc-sch-item-corps"><span>{(construit.noeuds.find(x => x.id === c.de) || {}).nom || c.de} → {(construit.noeuds.find(x => x.id === c.a) || {}).nom || c.a}</span><span className="re-muted">{(GENRES_CABLE.find(g => g[0] === c.genre) || [])[1]}{c.calibre ? ` · ${c.calibre}` : ""}</span></div><div className="rc-sch-item-btn"><button onClick={() => retirerCable(c.id)}>✕</button></div></div>)}</div>}
              {(m.retouches.cables_retires || []).length > 0 && <div><b>Câbles automatiques retirés</b>{m.retouches.cables_retires.map(c => <div key={c} className="rc-sch-item rc-sch-item-cable"><span className="rc-sch-num">⌀</span><div className="rc-sch-item-corps"><span>{c.replace(">", " → ")}</span></div><div className="rc-sch-item-btn"><button title="Restaurer" onClick={() => restaurerCable(c)}>↺</button></div></div>)}</div>}
            </div>}
            {panneauDroit === "annotations" && <div className="rc-sch-legende">
              <div className="rc-sch-ajout"><input value={texteAnnotation} onChange={e => setTexteAnnotation(e.target.value)} placeholder="texte libre sur le dessin" onKeyDown={e => { if (e.key === "Enter") ajouterAnnotation(); }} /><button className="re-btn small primary" disabled={!texteAnnotation.trim()} onClick={ajouterAnnotation}>Ajouter</button></div>
              {annotations.map(a => <div key={a.id} className={"rc-sch-item" + (selection === a.id ? " sel" : "")}><button className="rc-sch-num" onClick={() => setSelection(a.id)}>T</button><div className="rc-sch-item-corps"><input value={a.texte} onChange={e => majAnnotation(a.id, "texte", e.target.value)} onFocus={() => setSelection(a.id)} /><input className="rc-sch-cote" type="number" min={7} max={40} value={a.taille || 11} onChange={e => majAnnotation(a.id, "taille", Number(e.target.value) || 11)} title="Taille" /></div><div className="rc-sch-item-btn"><button onClick={() => retirerComposante(a.id)}>✕</button></div></div>)}
              {!annotations.length && <p className="re-muted">Aucune annotation. Tape un texte et Ajouter, puis glisse-le sur le dessin.</p>}
            </div>}
          </aside>
        </div>
        {toast && <div className={"rc-sch-toast" + (toast.err ? " err" : "")}>{toast.err || toast.ok}</div>}
        {fantome && <div className="rc-sch-fantome" style={{ left: fantome.x + 12, top: fantome.y + 8 }}>{(PALETTE.find(x => x.cle === fantome.cle) || {}).nom}</div>}
      </div>
    );
  }

  // ───────────────────────── Boutons d'entrée ─────────────────────────
  function SchemaBoutonRE({ state, setState, libelle }) {
    const [ouvert, setOuvert] = useState(false);
    // Le système vient TOUJOURS des lignes du devis ; du schéma enregistré, on garde seulement le client saisi, les numéros HQ,
    // le service, les options et les retouches à la main (depuisSoumission s'en charge)
    const initial = useMemo(() => { if (!ouvert) return null; const f = depuisSoumission(state); const sv = state.schema_unifilaire; if (sv && sv.client) f.client = { ...f.client, ...Object.fromEntries(Object.entries(sv.client).filter(([, v]) => v)) }; if (sv && sv.meta) f.meta = { ...f.meta, dossier: sv.meta.dossier || f.meta.dossier, fichier: sv.meta.fichier || f.meta.fichier }; return f; }, [ouvert]); // eslint-disable-line
    return <>
      <button type="button" className="re-btn" onClick={() => setOuvert(true)} title="Schéma unifilaire pour la demande Hydro-Québec, prérempli depuis cette soumission">{libelle || "Schéma unifilaire"}</button>
      {ouvert && ReactDOM.createPortal(<Studio initial={initial} onFermer={() => setOuvert(false)} titreContexte={state.client && state.client.name ? `Soumission · ${state.client.name}` : null} regenererDepuis={() => depuisSoumission({ ...state, schema_unifilaire: null })} onEnregistrer={(m) => setState && setState(prev => ({ ...(typeof prev === "object" ? prev : state), schema_unifilaire: m }))} />, document.body)}
    </>;
  }
  function SchemaBoutonFicheRE({ prefill, libelle }) {
    const [ouvert, setOuvert] = useState(null);      // modèle à ouvrir dans le studio
    const [choix, setChoix] = useState(null);        // schémas existants du client (menu)
    const [charge, setCharge] = useState(false);
    const cle = cleClient(depuisFiche(prefill));
    const ouvrirMenu = async () => {
      setCharge(true); const liste = await schemasDuClient(cle); setCharge(false);
      if (!liste.length) { setOuvert(depuisFiche(prefill)); return; }
      setChoix(liste);
    };
    const modifier = (sch) => {
      const x = JSON.parse(JSON.stringify(sch.modele || {})); const base = depuisFiche(prefill);
      const mo = { ...base, ...x, client: { ...base.client, ...Object.fromEntries(Object.entries(x.client || {}).filter(([, v]) => v)) }, meta: { ...(x.meta || {}), fichier: sch.fichier, version: suivante(x.meta && x.meta.version ? x.meta.version : sch.version || "v1") } };
      setChoix(null); setOuvert(mo);
    };
    const quand = (d) => { try { return new Date(d).toLocaleDateString("fr-CA", { timeZone: "America/Toronto", day: "numeric", month: "short", year: "numeric" }); } catch (e) { return ""; } };
    return <>
      <button type="button" className="re-btn" onClick={ouvrirMenu} disabled={charge} title="Schéma unifilaire du client : modifier un schéma existant ou en faire un nouveau">{charge ? "Chargement…" : (libelle || "Schéma unifilaire")}</button>
      {choix && ReactDOM.createPortal(<div className="rc-sch-choix-fond" onClick={() => setChoix(null)}><div className="rc-sch-choix" onClick={e => e.stopPropagation()}>
        <h3>Schémas de {prefill && prefill.name ? prefill.name : "ce client"}</h3>
        <p className="re-muted">Modifier un schéma met à jour le même fichier dans le dossier du client (nouvelle version).</p>
        {choix.map(sch => <button key={sch.id} type="button" className="rc-sch-choix-item" onClick={() => modifier(sch)}><b>{sch.fichier}</b><span>{sch.version || "v1"} · modifié le {quand(sch.updated_at)}</span><em>Modifier</em></button>)}
        <div className="rc-sch-choix-actions"><button type="button" className="re-btn" onClick={() => { setChoix(null); setOuvert(depuisFiche(prefill)); }}>Nouveau schéma</button><button type="button" className="re-btn ghost" onClick={() => setChoix(null)}>Annuler</button></div>
      </div></div>, document.body)}
      {ouvert && ReactDOM.createPortal(<Studio initial={ouvert} regenererDepuis={() => { const b = depuisFiche(prefill); b.meta.fichier = ouvert.meta && ouvert.meta.fichier; return b; }} onFermer={() => setOuvert(null)} titreContexte={prefill && prefill.name ? `Fiche · ${prefill.name}` : null} />, document.body)}
    </>;
  }

  window.SchemaRE = { DEFAUT, depuisSoumission, depuisFiche, depuisPreset, depuisLignes, depuisModeleIntegre, MODELES_INTEGRES, ONDULEURS, lignesDuDevis, construire, cabler, caracteristiques, chercherPalette, topologie, Page, Studio, exporterPNG, exporterPDF, MARQUES, PAGE, PALETTE, GROUPES_PALETTE, retouchesDefaut, normaliserRetouches };
  window.SchemaBoutonRE = SchemaBoutonRE;
  window.SchemaBoutonFicheRE = SchemaBoutonFicheRE;
})();
