// proposition-re.jsx : proposition client Raycom, deck 1920 × 1080 conforme à la norme Claude Design
// (projet « Soumission combinée Raycom », CLAUDE.md du 5 nov. 2026).
//
//   window.PropositionRE.html(state, calc)        → document HTML autonome : une diapo 1920 × 1080 par section,
//                                                   mise à l'échelle à l'écran, une diapo par page à l'impression (paysage)
//   window.PropositionRE.htmlInline(state, calc)  → même document, images assets/… converties en data: (PDF serveur)
//   window.PropositionRE.ouvrir(state, calc)      → aperçu dans un onglet + bouton « Imprimer / Enregistrer en PDF »
//   window.PropositionRE.modele(state, calc)      → données calculées du deck (gabarit, volets, subventions, rendement)
//
// Structure fixe : Titre (sans prix) · Qui est Raycom · Nos réalisations · Technologie (systèmes complexes) · Volet(s)
// (prix avant taxes en blocs clé en main) · Secours (stockage sans solaire) · Subventions et Rendement (solaire) ·
// Étapes · Garanties et modalités · Récapitulatif et acceptation (seul endroit où le total taxes incluses apparaît).
// Gabarit choisi d'après les lignes du devis : Tesla (+ solaire), Fox ESS, Lux Power et Volthium, Sigenergy (+ V2X),
// solaire seul, borne seule, travaux. Les blocs de prix regroupent des lignes réelles du devis, jamais un prix unitaire
// ni un numéro de modèle ; leur somme est le sous-total de calc, et le total est calc.ttc (taxes de QuickBooks).

(function () {
  const esc = (s) => String(s == null ? "" : s).replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
  // Langue courante du deck (« fr » ou « en ») : fixée par appliquerLangue(state) au début de html() et de modele().
  // En français, les formats restent ceux de CALC_RE (« 22 823,38 $ ») ; en anglais canadien : « $22,823.38 », « 13.5 kWh ».
  let LOC = "fr-CA";
  const enCA = (n, opts) => (Number(n) || 0).toLocaleString("en-CA", opts);
  const fmt = (n) => LOC === "en-CA" ? enCA(n, { style: "currency", currency: "CAD", minimumFractionDigits: 2, maximumFractionDigits: 2 }) : window.CALC_RE.fmtCAD(n);
  const fmt0 = (n) => LOC === "en-CA" ? enCA(n, { style: "currency", currency: "CAD", minimumFractionDigits: 0, maximumFractionDigits: 0 }) : window.CALC_RE.fmtCAD(n, 0);
  const fmtInt = (n) => LOC === "en-CA" ? enCA(Math.round(Number(n) || 0)) : window.CALC_RE.fmtInt(n);
  const fmtNum = (n) => LOC === "en-CA" ? enCA(n, { minimumFractionDigits: 0, maximumFractionDigits: 1 }) : window.CALC_RE.fmtNum(n);
  const fmtTaux = (n) => (Number(n) || 0).toLocaleString(LOC, { minimumFractionDigits: 0, maximumFractionDigits: 2 });
  const fmtTarif = (n) => (Number(n) || 0).toLocaleString(LOC, { minimumFractionDigits: 2, maximumFractionDigits: 5 });
  const r2 = (x) => Math.round((Number(x) || 0) * 100) / 100;
  const somme = (lignes) => r2((lignes || []).reduce((s, l) => s + (Number(l.montant) || 0), 0));
  /** Taxes comme QuickBooks : TPS et TVQ arrondies séparément. */
  const taxesDe = (ht) => r2(r2(ht * 0.05) + r2(ht * 0.09975));
  const TAUX_TAXES = 0.14975;

  /** Date en toutes lettres. Une date seule (« 2026-11-04 ») est un jour civil, affichée telle quelle ; un horodatage
   *  complet est lu à l'heure de Mascouche. */
  const dateFR = (d, opts = { day: "numeric", month: "long", year: "numeric" }) => {
    const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(d || "").trim());
    if (m) return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toLocaleDateString(LOC, { timeZone: "UTC", ...opts });
    const dt = d ? new Date(d) : new Date();
    return (isNaN(dt.getTime()) ? new Date() : dt).toLocaleDateString(LOC, { timeZone: "America/Toronto", ...opts });
  };

  // ─── Textes du deck, en français et en anglais ───
  // Pour corriger un mot, on le change ici, dans la bonne langue : les deux blocs ont exactement les mêmes clés.
  // Une valeur est soit un texte, soit une petite fonction quand le texte contient un nombre (déjà formaté) ou un nom.
  // Noms propres conservés dans les deux langues : Raycom Électrique, Hydro-Québec, LogisVert, Rénoclimat, noms de produits.
  // Règles : aucun tiret cadratin ; en anglais, « you » neutre et formats canadiens ($1,000 · 13.5 kWh · 40%).
  const TXT = {
    fr: {
      htmlLang: "fr-CA", locale: "fr-CA",
      pct: (v) => `${v} %`,
      // Commun
      surProposition: "Proposition", propositionNo: (n) => `Proposition nº ${n}`, brouillon: "brouillon",
      diapositives: "diapositives", apercu: "aperçu avant envoi", imprimer: "Imprimer / Enregistrer en PDF",
      refVolet: (n) => ` (volet ${n})`, voletN: (n) => `VOLET ${n}`, votreProjet: "VOTRE PROJET", votreSysteme: "VOTRE SYSTÈME", avantTaxesParen: "(avant taxes)",
      sansBruit: "sans bruit ni essence",
      lienEnLigne: "Consultez et répondez en ligne",
      // Blocs commerciaux (volets du devis, sans prix unitaire)
      bCrit: "Secours des circuits essentiels · panneau de charges critiques", bComplet: "Secours de toute la maison · embase de compteur combinée",
      bEntree: "Entrée électrique et distribution", bInst: "Installation, mise en service et gestion de projet",
      bExpTesla: "Capacité additionnelle · batterie d'expansion Powerwall 3", bGwTesla: "Gestion énergétique et backup automatique · Gateway 3",
      bSysTeslaOnd: "Système énergétique Tesla Powerwall 3 · stockage et onduleur solaire intégré", bSysTesla: (kwh) => `Stockage d'énergie Tesla Powerwall 3 · ${kwh} kWh`,
      bGwFox: "Module de gestion de l'énergie · Hub G2", bSysFoxOnd: "Système énergétique Fox ESS · onduleur hybride et batteries empilables", bSysFox: (kwh) => `Stockage Fox ESS · batteries LFP empilables, ${kwh} kWh`,
      bGwSig: "Gestion énergétique et backup automatique · LoadHub 200 A", bV2x: "Recharge bidirectionnelle V2X · borne Sigenergy",
      bSysSigOnd: (kwh) => `Système énergétique Sigenergy · onduleur hybride et stockage ${kwh} kWh`, bSysSig: (kwh) => `Stockage Sigenergy · batteries LFP empilables, ${kwh} kWh`,
      bOndLuxOnd: "Onduleur hybride et gestion de l'énergie · Lux Power", bOndLux: "Communication et suivi à distance · Lux Power", bSysLux: (kwh) => `Stockage Volthium · batteries LFP autochauffantes, ${kwh} kWh`,
      bInfra: "Infrastructure et intégration électrique", bAcc: "Équipements et accessoires du système", bEqPv: "Équipements photovoltaïques",
      bInstBorne: "Installation, câblage et mise en service", bBorneCom: "Borne de recharge commerciale", bBorneN2: "Borne de recharge niveau 2",
      bLog: "Logistique, accès et conditions de chantier", bInstTrav: "Travaux électriques, installation et mise en service", bMat: "Matériel et équipements complémentaires",
      bRabais: (nom) => nom.replace(/,?\s*(modèle|model)\s+\S+/i, ""),
      // Page titre
      titreStockageSolaire: "Votre projet de stockage énergétique et solaire", titreV2x: "Votre maison protégée des pannes, votre véhicule en renfort",
      titreBatterie: "Votre projet de secours par batterie", titreSolaire: "Votre projet de production solaire", titreBorne: "Votre projet de recharge à la maison", titreTravaux: "Votre projet électrique",
      preparePour: "Préparé pour", prepareParRaycom: "Préparé par Raycom Électrique", valide30: "Valide 30 jours",
      // Secours
      secComplet: { sujet: "toute la maison", verbe: "reste alimentée" }, secPartiel: { sujet: "vos circuits essentiels", verbe: "restent alimentés" }, secBase: { sujet: "vos circuits prioritaires", verbe: "restent alimentés" },
      app: { tesla: "application Tesla", fox: "application Fox ESS", sigenergy: "application mySigen", lux: "application Lux Power" }, appFabricant: "application du fabricant",
      // Volet stockage · Tesla
      teslaSujet: (n, kwh) => n > 1 ? `<strong>${n} Powerwall 3</strong> totalisant <strong>${kwh} kWh</strong> qui prennent` : `Un <strong>Powerwall 3</strong> de <strong>${kwh} kWh</strong> qui prend`,
      teslaDesc: (o) => `${o.sujet} le relais en une fraction de seconde : dès qu'Hydro-Québec tombe, ${o.sec.sujet} ${o.sec.verbe}, sans bruit ni essence. ${o.aSol ? `La partie onduleur solaire du Powerwall 3 est présentée avec votre système photovoltaïque${o.refSol}.` : "Son onduleur solaire intégré de 11,5 kW est déjà en place si vous décidez d'ajouter des panneaux plus tard : un seul équipement, deux fonctions."}`,
      teslaIncPw: ["Batterie LFP, garantie Tesla 10 ans"], teslaIncGw: ["Gateway 3 · 200 A", "Bascule automatique dès qu'une panne survient"],
      teslaIncComplet: ["Toute la maison protégée", "Embase de compteur combinée 200 A approuvée Hydro-Québec"], teslaIncPartiel: ["Circuits essentiels protégés", "Panneau de charges critiques de 100 A : beaucoup plus de circuits (frigo, congélateur, pompes, chauffage, Wi-Fi)"],
      teslaIncBase: (c120, c240) => ["Circuits prioritaires protégés", c120 > 0 ? `Dans la passerelle : jusqu'à ${c120} circuits 120 V, ou ${c240} circuit${c240 > 1 ? "s" : ""} 240 V de 40 A max.` : "Passerelle pleine : panneau de charges critiques requis"], teslaIncExp: ["Batterie d'expansion · 13,5 kWh", "Capacité additionnelle, même garantie Tesla"],
      teslaIncPermis: ["Permis et démarches Hydro-Québec", "Dossier préparé et déposé par Raycom"], teslaIncMes: ["Mise en service Tesla", "Programmation et configuration de l'application Tesla"],
      teslaTitre: "Stockage d'énergie · Tesla Powerwall 3", teslaSous: "Garantie Tesla 10 ans", teslaAlt: "Batterie Powerwall 3 installée sur la façade d'une résidence",
      // Volet stockage · Fox ESS
      foxTitre: "Stockage d'énergie · Fox ESS", foxSous: (kwh) => `Batteries LFP ${kwh} kWh`,
      foxDesc: (o) => `${o.kwh} kWh de stockage en batteries LFP Fox ESS empilables, ${o.aSol ? `raccordées à l'onduleur hybride de votre système photovoltaïque${o.refSol}` : "gérées par l'onduleur hybride Fox ESS"}. Lors d'une panne, elles prennent le relais automatiquement et gardent ${o.complet ? "toute la maison alimentée" : o.sec.sujet + " alimentés"}, sans bruit ni essence.${o.aSol ? " Le jour, vos panneaux les rechargent." : " L'onduleur hybride est déjà prêt à recevoir des panneaux solaires."}`,
      foxIncModules: (n, kwh) => `${n} module${n > 1 ? "s" : ""} LFP Fox ESS · ${kwh} kWh`, transfertComplet: "Transfert automatique · toute la maison", transfertPrio: "Transfert automatique · circuits prioritaires",
      foxIncHub: "Module de gestion de l'énergie Hub G2", foxIncRacc: "Raccordement, câblage de contrôle et protections", foxIncSuivi: "Suivi en temps réel · application Fox ESS",
      foxIncEmpil: "Batteries empilables, capacité évolutive", essaisMes: "Essais et mise en service", foxAlt: "Système de stockage Fox ESS", foxRecap: "Stockage Fox ESS",
      // Volet stockage · Sigenergy
      sigTitreSeul: "Votre système Sigenergy complet", sigTitre: "Stockage d'énergie · Sigenergy", sigSousV2x: "borne V2X",
      sigDesc: (o) => `${o.aSol ? `Des batteries LFP de ${o.kwh} kWh, raccordées à l'onduleur hybride de votre système photovoltaïque${o.refSol}` : `Un onduleur hybride de ${o.kwOnd} kW avec ${o.kwh} kWh de batterie LFP`}${o.loadhub ? ", piloté par le panneau intelligent LoadHub 200 A" : ""} : dès qu'Hydro-Québec tombe, ${o.loadhub ? "votre maison bascule" : o.sec.sujet + " basculent"} sur la batterie par transfert instantané, sans bruit ni essence.${o.v2x ? " La borne bidirectionnelle V2X fait partie du même système : elle recharge votre véhicule et peut le transformer en réserve de secours." : ""}${o.aSol ? "" : " Le tout est déjà prêt à recevoir des panneaux solaires."}`,
      sigIncBackupComplet: "Backup de toute la maison, transfert instantané", sigIncBackupPrio: "Backup des circuits prioritaires, transfert instantané",
      sigIncDistrib: "Distribution intelligente des charges", sigIncRacc: "Raccordement, protections et mise à la terre", sigIncEmpil: "Batteries empilables, jusqu'à 72 kWh",
      sigIncV2x: "Borne V2X bidirectionnelle incluse", sigIncHiver: "Protection hivernale pour l'extérieur", permisHQ: "Permis et démarches Hydro-Québec", sigIncApp: "Application mySigen configurée",
      sigAlt: "Système Sigenergy installé", sigRecapSeul: "Système Sigenergy complet", sigRecap: "Stockage Sigenergy",
      // Volet stockage · Lux Power et Volthium
      luxTitre: "Stockage d'énergie · Lux Power et Volthium", luxSous: (kwh) => `Onduleur hybride et batteries LFP ${kwh} kWh`,
      luxDesc: (o) => `${o.aSol ? `${o.kwh} kWh de stockage LFP Volthium, raccordés à l'onduleur hybride Lux Power de votre système photovoltaïque${o.refSol}` : `Un onduleur hybride Lux Power${o.kwOnd ? ` de ${o.kwOnd} kW` : ""} avec ${o.kwh} kWh de stockage LFP Volthium`}, qui prend le relais automatiquement lors des pannes et garde ${o.complet ? "toute la maison alimentée" : o.sec.sujet + " alimentés"}, sans bruit ni essence.${o.aSol ? "" : " Le même onduleur est prêt à gérer une production solaire : un seul équipement, deux fonctions."}`,
      luxIncBatt: "Batteries raccordées à l'onduleur hybride", luxIncOnd: (kw) => `Onduleur hybride${kw ? ` ${kw} kW` : ""} · 120/240 V`, luxIncUl: (kwh) => `Batteries ${kwh} kWh LFP certifiées UL9540`,
      luxIncConfig: "Configuration, programmation et mise en service", luxIncTests: "Tests de transfert en mode secours", luxRecap: "Stockage Lux Power et Volthium",
      // Volet stockage · autre marque
      stoTitre: "Stockage d'énergie", stoDesc: (kwh) => `${kwh} kWh de stockage qui prennent le relais automatiquement lors des pannes, sans bruit ni essence.`,
      stoIncTransfert: "Transfert automatique", stoIncRacc: "Raccordement et protections",
      // Volet solaire
      ondTesla: "l'<strong>onduleur solaire 11,5 kW du Powerwall 3</strong>", ondHybride: (marque, kw) => `l'<strong>onduleur hybride ${marque}${kw ? ` de ${kw} kW` : ""}</strong>`,
      solIncStructure: "Structure de montage, crochets et solins étanches", solIncRsd: "Arrêt rapide (Rapid Shutdown) conforme", solIncOpt: "Optimiseurs de production et arrêt rapide",
      solIncDc: "Câblage DC et sectionneurs", solIncDcProt: "Câblage DC, protections et mise à la terre", solIncOnd: (marque, kw) => `Onduleur hybride ${marque}${kw ? ` ${kw} kW` : ""}`,
      solIncAutoprod: "Demande d'autoproduction Hydro-Québec", solIncTests: "Tests électriques et vérification finale", solIncMes: "Essais et mise en service complète",
      solTitre: (kw) => `Système photovoltaïque ${kw} kW`, solSous: (n, kw) => `${n} panneaux · ${kw} kW DC`,
      solDesc: (o) => `${o.n} panneaux <strong>${o.mp ? o.mp + " " : ""}de ${o.w || ""} W</strong>${o.bif ? " bifaciaux" : ""}, sur votre toiture, ${o.ondTxt ? `avec ${o.ondTxt} qui convertit votre production` : "raccordés au réseau en mesurage net"}. Solution clé en main, de la conception à la mise en service.`.replace(" de  W", ""),
      // Volet borne
      borneTitre: "Recharge de véhicule électrique", borneSous: "Borne 240 V installée par un maître électricien",
      borneDesc: "Une borne de recharge 240 V raccordée à votre panneau par un maître électricien, avec disjoncteur dédié et câblage conforme. Votre véhicule se recharge complètement pendant la nuit, à la maison.",
      borneIncBorne: "Borne de recharge niveau 2", borneIncCablage: "Câblage et raccordement de la borne", borneIncDisj: "Disjoncteur dédié et câblage conforme", borneIncInst: "Installation et raccordement au panneau",
      borneIncEssais: "Configuration et essais de recharge", borneIncExpl: "Explications et prise en main", borneAlt: "Borne de recharge", borneAltVe: "Véhicule électrique en recharge",
      // Volet travaux
      travTitreN: "Travaux électriques complémentaires", travTitre: "Vos travaux électriques", travSous: "Par maître électricien",
      travDesc: "Travaux électriques réalisés par nos électriciens, conformes au Code de construction du Québec, chapitre V, Électricité. Matériel, main-d'œuvre, essais et nettoyage du chantier inclus.",
      travInc: ["Matériel et fournitures", "Main-d'œuvre par électriciens licenciés", "Protections et mise à la terre", "Essais et vérification finale"], travRecap: "Travaux électriques",
      // Qui est Raycom
      raycomSur: "Qui est Raycom Électrique", raycomTitreSol: "Maître électricien et spécialiste solaire", raycomTitre: "Maître électricien et spécialiste en énergie",
      raycomTexte: "Garder le courant pendant les pannes, produire votre propre énergie et recharger votre véhicule à la maison : c'est ce que Raycom Électrique installe chaque semaine dans Lanaudière, les Laurentides et le Grand Montréal. Une entreprise d'électriciens établie à Mascouche, des équipements choisis pour les conditions du Québec, et des installations propres, conformes et faites pour durer.",
      tuileAns: "22 ans", tuileExp: "d'expérience en électricité", tuileAvis: "avis Google", tuileDepuis: "maître électricien depuis",
      altTesla: "Installateur certifié Tesla Powerwall", altCmeq: "Corporation des maîtres électriciens du Québec", membreCmeqLic: "Membre CMEQ<br>Licence RBQ 5590-9402-01", altInstallation: "Installation réalisée par Raycom",
      // Réalisations
      realSur: "Nos réalisations", realTesla: "L'énergie Tesla, installée dans votre foyer", realSig: "L'énergie Sigenergy, installée dans votre foyer", realSol: "L'énergie solaire, installée dans votre foyer",
      regions: "Lanaudière · Laurentides · Grand Montréal", altRealisation: "Réalisation Raycom",
      // Technologie
      techSur: "La technologie proposée", techTitreSig: "Sigenergy : un système intelligent tout-en-un", techTitreLux: "Un duo fiable, pensé pour l'hiver québécois",
      techSigStorSous: "Onduleur et batterie", techSigStor: (kw, kwh, aSol) => [`Onduleur hybride ${kw} kW · batterie LFP ${kwh} kWh`, "Modulaire : empilable jusqu'à 72 kWh", "Extérieur, conçu pour l'hiver québécois", aSol ? "Reçoit directement vos panneaux solaires" : "Déjà prêt pour des panneaux solaires"],
      techHubSous: "Panneau intelligent", techHub: ["Transfert instantané lors d'une panne", "Backup de toute la maison, charges priorisées", "Distribution intelligente de l'énergie", "Suivi en temps réel dans l'application mySigen"],
      techV2xTitre: "Borne V2X", techV2xSous: "Recharge bidirectionnelle", techV2x: ["Recharge rapide DC 25 kW, NACS et CCS1", "V2H : votre véhicule alimente la maison", "Intégrée au même système Sigenergy", "Gestion dans l'application mySigen"],
      techLuxSous: "Onduleur hybride", techLux: ["120/240 V monophasé, transfert automatique", "Entrées solaires intégrées", "Suivi à distance dans l'application Lux Power", "Programmation par Raycom à la mise en service"], techLuxHybride: "Hybride",
      techVolSous: "Batteries LFP", techVol: ["LFP certifiée UL9540, conforme au Code", "Conçue et assemblée au Québec", "Autochauffante, charge sécuritaire par grand froid", "Extensible : ajoutez des modules au besoin"],
      // Diapo volet solaire (carte du toit)
      ensoleillementMesure: "Ensoleillement mesuré sur votre toit", accesSolaire: "Accès solaire", irradianceMoy: "Irradiance moyenne", kwhM2An: "kWh/m²/an", kwhAn: "kWh/an",
      prodMoyEstimee: "Production moyenne estimée", altConception: "Conception du système sur votre toiture", altSolaire: "Système photovoltaïque installé par Raycom", panneaux: "panneaux",
      // Secours et évolutivité
      evolTesla: "Une batterie d'expansion Powerwall 3 de 13,5 kWh s'ajoute plus tard, sans refaire l'installation électrique.",
      evolFox: "Les batteries Fox ESS sont empilables : des modules s'ajoutent plus tard, sans changer l'onduleur.",
      evolSig: "Des modules de batterie s'empilent jusqu'à 72 kWh : ajoutez de la capacité plus tard, sans changer d'équipement.",
      evolLux: "Les batteries Volthium sont modulaires : des modules s'ajoutent en tout temps, sans changer l'onduleur.",
      renoJusqua: (m) => `Rénoclimat · jusqu'à ${m}`,
      renoTexte: (raccord) => `Batterie fixe : jusqu'à 4 000 $ sur l'achat du système${raccord ? " · raccordement de secours : jusqu'à 1 000 $ sur les honoraires du maître électricien, à confirmer auprès de Rénoclimat" : ""}. Résidence principale construite et habitée depuis au moins 5 ans. Estimé, sous réserve des conditions officielles du programme.`,
      secSurSig: "Autonomie et évolutivité", secSur: "Pourquoi ce système", secTitre: "Conçu pour les pannes, prêt pour le solaire", secCarte: "Secours en cas de panne",
      batterieSeule: (kwh) => `Batterie seule · ${kwh} kWh`, heures: (a, b) => `≈ ${a} à ${b} h`, selonCircuits: "selon les circuits utilisés",
      secTransfertInst: "Transfert instantané, aucune manipulation requise", secBascule: "Basculement automatique, aucune manipulation requise",
      secMaison: "Toute la maison alimentée, en silence", secPrio: "Circuits prioritaires alimentés, en silence", secNiveau: (app) => `Niveau de batterie en temps réel dans l'${app}`,
      besoinAutonomie: "Besoin de plus d'autonomie ?", pretSolaire: "Prêt pour le solaire", pretSolaireTitre: "Ajoutez des panneaux plus tard, sans équipement supplémentaire",
      pretSolaireTexte: (o) => `${o.tesla ? "Le Powerwall 3 possède un onduleur solaire intégré de 11,5 kW." : "L'onduleur installé est un onduleur hybride : ses entrées solaires sont déjà en place."} Si vous décidez de produire votre énergie un jour, les panneaux se raccordent directement à l'équipement installé dans ce projet. Le solaire est admissible à la subvention LogisVert d'Hydro-Québec : 1 000 $ par kW installé, jusqu'à 40 % du coût admissible.${o.v2x ? " Votre véhicule branché à la borne V2X devient aussi une réserve de secours pour la maison." : ""}`,
      // Subventions
      subPrincipale: "Résidence principale, maison de 5 ans ou plus", subSecondaire: "Résidence secondaire habitable à l'année, ou maison de moins de 5 ans",
      subSaisonnier: "Chalet saisonnier non habitable à l'année", subAnnee: "Maison ou chalet habitable à l'année", subAucune: "Aucune subvention · 0 $", lvSeulement: "LogisVert seulement",
      renoCarte: "Batterie · Rénoclimat", jusquaCap: (m) => `Jusqu'à ${m}`,
      renoPuceBatt: (s) => `<strong style="${s}">Batterie fixe : jusqu'à 4 000 $</strong><br>sur l'achat du système (batteries et onduleurs)`,
      renoPuceRacc: (s) => `<strong style="${s}">Raccordement de secours : jusqu'à 1 000 $</strong><br>sur les honoraires du maître électricien, à confirmer auprès de Rénoclimat`,
      renoConditions: "Résidence principale construite et habitée depuis au moins 5 ans, habitable à l'année, chauffage capable de maintenir 21 °C. Résidence secondaire exclue. Demande au plus tard 12 mois après les travaux. Admissibilité et cumul avec LogisVert à confirmer par le programme.",
      mesurageCarte: "Mesurage net · Hydro-Québec", surplusCredits: "Surplus = crédits",
      mesurageTexte: "L'électricité produite en trop l'été est injectée sur le réseau et vous revient en crédits kWh, consommables plus tard, l'hiver par exemple. Raccordement autorisé inclus dans notre installation : Raycom prépare et dépose la demande d'autoproduction.",
      subSur: (mois) => `Subventions en vigueur au Québec · ${mois}`, subTitre: "Vos subventions selon votre habitation", subEstimees: "Subventions estimées", jusqua: (m) => `jusqu'à ${m}`,
      lvCarte: "Solaire · Hydro-Québec · LogisVert", lvParKw: "1 000 $ / kW",
      lvTexte: "installé, plafonné à 40 % du coût d'achat et d'installation de la portion solaire (panneaux, onduleur, composants, raccordement). Stockage, réparations de toiture et plans d'ingénierie exclus. Maison ou chalet habitable à l'année : aucune exigence de résidence principale ni d'âge.",
      lvKwFois: (kw) => `${kw} kW × 1 000 $`, lv40de: (m) => `40 % de ${m}`, plafondApplique: "Plafond appliqué : ", plafondKw: "1 000 $ par kW installé", plafond40: "40 % du coût admissible",
      lvVersee: "Versée au propriétaire seulement : le nom sur la facture doit correspondre à la preuve de propriété. Demande au plus tard 9 mois après l'installation, après l'autorisation finale de raccordement d'Hydro-Québec.",
      subSituation: "Subventions selon votre situation", netTaxesIncl: "Net, taxes incluses", autreSubvention: "Autre subvention", autresInclus: (lib, m) => `${lib} : ${m} (inclus)`,
      subSources: "Estimé, sous réserve des conditions officielles des programmes et de l'admissibilité de l'habitation au moment de la demande. Sources : Rénoclimat, Guide du participant, édition 2026 (MELCCFP) · LogisVert, Guide de participation résidentiel v1.10, 15 septembre 2026 (Hydro-Québec).",
      // Rendement
      plusDe40: "plus de 40 ans", moinsDe2: "moins de 2 ans", ansEntre: (a, b) => `${a} à ${b} ans`, mesureeToit: "mesurée sur votre toit", zeroVirgule80: "0,80",
      avantTaxes: "avant taxes", colSolaire: "Solaire", colStockage: "Stockage",
      tSousTotal: "Sous-total avant taxes", tTaxes: "TPS + TVQ (14,975 %)", tTotal: "Total taxes incluses", tMoinsSub: "Moins subvention", tMoinsLv: "Moins LogisVert", tCoutNet: "Coût net",
      projetCompletTI: "Projet complet taxes incluses", coutNetPrincipale: "Coût net, résidence principale 5 ans+", coutNetApresLv: "Coût net après LogisVert",
      autonomieCarte: "Autonomie en cas de panne", batterieSolaire: "Batterie <strong>+ solaire</strong>", plusieursJours: "plusieurs jours",
      // Autonomie calculée sur les charges cochées au configurateur (JF, 6 nov. 2026)
      autoEstimee: "Autonomie estimée", autoBatterie: (kwh) => `Batterie · ${kwh} kWh utilisables`, autoBattSeule: "Batterie seule",
      autoBattSol: (kw) => `<strong>+ ${kw} kW de solaire</strong>`,
      autoSolaireLigne: (p) => `Solaire : ≈ ${p} kWh/jour, journée moyenne de panne`,
      chargesCouvertes: (l) => `<strong>Charges couvertes :</strong> ${l}`, autoEtAutres: (n) => ` et ${n} autre${n > 1 ? "s" : ""}`,
      autoNote: "Batterie pleine au début de la panne ; solaire d'une journée moyenne, un jour sombre produit moins.",
      rendSur: "Rendement et économies · estimations", rendTitre: "Un investissement qui travaille pour vous",
      kpiProd: "Production annuelle", kpiEco: "Économie mensuelle", parMois: (m) => `${m} / mois`, inclTaxesAvant: (m) => `incluant taxes · ${m} avant taxes`,
      kpiLv: "Subvention LogisVert", kpiLvSous: "estimé · montant final par LogisVert", kpiNetRenta: "Coût net rentabilité", kpiNetSol: "Coût net solaire",
      kpiNetPw: (base, lv) => `onduleur Powerwall compté à 2 300 $ · ${base} TTC − ${lv}`, kpiNet: (base, lv) => `${base} TTC − ${lv}`, kpiRoi: "Retour sur investissement",
      ecoCumulees: "Économies cumulées estimées, taxes incluses",
      ecoCalcul: (prod, tarif, an, anT) => `${prod} kWh × ${tarif} $ = <strong style="color:#FFF;">${an} / an</strong> avant taxes, soit ${anT} incluant taxes (14,975 %)`,
      legEco: "Économies cumulées", legNetRenta: "Coût net pour la rentabilité", legNetSol: "Coût net solaire", nAns: (n) => `${n} ans`, calculLigne: "Calcul du coût net, ligne par ligne",
      hypotheses: (o) => `<strong style="color:${o.c};">Hypothèses :</strong> système de ${o.kw} kW${o.google ? " (production mesurée sur votre toit, ombrage inclus" : ` (irradiance ${o.irr} kWh/m²/an, accès solaire ${o.acces} %`}, ratio de performance 80 %) · tarif Hydro-Québec ${o.tarif} $/kWh · indexation ${o.idx} %/an · dégradation ${o.deg} %/an · taxes 14,975 % · crédit hivernal non déduit${o.pw ? " · onduleur du Powerwall 3 compté à 2 300 $ avant taxes dans la rentabilité, son installation exclue" : ""}. Estimations non contractuelles.`,
      // Étapes
      etapesStd: [
        ["On confirme votre projet", ["Signature de l'offre", "Dépôt initial de 1 000 $", "Dossier ouvert le jour même"]],
        ["On gère Hydro-Québec", ["Préparation complète du dossier", "Demande de raccordement déposée", "Suivis jusqu'à l'approbation, rien à faire de votre côté"]],
        ["On commande", ["Dépôt de 50 % après l'acceptation d'Hydro-Québec", "On commande tous les équipements", "On vous donne une date d'installation"]],
        ["On installe", ["Installation des équipements", "Mise en service et tests", "Rapport final transmis à Hydro-Québec"]]
      ],
      etapesSimples: [
        ["On confirme votre projet", ["Signature de l'offre", "Dépôt à la signature", "Dossier ouvert le jour même"]],
        ["On planifie", ["Relevé technique au besoin", "Commande des équipements", "On vous donne une date d'installation"]],
        ["On installe", ["Installation par nos électriciens", "Câblage et protections conformes", "Chantier propre"]],
        ["On met en service", ["Essais et mise en service", "Explications et prise en main", "Solde à la fin des travaux"]]
      ],
      etapesSur: "Étapes du projet", etapesTitre: "Un déroulement simple, un seul interlocuteur",
      // Garanties et modalités (b(...) met un mot en évidence)
      gTesla: (b, gw) => `Garantie limitée Tesla de ${b("10 ans")} sur Powerwall 3${gw ? " et Gateway 3" : ""}.`,
      gFox: (b) => `Fox ESS : ${b("12,5 ans")} sur l'onduleur et les batteries, système enregistré par Raycom.`,
      gSig: (b) => `Sigenergy : ${b("10 ans")} sur l'onduleur et les batteries.`, gLux: (b) => `Lux Power et Volthium : ${b("10 ans")} sur l'onduleur et les batteries.`,
      gLongi: (b) => `Panneaux LONGi : garantie produit ${b("25 ans")} et production linéaire ${b("30 ans")} (≥ 87,4 %).`,
      gJa: (b) => `Panneaux JA Solar : garantie produit ${b("25 ans")} et production linéaire ${b("30 ans")}.`,
      gWall: (b) => `Borne Tesla Wall Connector : ${b("4 ans")}.`, gFlo: (b) => `Borne FLO : ${b("5 ans")}.`, gWallbox: (b) => `Borne Wallbox : ${b("3 ans")}.`,
      gMo: (b) => `Main-d'œuvre Raycom : ${b("2 ans")}.`,
      paiementStd: (b) => `Dépôt de ${b("1 000 $")} à la signature · ${b("50 %")} après l'approbation d'Hydro-Québec et la cédule d'installation · ${b("solde")} à la fin de l'installation et des tests. Virement Interac ou chèque.`,
      paiementSimple: (b) => `Dépôt à la signature pour réserver votre date · ${b("solde")} à la fin de l'installation et des tests. Virement Interac ou chèque.`,
      suiviQuoi: (sol, bat) => sol && bat ? "production et de votre batterie" : sol ? "production" : "batterie",
      apresStd: (b, quoi, app) => `Suivi de votre ${quoi} en temps réel${app ? ` dans l'${b(app)}` : ""}. Support local Raycom, mises à jour logicielles à distance et ${b("accompagnement complet")} pour vos demandes de subventions.`,
      apresSimple: "Support local Raycom : un seul numéro pour toute question. Pour une réclamation, peu importe le composant, nous ouvrons le dossier auprès du fabricant et coordonnons la réparation.",
      finPromo: (s, n, m, taux, mois) => `<br><strong style="${s}">Programme promotionnel : 0 $ de paiement et 0 % d'intérêt pendant ${n} mois</strong>, puis ${m} par mois à ${taux} % sur ${mois} mois pour le projet complet. Sous réserve d'approbation de crédit.`,
      finExemple: (s, m, mois, taux) => `<br>Exemple pour le projet complet : <strong style="${s}">${m} par mois</strong>${mois ? ` sur ${mois} mois` : ""}${taux ? ` à ${taux} %` : ""}. Sous réserve d'approbation de crédit.`,
      carteGaranties: "Garanties", carteModalites: "Modalités de paiement", carteApres: "Après l'installation",
      financeitTitre: "Financement disponible avec notre partenaire Financeit", financeitTexte: "De 1 000 $ à 100 000 $, remboursable sur 12 à 240 mois. Aucuns frais de dossier, remboursement anticipé sans pénalité.",
      note: "Note :",
      conformite: (rbq, nV) => `Travaux conformes au Code de construction du Québec, chapitre V, Électricité · ${rbq} · membre CMEQ. Exclusions : tout travail non décrit ${nV > 1 ? `aux volets 1 à ${nV}` : "dans cette proposition"} (réparations de structure ou de toiture, mise à niveau du panneau existant si requise). Tout extra fait l'objet d'un avenant écrit approuvé avant exécution. Proposition valide 30 jours.`,
      garSur: "Garanties et modalités", garTitre: "Un cadre clair, sans surprise",
      // Récapitulatif et acceptation
      recapLv: (lv, reno, autres, net) => `LogisVert ${lv}${reno ? ` + Rénoclimat jusqu'à ${reno}, si admissible` : ""}${autres ? ` + ${autres}` : ""} · coût net estimé ${net}`,
      renoEstime: "Rénoclimat estimé", jusquaMoins: (m) => `jusqu'à − ${m}`, renoSiAdmissible: (net) => `si admissible, à confirmer par le programme · coût net estimé ${net}`,
      finCarte: "Financement Financeit", finPromoCourt: (n) => `0 $ pendant ${n} mois`, finPuis: (m) => `puis ${m} par mois, `, surApprobation: "sur approbation de crédit",
      recapSur: "Récapitulatif et acceptation", recapTitre: "Résumé de votre système", sousTotalAvant: "Sous-total avant taxes", tpsTvq: "TPS 5 % + TVQ 9,975 %", projetCompletTICap: "PROJET COMPLET · TAXES INCLUSES",
      siege: "Siège social", bureaux: "Bureaux et entrepôt", texto: "texto",
      enSignant: (num, m) => `En signant, vous acceptez la proposition nº ${num} au montant de ${m} taxes incluses.`,
      acceptePar: (nom) => `Accepté par${nom ? ` ${nom}` : ""} (signature)`, date: "Date", membreCmeq: "membre CMEQ"
    },
    en: {
      htmlLang: "en-CA", locale: "en-CA",
      pct: (v) => `${v}%`,
      // Common
      surProposition: "Proposal", propositionNo: (n) => `Proposal No. ${n}`, brouillon: "draft",
      diapositives: "slides", apercu: "preview before sending", imprimer: "Print / Save as PDF",
      refVolet: (n) => ` (part ${n})`, voletN: (n) => `PART ${n}`, votreProjet: "YOUR PROJECT", votreSysteme: "YOUR SYSTEM", avantTaxesParen: "(before taxes)",
      sansBruit: "with no noise and no fuel",
      lienEnLigne: "View and respond online",
      // Price blocks
      bCrit: "Essential circuit backup · critical loads panel", bComplet: "Whole-home backup · combination meter base",
      bEntree: "Electrical service and distribution", bInst: "Installation, commissioning and project management",
      bExpTesla: "Additional capacity · Powerwall 3 expansion battery", bGwTesla: "Energy management and automatic backup · Gateway 3",
      bSysTeslaOnd: "Tesla Powerwall 3 energy system · storage and built-in solar inverter", bSysTesla: (kwh) => `Tesla Powerwall 3 energy storage · ${kwh} kWh`,
      bGwFox: "Energy management module · Hub G2", bSysFoxOnd: "Fox ESS energy system · hybrid inverter and stackable batteries", bSysFox: (kwh) => `Fox ESS storage · stackable LFP batteries, ${kwh} kWh`,
      bGwSig: "Energy management and automatic backup · LoadHub 200 A", bV2x: "V2X bidirectional charging · Sigenergy charger",
      bSysSigOnd: (kwh) => `Sigenergy energy system · hybrid inverter and ${kwh} kWh storage`, bSysSig: (kwh) => `Sigenergy storage · stackable LFP batteries, ${kwh} kWh`,
      bOndLuxOnd: "Hybrid inverter and energy management · Lux Power", bOndLux: "Communication and remote monitoring · Lux Power", bSysLux: (kwh) => `Volthium storage · self-heating LFP batteries, ${kwh} kWh`,
      bInfra: "Electrical infrastructure and integration", bAcc: "System equipment and accessories", bEqPv: "Solar PV equipment",
      bInstBorne: "Installation, wiring and commissioning", bBorneCom: "Commercial EV charger", bBorneN2: "Level 2 EV charger",
      bLog: "Logistics, site access and site conditions", bInstTrav: "Electrical work, installation and commissioning", bMat: "Additional materials and equipment",
      bRabais: (nom) => /promotion/i.test(nom) ? "Manufacturer or distributor promotion" : "Discount",
      // Title slide
      titreStockageSolaire: "Your energy storage and solar project", titreV2x: "Your home protected from outages, your vehicle as backup",
      titreBatterie: "Your battery backup project", titreSolaire: "Your solar power project", titreBorne: "Your home charging project", titreTravaux: "Your electrical project",
      preparePour: "Prepared for", prepareParRaycom: "Prepared by Raycom Électrique", valide30: "Valid for 30 days",
      // Backup
      secComplet: { sujet: "your whole home", verbe: "stays powered" }, secPartiel: { sujet: "your essential circuits", verbe: "stay powered" }, secBase: { sujet: "your priority circuits", verbe: "stay powered" },
      app: { tesla: "Tesla app", fox: "Fox ESS app", sigenergy: "mySigen app", lux: "Lux Power app" }, appFabricant: "manufacturer's app",
      // Storage part · Tesla
      teslaSujet: (n, kwh) => n > 1 ? `<strong>${n} Powerwall 3 units</strong> totalling <strong>${kwh} kWh</strong> take` : `A <strong>${kwh} kWh Powerwall 3</strong> takes`,
      teslaDesc: (o) => `${o.sujet} over in a fraction of a second: the moment Hydro-Québec power goes out, ${o.sec.sujet} ${o.sec.verbe}, with no noise and no fuel. ${o.aSol ? `The solar inverter built into the Powerwall 3 is presented with your solar PV system${o.refSol}.` : "Its built-in 11.5 kW solar inverter is already in place if you decide to add panels later: one unit, two functions."}`,
      teslaIncPw: ["LFP battery, 10-year Tesla warranty"], teslaIncGw: ["Gateway 3 · 200 A", "Switches over automatically the moment an outage occurs"],
      teslaIncComplet: ["Whole home protected", "Hydro-Québec approved 200 A combination meter base"], teslaIncPartiel: ["Essential circuits protected", "100 A critical loads panel: many more circuits (fridge, freezer, pumps, heating, Wi-Fi)"],
      teslaIncBase: (c120, c240) => ["Priority circuits protected", c120 > 0 ? `In the Gateway: up to ${c120} circuits at 120 V, or ${c240} circuit${c240 > 1 ? "s" : ""} at 240 V (40 A max.)` : "Gateway full: critical loads panel required"], teslaIncExp: ["Expansion battery · 13.5 kWh", "Additional capacity, same Tesla warranty"],
      teslaIncPermis: ["Permits and Hydro-Québec applications", "File prepared and submitted by Raycom"], teslaIncMes: ["Tesla commissioning", "Programming and Tesla app setup"],
      teslaTitre: "Energy storage · Tesla Powerwall 3", teslaSous: "10-year Tesla warranty", teslaAlt: "Powerwall 3 battery installed on the front of a home",
      // Storage part · Fox ESS
      foxTitre: "Energy storage · Fox ESS", foxSous: (kwh) => `${kwh} kWh LFP batteries`,
      foxDesc: (o) => `${o.kwh} kWh of storage in stackable Fox ESS LFP batteries, ${o.aSol ? `connected to the hybrid inverter of your solar PV system${o.refSol}` : "managed by the Fox ESS hybrid inverter"}. During an outage, they take over automatically and keep ${o.sec.sujet} powered, with no noise and no fuel.${o.aSol ? " During the day, your panels recharge them." : " The hybrid inverter is already ready for solar panels."}`,
      foxIncModules: (n, kwh) => `${n} Fox ESS LFP module${n > 1 ? "s" : ""} · ${kwh} kWh`, transfertComplet: "Automatic transfer · whole home", transfertPrio: "Automatic transfer · priority circuits",
      foxIncHub: "Hub G2 energy management module", foxIncRacc: "Connection, control wiring and protection devices", foxIncSuivi: "Real-time monitoring · Fox ESS app",
      foxIncEmpil: "Stackable batteries, expandable capacity", essaisMes: "Testing and commissioning", foxAlt: "Fox ESS storage system", foxRecap: "Fox ESS storage",
      // Storage part · Sigenergy
      sigTitreSeul: "Your complete Sigenergy system", sigTitre: "Energy storage · Sigenergy", sigSousV2x: "V2X charger",
      sigDesc: (o) => `${o.aSol ? `${o.kwh} kWh of LFP batteries, connected to the hybrid inverter of your solar PV system${o.refSol}` : `A ${o.kwOnd} kW hybrid inverter with ${o.kwh} kWh of LFP battery storage`}${o.loadhub ? ", controlled by the LoadHub 200 A smart panel" : ""}: the moment Hydro-Québec power goes out, ${o.loadhub ? "your home switches" : o.sec.sujet + " switch"} to the battery instantly, with no noise and no fuel.${o.v2x ? " The bidirectional V2X charger is part of the same system: it charges your vehicle and can turn it into a backup power reserve." : ""}${o.aSol ? "" : " Everything is already ready for solar panels."}`,
      sigIncBackupComplet: "Whole-home backup, instant transfer", sigIncBackupPrio: "Priority circuit backup, instant transfer",
      sigIncDistrib: "Smart load distribution", sigIncRacc: "Connection, protection devices and grounding", sigIncEmpil: "Stackable batteries, up to 72 kWh",
      sigIncV2x: "Bidirectional V2X charger included", sigIncHiver: "Winter protection for outdoor installation", permisHQ: "Permits and Hydro-Québec applications", sigIncApp: "mySigen app set up",
      sigAlt: "Installed Sigenergy system", sigRecapSeul: "Complete Sigenergy system", sigRecap: "Sigenergy storage",
      // Storage part · Lux Power and Volthium
      luxTitre: "Energy storage · Lux Power and Volthium", luxSous: (kwh) => `Hybrid inverter and ${kwh} kWh LFP batteries`,
      luxDesc: (o) => `${o.aSol ? `${o.kwh} kWh of Volthium LFP storage, connected to the Lux Power hybrid inverter of your solar PV system${o.refSol}` : `A${o.kwOnd ? ` ${o.kwOnd} kW` : ""} Lux Power hybrid inverter with ${o.kwh} kWh of Volthium LFP storage`}, taking over automatically during outages and keeping ${o.sec.sujet} powered, with no noise and no fuel.${o.aSol ? "" : " The same inverter is ready to manage solar production: one unit, two functions."}`,
      luxIncBatt: "Batteries connected to the hybrid inverter", luxIncOnd: (kw) => `Hybrid inverter${kw ? ` ${kw} kW` : ""} · 120/240 V`, luxIncUl: (kwh) => `${kwh} kWh LFP batteries, UL9540 certified`,
      luxIncConfig: "Setup, programming and commissioning", luxIncTests: "Backup mode transfer tests", luxRecap: "Lux Power and Volthium storage",
      // Storage part · other brand
      stoTitre: "Energy storage", stoDesc: (kwh) => `${kwh} kWh of storage that takes over automatically during outages, with no noise and no fuel.`,
      stoIncTransfert: "Automatic transfer", stoIncRacc: "Connection and protection devices",
      // Solar part
      ondTesla: "the <strong>Powerwall 3's 11.5 kW solar inverter</strong>", ondHybride: (marque, kw) => `the <strong>${kw ? `${kw} kW ` : ""}${marque} hybrid inverter</strong>`,
      solIncStructure: "Racking, roof hooks and watertight flashing", solIncRsd: "Code-compliant rapid shutdown", solIncOpt: "Power optimizers and rapid shutdown",
      solIncDc: "DC wiring and disconnects", solIncDcProt: "DC wiring, protection devices and grounding", solIncOnd: (marque, kw) => `${marque}${kw ? ` ${kw} kW` : ""} hybrid inverter`,
      solIncAutoprod: "Hydro-Québec self-generation application", solIncTests: "Electrical testing and final inspection", solIncMes: "Full testing and commissioning",
      solTitre: (kw) => `${kw} kW solar PV system`, solSous: (n, kw) => `${n} panels · ${kw} kW DC`,
      solDesc: (o) => `${o.n} <strong>${[o.mp, o.w ? `${o.w} W` : ""].filter(Boolean).join(" ")}</strong>${o.bif ? " bifacial" : ""} panels on your roof, ${o.ondTxt ? `with ${o.ondTxt} converting your production` : "connected to the grid under net metering"}. A turnkey solution, from design to commissioning.`.replace("<strong></strong> ", ""),
      // EV charger part
      borneTitre: "Electric vehicle charging", borneSous: "240 V charger installed by a master electrician",
      borneDesc: "A 240 V charging station connected to your panel by a master electrician, with a dedicated breaker and code-compliant wiring. Your vehicle charges fully overnight, right at home.",
      borneIncBorne: "Level 2 charging station", borneIncCablage: "Charger wiring and connection", borneIncDisj: "Dedicated breaker and code-compliant wiring", borneIncInst: "Installation and panel connection",
      borneIncEssais: "Setup and charging tests", borneIncExpl: "Walkthrough and handover", borneAlt: "Charging station", borneAltVe: "Electric vehicle charging",
      // Electrical work part
      travTitreN: "Additional electrical work", travTitre: "Your electrical work", travSous: "By a master electrician",
      travDesc: "Electrical work performed by our electricians in compliance with the Quebec Construction Code, Chapter V, Electricity. Materials, labour, testing and site cleanup included.",
      travInc: ["Materials and supplies", "Labour by licensed electricians", "Protection devices and grounding", "Testing and final inspection"], travRecap: "Electrical work",
      // About Raycom
      raycomSur: "About Raycom Électrique", raycomTitreSol: "Master electrician and solar specialist", raycomTitre: "Master electrician and energy specialist",
      raycomTexte: "Keeping the power on during outages, producing your own energy and charging your vehicle at home: that is what Raycom Électrique installs every week across Lanaudière, the Laurentians and Greater Montréal. A team of electricians based in Mascouche, equipment chosen for Québec conditions, and clean, code-compliant installations built to last.",
      tuileAns: "22 years", tuileExp: "of electrical experience", tuileAvis: "Google reviews", tuileDepuis: "master electrician since",
      altTesla: "Tesla Powerwall Certified Installer", altCmeq: "CMEQ, Québec master electricians' corporation", membreCmeqLic: "CMEQ member<br>RBQ licence 5590-9402-01", altInstallation: "Installation completed by Raycom",
      // Our projects
      realSur: "Our projects", realTesla: "Tesla energy, installed in your home", realSig: "Sigenergy energy, installed in your home", realSol: "Solar energy, installed in your home",
      regions: "Lanaudière · Laurentians · Greater Montréal", altRealisation: "Raycom project",
      // Technology
      techSur: "The proposed technology", techTitreSig: "Sigenergy: a smart all-in-one system", techTitreLux: "A reliable pair, designed for Québec winters",
      techSigStorSous: "Inverter and battery", techSigStor: (kw, kwh, aSol) => [`${kw} kW hybrid inverter · ${kwh} kWh LFP battery`, "Modular: stackable up to 72 kWh", "Outdoor rated, built for Québec winters", aSol ? "Connects directly to your solar panels" : "Already ready for solar panels"],
      techHubSous: "Smart panel", techHub: ["Instant transfer during an outage", "Whole-home backup, prioritized loads", "Smart energy distribution", "Real-time monitoring in the mySigen app"],
      techV2xTitre: "V2X charger", techV2xSous: "Bidirectional charging", techV2x: ["25 kW DC fast charging, NACS and CCS1", "V2H: your vehicle powers your home", "Part of the same Sigenergy system", "Managed in the mySigen app"],
      techLuxSous: "Hybrid inverter", techLux: ["120/240 V single-phase, automatic transfer", "Built-in solar inputs", "Remote monitoring in the Lux Power app", "Programmed by Raycom at commissioning"], techLuxHybride: "Hybrid",
      techVolSous: "LFP batteries", techVol: ["UL9540 certified LFP, code compliant", "Designed and assembled in Québec", "Self-heating, safe charging in extreme cold", "Expandable: add modules as needed"],
      // Solar part slide (roof card)
      ensoleillementMesure: "Sunlight measured on your roof", accesSolaire: "Solar access", irradianceMoy: "Average irradiance", kwhM2An: "kWh/m²/yr", kwhAn: "kWh/yr",
      prodMoyEstimee: "Estimated average production", altConception: "System design on your roof", altSolaire: "Solar PV system installed by Raycom", panneaux: "panels",
      // Backup and expandability
      evolTesla: "A 13.5 kWh Powerwall 3 expansion battery can be added later, without redoing the electrical installation.",
      evolFox: "Fox ESS batteries are stackable: modules can be added later without changing the inverter.",
      evolSig: "Battery modules stack up to 72 kWh: add capacity later without changing equipment.",
      evolLux: "Volthium batteries are modular: modules can be added at any time without changing the inverter.",
      renoJusqua: (m) => `Rénoclimat · up to ${m}`,
      renoTexte: (raccord) => `Rénoclimat is the Québec government's home energy renovation program. Fixed battery: up to $4,000 on the system purchase${raccord ? " · backup connection: up to $1,000 on the master electrician's fees, to be confirmed with Rénoclimat" : ""}. Principal residence built and lived in for at least 5 years. Estimate, subject to the program's official conditions.`,
      secSurSig: "Backup time and expandability", secSur: "Why this system", secTitre: "Built for outages, ready for solar", secCarte: "Outage backup",
      batterieSeule: (kwh) => `Battery only · ${kwh} kWh`, heures: (a, b) => `≈ ${a} to ${b} h`, selonCircuits: "depending on the circuits in use",
      secTransfertInst: "Instant transfer, nothing for you to do", secBascule: "Automatic switchover, nothing for you to do",
      secMaison: "Whole home powered, silently", secPrio: "Priority circuits powered, silently", secNiveau: (app) => `Real-time battery level in the ${app}`,
      besoinAutonomie: "Need more backup time?", pretSolaire: "Ready for solar", pretSolaireTitre: "Add panels later, with no additional equipment",
      pretSolaireTexte: (o) => `${o.tesla ? "The Powerwall 3 has a built-in 11.5 kW solar inverter." : "The installed inverter is a hybrid inverter: its solar inputs are already in place."} If you decide to produce your own energy one day, the panels connect directly to the equipment installed in this project. Solar qualifies for LogisVert, Hydro-Québec's residential energy efficiency program: $1,000 per installed kW, up to 40% of the eligible cost.${o.v2x ? " Your vehicle plugged into the V2X charger also becomes a backup power reserve for your home." : ""}`,
      // Subsidies
      subPrincipale: "Principal residence, home 5 years or older", subSecondaire: "Year-round secondary residence, or home less than 5 years old",
      subSaisonnier: "Seasonal cottage not habitable year-round", subAnnee: "Home or cottage habitable year-round", subAucune: "No subsidy · $0", lvSeulement: "LogisVert only",
      renoCarte: "Battery · Rénoclimat", jusquaCap: (m) => `Up to ${m}`,
      renoPuceBatt: (s) => `<strong style="${s}">Fixed battery: up to $4,000</strong><br>on the system purchase (batteries and inverters)`,
      renoPuceRacc: (s) => `<strong style="${s}">Backup connection: up to $1,000</strong><br>on the master electrician's fees, to be confirmed with Rénoclimat`,
      renoConditions: "Rénoclimat is the Québec government's home energy renovation program. Principal residence built and lived in for at least 5 years, habitable year-round, with heating able to maintain 21 °C. Secondary residences excluded. Apply within 12 months of the work. Eligibility and combining with LogisVert to be confirmed by the program.",
      mesurageCarte: "Net metering · Hydro-Québec", surplusCredits: "Surplus = credits",
      mesurageTexte: "Electricity you produce in excess in summer is fed into the grid and comes back to you as kWh credits, to be used later, in winter for example. Authorized grid connection included in our installation: Raycom prepares and submits the self-generation application.",
      subSur: (mois) => `Current Québec subsidies · ${mois}`, subTitre: "Your subsidies based on your home", subEstimees: "Estimated subsidies", jusqua: (m) => `up to ${m}`,
      lvCarte: "Solar · Hydro-Québec · LogisVert", lvParKw: "$1,000 / kW",
      lvTexte: "installed, under LogisVert, Hydro-Québec's residential energy efficiency program. Capped at 40% of the purchase and installation cost of the solar portion (panels, inverter, components, connection). Storage, roof repairs and engineering plans excluded. Home or cottage habitable year-round: no principal residence or age requirement.",
      lvKwFois: (kw) => `${kw} kW × $1,000`, lv40de: (m) => `40% of ${m}`, plafondApplique: "Cap applied: ", plafondKw: "$1,000 per installed kW", plafond40: "40% of eligible cost",
      lvVersee: "Paid to the owner only: the name on the invoice must match the proof of ownership. Apply within 9 months of installation, after Hydro-Québec's final connection approval.",
      subSituation: "Subsidies by situation", netTaxesIncl: "Net, taxes included", autreSubvention: "Other subsidy", autresInclus: (lib, m) => `${lib}: ${m} (included)`,
      subSources: "Estimates, subject to the programs' official conditions and the home's eligibility at the time of application. Sources: Rénoclimat, Participant's Guide, 2026 edition (MELCCFP) · LogisVert, Residential Participation Guide v1.10, September 15, 2026 (Hydro-Québec).",
      // Return
      plusDe40: "over 40 years", moinsDe2: "under 2 years", ansEntre: (a, b) => `${a} to ${b} years`, mesureeToit: "measured on your roof", zeroVirgule80: "0.80",
      avantTaxes: "before taxes", colSolaire: "Solar", colStockage: "Storage",
      tSousTotal: "Subtotal before taxes", tTaxes: "GST + QST (14.975%)", tTotal: "Total including taxes", tMoinsSub: "Less subsidy", tMoinsLv: "Less LogisVert", tCoutNet: "Net cost",
      projetCompletTI: "Complete project including taxes", coutNetPrincipale: "Net cost, principal residence 5+ years", coutNetApresLv: "Net cost after LogisVert",
      autonomieCarte: "Backup time during an outage", batterieSolaire: "Battery <strong>+ solar</strong>", plusieursJours: "several days",
      autoEstimee: "Estimated backup time", autoBatterie: (kwh) => `Battery · ${kwh} kWh usable`, autoBattSeule: "Battery only",
      autoBattSol: (kw) => `<strong>+ ${kw} kW of solar</strong>`,
      autoSolaireLigne: (p) => `Solar: ≈ ${p} kWh/day on an average outage day`,
      chargesCouvertes: (l) => `<strong>Loads covered:</strong> ${l}`, autoEtAutres: (n) => ` and ${n} more`,
      autoNote: "Battery fully charged when the outage starts; solar for an average day, a dark day produces less.",
      rendSur: "Return and savings · estimates", rendTitre: "An investment that works for you",
      kpiProd: "Annual production", kpiEco: "Monthly savings", parMois: (m) => `${m} / month`, inclTaxesAvant: (m) => `incl. taxes · ${m} before taxes`,
      kpiLv: "LogisVert subsidy", kpiLvSous: "estimate · final amount set by LogisVert", kpiNetRenta: "Net cost for payback", kpiNetSol: "Net solar cost",
      kpiNetPw: (base, lv) => `Powerwall inverter counted at $2,300 · ${base} incl. tax − ${lv}`, kpiNet: (base, lv) => `${base} incl. tax − ${lv}`, kpiRoi: "Payback period",
      ecoCumulees: "Estimated cumulative savings, taxes included",
      ecoCalcul: (prod, tarif, an, anT) => `${prod} kWh × $${tarif} = <strong style="color:#FFF;">${an} / year</strong> before taxes, or ${anT} including taxes (14.975%)`,
      legEco: "Cumulative savings", legNetRenta: "Net cost for payback", legNetSol: "Net solar cost", nAns: (n) => `${n} years`, calculLigne: "Net cost calculation, line by line",
      hypotheses: (o) => `<strong style="color:${o.c};">Assumptions:</strong> ${o.kw} kW system${o.google ? " (production measured on your roof, shading included" : ` (irradiance ${o.irr} kWh/m²/yr, solar access ${o.acces}%`}, 80% performance ratio) · Hydro-Québec rate $${o.tarif}/kWh · rate increase ${o.idx}%/yr · degradation ${o.deg}%/yr · taxes 14.975% · winter credit not deducted${o.pw ? " · Powerwall 3 inverter counted at $2,300 before taxes for payback, its installation excluded" : ""}. Non-binding estimates.`,
      // Steps
      etapesStd: [
        ["We confirm your project", ["Offer signed", "Initial deposit of $1,000", "File opened the same day"]],
        ["We handle Hydro-Québec", ["Complete file preparation", "Connection request submitted", "Follow-up until approval, nothing for you to do"]],
        ["We order", ["50% deposit after Hydro-Québec approval", "We order all the equipment", "We give you an installation date"]],
        ["We install", ["Equipment installation", "Commissioning and testing", "Final report sent to Hydro-Québec"]]
      ],
      etapesSimples: [
        ["We confirm your project", ["Offer signed", "Deposit at signing", "File opened the same day"]],
        ["We plan", ["Technical site survey if needed", "Equipment ordered", "We give you an installation date"]],
        ["We install", ["Installation by our electricians", "Code-compliant wiring and protection", "Clean job site"]],
        ["We commission", ["Testing and commissioning", "Walkthrough and handover", "Balance due on completion"]]
      ],
      etapesSur: "Project steps", etapesTitre: "A simple process, a single point of contact",
      // Warranties and terms
      gTesla: (b, gw) => `Tesla ${b("10-year")} limited warranty on Powerwall 3${gw ? " and Gateway 3" : ""}.`,
      gFox: (b) => `Fox ESS: ${b("12.5 years")} on the inverter and batteries, system registered by Raycom.`,
      gSig: (b) => `Sigenergy: ${b("10 years")} on the inverter and batteries.`, gLux: (b) => `Lux Power and Volthium: ${b("10 years")} on the inverter and batteries.`,
      gLongi: (b) => `LONGi panels: ${b("25-year")} product warranty and ${b("30-year")} linear power warranty (≥ 87.4%).`,
      gJa: (b) => `JA Solar panels: ${b("25-year")} product warranty and ${b("30-year")} linear power warranty.`,
      gWall: (b) => `Tesla Wall Connector: ${b("4 years")}.`, gFlo: (b) => `FLO charger: ${b("5 years")}.`, gWallbox: (b) => `Wallbox charger: ${b("3 years")}.`,
      gMo: (b) => `Raycom workmanship: ${b("2 years")}.`,
      paiementStd: (b) => `${b("$1,000")} deposit at signing · ${b("50%")} after Hydro-Québec approval and installation scheduling · ${b("balance")} once installation and testing are complete. Interac e-Transfer or cheque.`,
      paiementSimple: (b) => `Deposit at signing to reserve your date · ${b("balance")} once installation and testing are complete. Interac e-Transfer or cheque.`,
      suiviQuoi: (sol, bat) => sol && bat ? "production and battery" : sol ? "production" : "battery",
      apresStd: (b, quoi, app) => `Real-time monitoring of your ${quoi}${app ? ` in the ${b(app)}` : ""}. Local Raycom support, remote software updates and ${b("full assistance")} with your subsidy applications.`,
      apresSimple: "Local Raycom support: one number for any question. For a warranty claim, whatever the component, we open the file with the manufacturer and coordinate the repair.",
      finPromo: (s, n, m, taux, mois) => `<br><strong style="${s}">Promotional program: $0 payments and 0% interest for ${n} months</strong>, then ${m} per month at ${taux}% over ${mois} months for the complete project. Subject to credit approval.`,
      finExemple: (s, m, mois, taux) => `<br>Example for the complete project: <strong style="${s}">${m} per month</strong>${mois ? ` over ${mois} months` : ""}${taux ? ` at ${taux}%` : ""}. Subject to credit approval.`,
      carteGaranties: "Warranties", carteModalites: "Payment terms", carteApres: "After installation",
      financeitTitre: "Financing available through our partner Financeit", financeitTexte: "From $1,000 to $100,000, repayable over 12 to 240 months. No application fees, early repayment without penalty.",
      note: "Note:",
      conformite: (rbq, nV) => `Work compliant with the Quebec Construction Code, Chapter V, Electricity · ${rbq} · CMEQ member. Exclusions: any work not described ${nV > 2 ? `in parts 1 to ${nV}` : nV === 2 ? "in parts 1 and 2" : "in this proposal"} (structural or roof repairs, upgrade of the existing panel if required). Any extra is covered by a written change order approved before the work is done. Proposal valid for 30 days.`,
      garSur: "Warranties and terms", garTitre: "Clear terms, no surprises",
      // Summary and acceptance
      recapLv: (lv, reno, autres, net) => `LogisVert ${lv}${reno ? ` + Rénoclimat up to ${reno}, if eligible` : ""}${autres ? ` + ${autres}` : ""} · estimated net cost ${net}`,
      renoEstime: "Estimated Rénoclimat", jusquaMoins: (m) => `up to − ${m}`, renoSiAdmissible: (net) => `if eligible, to be confirmed by the program · estimated net cost ${net}`,
      finCarte: "Financeit financing", finPromoCourt: (n) => `$0 for ${n} months`, finPuis: (m) => `then ${m} per month, `, surApprobation: "subject to credit approval",
      recapSur: "Summary and acceptance", recapTitre: "Your system at a glance", sousTotalAvant: "Subtotal before taxes", tpsTvq: "GST 5% + QST 9.975%", projetCompletTICap: "COMPLETE PROJECT · TAXES INCLUDED",
      siege: "Head office", bureaux: "Offices and warehouse", texto: "text",
      enSignant: (num, m) => `By signing, you accept proposal No. ${num} in the amount of ${m}, taxes included.`,
      acceptePar: (nom) => `Accepted by${nom ? ` ${nom}` : ""} (signature)`, date: "Date", membreCmeq: "CMEQ member"
    }
  };
  let X = TXT.fr;
  /** Langue de la proposition : celle choisie dans la soumission (state.client.langue_proposition), sinon la langue de la
   *  fiche client si elle en a une, sinon le français. */
  const langueDe = (state) => {
    const c = (state && state.client) || {};
    const v = String(c.langue_proposition || c.langue || "").trim().toLowerCase();
    return /^(en|ang)/.test(v) ? "en" : "fr";
  };
  const appliquerLangue = (state) => { const l = langueDe(state); X = TXT[l]; LOC = X.locale; return l; };

  // ─── Actifs (assets/proposition : photos réelles d'installations et de produits, logos) ───
  const D = "assets/proposition/";
  const A = {
    logo: D + "logo-raycom.png", cmeq: D + "logo-cmeq.png", tesla: D + "logo-tesla-certified.png", financeit: D + "logo-financeit.png",
    maisonNuit: D + "maison-solaire-crepuscule.jpg", maisonJour: D + "maison-solaire-jour.jpg", solaire: D + "solaire-installation.jpg",
    teslaGarage: D + "tesla-garage.jpg", teslaTerrasse: D + "tesla-terrasse.jpg", teslaRecharge: D + "tesla-recharge.jpg",
    teslaSolaire: D + "tesla-solaire-facade.jpg", teslaMur: D + "tesla-powerwall-mur.jpg", teslaFacade: D + "tesla-powerwall-facade.jpg",
    teslaAerien: D + "tesla-maison-aerienne.jpg", teslaNuit: D + "tesla-maison-nuit.jpg",
    raycomPw: D + "raycom-installation-powerwall.jpg", fox: D + "fox-ess-aio.jpg",
    sigStor: D + "sigenergy-sigenstor.jpg", sigHub: D + "sigenergy-loadhub.jpg", sigV2x: D + "sigenergy-v2x.jpg", recharge: D + "recharge-vehicule.jpg"
  };
  // Photos déjà utilisées dans la proposition en cours (JF, 6 nov. 2026 : « deux photos pareilles »). Remis à zéro à chaque génération.
  let VUS = new Set();
  const marquer = (src) => { if (src) VUS.add(src); return src; };
  const prendre = (cands, repli) => { for (const s of cands) if (s && !VUS.has(s)) { VUS.add(s); return s; } return marquer(repli); };
  // JF, 8 nov. 2026 (« c'est tout le temps les mêmes ») : l'ordre des photos candidates tourne d'une proposition à l'autre,
  // selon une graine stable par soumission (même proposition = mêmes photos à chaque génération, brouillon comme finale).
  let GRAINE = 0;
  const graineDe = (t) => { let h = 2166136261; for (const ch of String(t || "")) { h ^= ch.codePointAt(0); h = Math.imul(h, 16777619) >>> 0; } return h; };
  const tourner = (arr, k) => { const g = GRAINE >>> (((k || 0) * 5) % 28); return arr.map((_, i) => arr[(i + g) % arr.length]); };
  const RAYCOM_INST = [D + "raycom-installation-1.jpg", D + "raycom-installation-2.jpg", D + "raycom-installation-3.jpg"];
  const RAYCOM = { nom: "Raycom Électrique inc.", rbq: "RBQ 5590-9402-01", tel: "450 474-8470", texto: "438 801-6401", courriel: "info@raycomelectrique.com", web: "www.raycomelectrique.com", siege: "2222 Davignac, Mascouche QC J7K 0K8", entrepot: "3321 av. de la Gare #112, Mascouche QC J7K 0X7" };

  // ─── Charte (norme) ───
  const C = { navy: "#0C2340", blue: "#1568C8", sky: "#2FA3EE", s1: "#7FB8F0", s2: "#9FB4CC", s3: "#C7D6E8", light: "#F0F5FB", g1: "#37455A", g2: "#6B7A8C", yellow: "#FFC93C", green: "#3ECF8E", trait: "#EDF2F8", bord: "#DEE7F2" };
  const T = "font-family:'Barlow Semi Condensed','Barlow',Arial,sans-serif;font-weight:800;";
  const LIS_CLAIR = `<div style="position:absolute;top:0;left:0;right:0;height:12px;background:linear-gradient(90deg,${C.navy} 60%,${C.blue});"></div>`;
  const LIS_VERT = `<div style="position:absolute;top:0;left:0;right:0;height:12px;background:linear-gradient(90deg,${C.navy} 50%,${C.blue} 78%,${C.green});"></div>`;
  const LIS_MARINE_HAUT = `<div style="position:absolute;top:0;left:0;right:0;height:12px;background:linear-gradient(90deg,${C.sky},${C.blue});"></div>`;
  const LIS_MARINE_BAS = `<div style="position:absolute;bottom:0;left:0;right:0;height:12px;background:linear-gradient(90deg,${C.sky},${C.blue});"></div>`;
  const CARTE_MARINE = "background:rgba(255,255,255,.06);border:1px solid rgba(127,184,240,.3);border-radius:14px;";

  const surtitre = (t, sombre) => `<div style="font-size:24px;font-weight:700;letter-spacing:5px;color:${sombre ? C.sky : C.blue};text-transform:uppercase;">${t}</div>`;
  const grandTitre = (t, sombre, taille = 60, mt = 12) => `<div style="${T}font-size:${taille}px;color:${sombre ? "#FFF" : C.navy};line-height:1.1;margin-top:${mt}px;">${t}</div>`;
  const puce = (texte, couleur = C.navy) => `<div style="display:flex;gap:14px;align-items:flex-start;line-height:1.4;"><span style="flex-shrink:0;width:9px;height:9px;border-radius:50%;background:${couleur};margin-top:13px;"></span><span>${texte}</span></div>`;
  const puce2 = (titre, sous) => `<div style="display:flex;gap:14px;align-items:flex-start;"><span style="flex-shrink:0;width:9px;height:9px;border-radius:50%;background:${C.navy};margin-top:12px;"></span><div><div style="font-weight:700;color:${C.navy};font-size:24px;line-height:1.25;">${titre}</div><div style="font-size:22px;color:${C.g2};line-height:1.3;margin-top:1px;">${sous}</div></div></div>`;
  const crochet = (texte, clair) => `<div style="display:flex;gap:10px;align-items:flex-start;font-size:24px;color:${clair ? "#D9F5E8" : C.s3};line-height:1.45;"><span style="color:${C.green};font-weight:700;">✓</span><span>${texte}</span></div>`;
  const photoPanneau = (src, alt, fondu, fit = "cover", fond = "") => `<div style="position:relative;${fond ? `background:${fond};` : ""}"><img src="${esc(src)}" alt="${esc(alt)}" style="position:absolute;inset:${fit === "contain" ? "6%" : "0"};width:${fit === "contain" ? "88%" : "100%"};height:${fit === "contain" ? "88%" : "100%"};object-fit:${fit};">${fondu ? `<div style="position:absolute;inset:0;background:linear-gradient(${fondu},#FFF 0%,rgba(255,255,255,0) 12%);pointer-events:none;"></div>` : ""}</div>`;
  const diapo = (label, fond, inner, sombre) => `<div class="slide-wrap"><section class="slide" data-label="${esc(label)}" style="position:relative;width:1920px;height:1080px;overflow:hidden;box-sizing:border-box;background:${fond};color:${sombre ? "#FFF" : C.navy};font-family:'Barlow',Arial,sans-serif;">${inner}</section></div>`;

  // ─── Lecture du devis ───
  const MARQUES = [["tesla", /Tesla|Powerwall/i], ["fox", /Fox ESS/i], ["sigenergy", /Sigenergy/i], ["lux", /Lux Power|Volthium/i]];
  const marqueDeNom = (nom) => (MARQUES.find(([, re]) => re.test(nom || "")) || [null])[0];
  const estMO = (l) => /^(Installation|Raccordement|Main-d|Branchement|Pose|Mise en service|Gestion|Levage|Manutention|Programmation|Configuration)/i.test(l.nom || "") || !!(l.article && l.article.famille === "batterie_mo");
  const estOnduleur = (l) => /^Onduleur/i.test(l.nom || "");
  const estInstOnduleur = (l) => /^Installation onduleur/i.test(l.nom || "");
  const kwDe = (nom) => { const n = nom || ""; const m = n.match(/(\d+(?:[.,]\d+)?)\s*kW\b/) || n.match(/\b(\d+(?:[.,]\d+)?)K\b/); return m ? parseFloat(m[1].replace(",", ".")) : null; };
  const marquePanneau = (nom) => /LONGi/i.test(nom || "") ? "LONGi" : /JA Solar/i.test(nom || "") ? "JA Solar" : "";
  const marqueBorne = (nom) => /Tesla|Wall Connector/i.test(nom || "") ? "Tesla Wall Connector" : /FLO/.test(nom || "") ? "FLO" : /Wallbox/i.test(nom || "") ? "Wallbox" : /Sigenergy/i.test(nom || "") ? "Sigenergy" : "";

  /** Répartit les lignes du devis en volets (stockage, solaire, borne, travaux), puis en blocs commerciaux. */
  function construireVolets(calc) {
    const L = (calc.lignes || []).filter(l => l.groupe !== "info" && Math.abs(Number(l.montant) || 0) > 0.004);
    const aBatt = L.some(l => l.article && l.article.est_batterie && l.qty > 0);
    const aSol = (calc.kw || 0) > 0;
    const marque = aBatt ? (marqueDeNom((L.find(l => l.article && l.article.est_batterie) || {}).nom) || "autre") : null;
    const par = { stockage: [], solaire: [], borne: [], travaux: [] };
    for (const l of L) {
      const g = l.groupe;
      let v = "travaux";
      if (g === "solaire") v = aSol ? "solaire" : "travaux";
      else if (g === "stockage") v = aBatt ? ((aSol && (estOnduleur(l) || estInstOnduleur(l))) ? "solaire" : "stockage") : ((aSol && (estOnduleur(l) || estInstOnduleur(l))) ? "solaire" : "travaux");
      else if (g === "entree") v = aBatt ? "stockage" : "travaux";
      else if (g === "borne") v = (marque === "sigenergy" && /Sigenergy/i.test(l.nom)) ? "stockage" : "borne";
      par[v].push(l);
    }
    const kwhDe = (lignes) => r2(lignes.filter(l => l.article && l.article.est_batterie && l.article.kwh).reduce((s, l) => s + l.qty * l.article.kwh, 0));
    const blocs = (id, lignes) => {
      const ondDansVolet = lignes.some(estOnduleur);
      const kwh = kwhDe(lignes);
      const defs = [];
      const ajoute = (cle, label, ordre, l) => { let b = defs.find(x => x.cle === cle); if (!b) { b = { cle, label, ordre, lignes: [] }; defs.push(b); } b.lignes.push(l); };
      for (const l of lignes) {
        const n = l.nom || "";
        if (l.montant < 0) { ajoute("rabais-" + (l.qbo_id || n), X.bRabais(n), 90, l); continue; }
        if (id === "stockage") {
          if (/charges critiques|section de secours/i.test(n)) ajoute("crit", X.bCrit, 40, l);
          else if (/embase de compteur combinée/i.test(n)) ajoute("complet", X.bComplet, 40, l);
          else if (l.groupe === "entree") ajoute("entree", X.bEntree, 45, l);
          else if (estMO(l)) ajoute("inst", X.bInst, 80, l);
          else if (marque === "tesla" && (/expansion/i.test(n))) ajoute("exp", X.bExpTesla, 15, l);
          else if (marque === "tesla" && /Gateway|Remote Meter|Compteur distant/i.test(n)) ajoute("gw", X.bGwTesla, 20, l);
          else if (marque === "tesla" && /Powerwall/i.test(n)) ajoute("sys", ondDansVolet ? X.bSysTeslaOnd : X.bSysTesla(fmtNum(kwh)), 10, l);
          else if (marque === "fox" && /Hub G2|Module Fox/i.test(n)) ajoute("gw", X.bGwFox, 20, l);
          else if (marque === "fox" && /Fox/i.test(n)) ajoute("sys", ondDansVolet ? X.bSysFoxOnd : X.bSysFox(fmtNum(kwh)), 10, l);
          else if (marque === "sigenergy" && /LoadHub/i.test(n)) ajoute("gw", X.bGwSig, 20, l);
          else if (marque === "sigenergy" && l.groupe === "borne") ajoute("v2x", X.bV2x, 30, l);
          else if (marque === "sigenergy" && /Sigenergy|Manteau|LTE/i.test(n)) ajoute("sys", ondDansVolet ? X.bSysSigOnd(fmtNum(kwh)) : X.bSysSig(fmtNum(kwh)), 10, l);
          else if (marque === "lux" && /Lux Power/i.test(n)) ajoute("ond", ondDansVolet ? X.bOndLuxOnd : X.bOndLux, 10, l);
          else if (marque === "lux" && /Volthium/i.test(n)) ajoute("sys", X.bSysLux(fmtNum(kwh)), 12, l);
          else if (/Câblage DC|Sectionneur DC|Busbar/i.test(n)) ajoute("infra", X.bInfra, 50, l);
          else ajoute("acc", X.bAcc, 60, l);
        } else if (id === "solaire") {
          if (/BOM|structure|Arrêt rapide|RSD|ProJoy|\bMCI\b|Optimiseur|Tigo|rail|Câblage|Sectionneur/i.test(n)) ajoute("infra", X.bInfra, 20, l);
          else if (estMO(l)) ajoute("inst", X.bInst, 30, l);
          else ajoute("eq", X.bEqPv, 10, l);
        } else if (id === "borne") {
          const fam = l.article && l.article.famille;
          if (fam === "travaux" || estMO(l) || /Câblage/i.test(n)) ajoute("inst", X.bInstBorne, 20, l);
          else { const mb = marqueBorne(n); ajoute("eq", `${/commerciale/i.test(n) ? X.bBorneCom : X.bBorneN2}${mb ? ` · ${mb}` : ""}`, 10, l); }
        } else {
          if (/Levage|Manutention|Déplacement|Hébergement|Travail extérieur|Travail en grenier|en hauteur|échafaudage|Démolition|Service urgence/i.test(n)) ajoute("log", X.bLog, 30, l);
          else if (/panneau|Entrée|embase|sectionneur|disjoncteur|mât|compteur|Mise à niveau|Remplacement/i.test(n)) ajoute("elec", X.bEntree, 10, l);
          else if (estMO(l) || (l.article && l.article.famille === "travaux")) ajoute("inst", X.bInstTrav, 20, l);
          else ajoute("mat", X.bMat, 25, l);
        }
      }
      return defs.sort((a, b) => a.ordre - b.ordre).map(b => ({ cle: b.cle, label: b.label, montant: somme(b.lignes), lignes: b.lignes }));
    };
    // Installation d'une borne intégrée au système (V2X Sigenergy) : sans autre borne au devis, elle rejoint le volet stockage
    if (par.borne.length && par.stockage.length && par.stockage.some(l => l.groupe === "borne") && par.borne.every(l => estMO(l) || (l.article && l.article.famille === "travaux") || /Câblage/i.test(l.nom || ""))) { par.stockage.push(...par.borne); par.borne = []; }
    const ordre = ["stockage", "solaire", "borne", "travaux"];
    const volets = ordre.filter(id => par[id].length).map(id => ({ id, lignes: par[id], ht: somme(par[id]), kwh: kwhDe(par[id]), blocs: blocs(id, par[id]) }));
    const plusieurs = volets.length > 1;
    volets.forEach((v, i) => { v.numero = plusieurs ? String(i + 1).padStart(2, "0") : null; });
    return { volets, aBatt, aSol, marque, lignes: L };
  }

  /** Gabarit de référence selon le devis (norme : tableau des gabarits). */
  function gabaritDe(vs, calc) {
    const L = vs.lignes;
    const v2x = L.some(l => /V2X|bidirection/i.test(l.nom || ""));
    if (vs.aBatt) {
      if (vs.marque === "tesla") return vs.aSol ? "tesla_solaire" : "powerwall";
      if (vs.marque === "fox") return vs.aSol ? "fox_solaire" : "fox";
      if (vs.marque === "lux") return vs.aSol ? "lux_solaire" : "lux";
      if (vs.marque === "sigenergy") return (vs.aSol ? "sigenergy_solaire" : "sigenergy") + (v2x ? "_v2x" : "");
      return vs.aSol ? "stockage_solaire" : "stockage";
    }
    if (vs.aSol) return "solaire";
    if (L.length && L.every(l => l.groupe === "borne")) return "borne";
    if (vs.volets.some(v => v.id === "borne") && vs.volets.length === 1) return "borne";
    return "travaux";
  }

  /** Modèle complet du deck : volets, subventions (norme), rendement, financement. */
  function modele(state, calc) {
    appliquerLangue(state);
    const sol = (state && state.solaire) || {}, sub = (state && state.subventions) || {};
    const vs = construireVolets(calc);
    const gabarit = gabaritDe(vs, calc);
    const vSol = vs.volets.find(v => v.id === "solaire") || null, vSto = vs.volets.find(v => v.id === "stockage") || null;
    const L = vs.lignes;
    const tesla = L.some(l => /Powerwall/i.test(l.nom || ""));
    const ondSol = vSol ? vSol.lignes.find(estOnduleur) : null;
    const marqueOnd = ondSol ? marqueDeNom(ondSol.nom) : (vs.aSol && vs.marque && vs.marque !== "autre" ? vs.marque : null);
    const panneau = L.find(l => l.article && l.article.est_panneau) || null;
    const loadhub = L.some(l => /LoadHub/i.test(l.nom || ""));
    const v2x = L.some(l => /V2X|bidirection/i.test(l.nom || ""));
    const complet = L.some(l => /embase de compteur combinée|maison complète/i.test(l.nom || "")) || loadhub;
    const partiel = !complet && L.some(l => /charges critiques|backup partiel|section de secours/i.test(l.nom || ""));
    const gw = L.some(l => /Gateway/i.test(l.nom || ""));
    const nbPw = L.filter(l => /^Batterie Tesla Powerwall 3/i.test(l.nom || "")).reduce((s, l) => s + l.qty, 0);
    const expansion = L.some(l => /^Batterie d'expansion/i.test(l.nom || ""));
    const nbModules = L.filter(l => l.article && l.article.est_batterie).reduce((s, l) => s + l.qty, 0);
    const ondStock = L.find(l => estOnduleur(l) && marqueDeNom(l.nom) === vs.marque);

    // LogisVert (norme) : min(kW × 1 000 $ ; 40 % du coût admissible avant taxes = volet solaire du devis, y compris
    // l'onduleur hybride et son installation tels que ventilés au devis ; stockage exclu). 40 kW au plus.
    const solHT = vSol ? vSol.ht : 0;
    const lvKw = Math.min(calc.kw || 0, 40) * 1000, lv40 = r2(solHT * 0.4);
    const logisvert = (vs.aSol && sub.logisvert_admissible !== false) ? r2(Math.min(lvKw, lv40)) : 0;
    const plafondKw = lvKw <= lv40;
    const reno = Number(calc.renoclimat) || 0, autres = Number(calc.autres) || 0;
    const subTot = r2(logisvert + reno + autres);

    // Rendement (norme) : tarif 0,11142 $/kWh, indexation 4 %/an, dégradation 0,4 %/an, économies avant et après taxes.
    // Avec un Powerwall 3, l'onduleur est compté à 2 300 $ avant taxes et son installation est exclue.
    const prod = Number(calc.production) || 0;
    const tarif = Number(sol.tarif_kwh) || 0.11142;
    const idx = (sol.indexation_pct == null || sol.indexation_pct === "" ? 4 : Number(sol.indexation_pct)) / 100;
    const deg = (sol.degradation_pct == null || sol.degradation_pct === "" ? 0.4 : Number(sol.degradation_pct)) / 100;
    const cumulHT = (n) => { let s = 0; for (let k = 1; k <= n; k++) s += prod * Math.pow(1 - deg, k - 1) * tarif * Math.pow(1 + idx, k - 1); return s; };
    let baseHT = solHT, onduleurPw = false;
    if (vSol) {
      const ondPw = vSol.lignes.filter(l => /^Onduleur Tesla/i.test(l.nom || "")), instPw = vSol.lignes.filter(l => /^Installation onduleur Tesla/i.test(l.nom || ""));
      if (ondPw.length) { onduleurPw = true; baseHT = r2(solHT - somme(ondPw) - somme(instPw) + 2300); }
    }
    const baseTTC = r2(baseHT + taxesDe(baseHT));
    const netRoi = r2(baseTTC - logisvert);
    const roi = (mult) => { if (prod <= 0) return null; for (let n = 1; n <= 40; n++) if (cumulHT(n) * mult >= netRoi) return n; return null; };
    const ecoAn1 = Math.round(prod * tarif), ecoAn1T = Math.round(ecoAn1 * (1 + TAUX_TAXES));
    const rendement = vs.aSol && prod > 0 ? {
      prod, tarif, idx, deg, ecoAn1, ecoAn1T, moisHT: Math.round(ecoAn1 / 12), moisT: Math.round(ecoAn1T / 12),
      baseHT, baseTTC, netRoi, onduleurPw, roiT: roi(1 + TAUX_TAXES), roiH: roi(1),
      barres: [5, 10, 15, 20, 25].map(an => ({ an, ht: Math.round(cumulHT(an)), ttc: Math.round(cumulHT(an) * (1 + TAUX_TAXES)) }))
    } : null;

    return {
      gabarit, volets: vs.volets, vSol, vSto, aBatt: vs.aBatt, aSol: vs.aSol, marque: vs.marque, tesla, marqueOnd, ondSol, ondStock, panneau,
      loadhub, v2x, complet, partiel, gw, nbPw, expansion, nbModules, kwh: calc.kwh || 0, kw: calc.kw || 0, autonomie: calc.autonomie || null,
      ht: calc.ht, taxes: calc.taxes, ttc: calc.ttc, sommeVolets: somme(vs.volets.map(v => ({ montant: v.ht }))),
      subv: { logisvert, lvKw, lv40, plafondKw, solHT, reno, renoBatterie: Number(calc.renoBatterie) || 0, renoRaccord: Number(calc.renoRaccord) || 0, autres, total: subTot },
      rendement
    };
  }

  // ─── Textes selon le gabarit ───
  const NOM_MARQUE = { tesla: "Tesla Powerwall 3", fox: "Fox ESS", sigenergy: "Sigenergy", lux: "Lux Power et Volthium" };
  function titreAccrocheur(M) {
    if (M.aBatt && M.aSol) return X.titreStockageSolaire;
    if (M.aBatt && M.marque === "sigenergy" && M.v2x) return X.titreV2x;
    if (M.aBatt) return X.titreBatterie;
    if (M.aSol) return X.titreSolaire;
    if (M.gabarit === "borne") return X.titreBorne;
    return X.titreTravaux;
  }
  function phraseSecours(M) {
    return M.complet ? X.secComplet : M.partiel ? X.secPartiel : X.secBase;
  }
  function numeroVolet(M, id) { const v = M.volets.find(x => x.id === id); return v && v.numero ? Number(v.numero) : null; }

  function contenuVolet(M, v, ctx) {
    const sec = phraseSecours(M);
    const nVolSol = numeroVolet(M, "solaire");
    const refSol = nVolSol ? X.refVolet(nVolSol) : "";
    if (v.id === "stockage") {
      const kwh = fmtNum(v.kwh);
      if (M.marque === "tesla") {
        const n = M.nbPw || 1;
        const sujet = X.teslaSujet(n, kwh);
        const inc = [puce2(`${n > 1 ? n + " " : ""}Powerwall 3 · ${kwh} kWh`, X.teslaIncPw[0])];
        if (M.gw) inc.push(puce2(...X.teslaIncGw));
        inc.push(M.complet ? puce2(...X.teslaIncComplet) : M.partiel ? puce2(...X.teslaIncPartiel) : puce2(...(() => { // JF, 8 nov. 2026 : 6 emplacements libres avec 1 Powerwall = 6 circuits 120 V ou 3 circuits 240 V (40 A max.)
          const f = window.ParcoursRE && window.ParcoursRE.capaciteSecoursGateway;
          const cap = typeof f === "function" ? f(n, {}) : { circuits_120_max: Math.max(0, 8 - 2 * n), circuits_240_max: Math.floor(Math.max(0, 8 - 2 * n) / 2) };
          return X.teslaIncBase(cap.circuits_120_max, cap.circuits_240_max);
        })()));
        if (M.expansion) inc.push(puce2(...X.teslaIncExp));
        inc.push(puce2(...X.teslaIncPermis));
        inc.push(puce2(...X.teslaIncMes));
        return {
          titre: X.teslaTitre, sous: X.teslaSous,
          desc: X.teslaDesc({ sujet, sec, aSol: M.aSol, refSol }),
          inclusions: inc.slice(0, 6), riche: true, photo: { src: tourner(M.aSol ? [A.teslaSolaire, A.teslaFacade, A.teslaTerrasse, A.teslaGarage] : [A.teslaFacade, A.teslaTerrasse, A.teslaGarage, A.teslaRecharge], 1).find(x => !VUS.has(x)) || A.teslaFacade, alt: X.teslaAlt }, recap: `Tesla Powerwall 3${M.gw ? " + Gateway 3" : ""}`
        };
      }
      if (M.marque === "fox") {
        const hub = M.volets.some(x => x.lignes.some(l => /Hub G2/i.test(l.nom || "")));
        return {
          titre: X.foxTitre, sous: X.foxSous(kwh),
          desc: X.foxDesc({ kwh, aSol: M.aSol, refSol, complet: M.complet, sec }),
          inclusions: [X.foxIncModules(M.nbModules, kwh), M.complet ? X.transfertComplet : X.transfertPrio, hub ? X.foxIncHub : X.foxIncRacc, X.foxIncSuivi, X.foxIncEmpil, X.essaisMes].map(t => puce(t)),
          photo: { src: A.fox, alt: X.foxAlt, fit: "contain", fond: "#FFF" }, recap: X.foxRecap
        };
      }
      if (M.marque === "sigenergy") {
        const kwOnd = M.ondStock ? (kwDe(M.ondStock.nom) || 11.5) : 11.5;
        const seul = !v.numero;
        return {
          titre: seul ? X.sigTitreSeul : X.sigTitre, sous: [`SigenStor ${kwh} kWh`, M.loadhub ? "LoadHub 200 A" : "", M.v2x ? X.sigSousV2x : ""].filter(Boolean).join(" + "),
          desc: X.sigDesc({ aSol: M.aSol, kwh, refSol, kwOnd: fmtNum(kwOnd), loadhub: M.loadhub, v2x: M.v2x, sec }),
          inclusions: [M.loadhub ? X.sigIncBackupComplet : X.sigIncBackupPrio, M.loadhub ? X.sigIncDistrib : X.sigIncRacc, X.sigIncEmpil, M.v2x ? X.sigIncV2x : X.sigIncHiver, X.permisHQ, X.sigIncApp].map(t => puce(t)),
          photo: { src: A.sigStor, alt: X.sigAlt }, recap: seul ? X.sigRecapSeul : X.sigRecap
        };
      }
      if (M.marque === "lux") {
        const kwOnd = M.ondStock ? kwDe(M.ondStock.nom) : null;
        return {
          titre: X.luxTitre, sous: X.luxSous(kwh),
          desc: X.luxDesc({ aSol: M.aSol, kwh, refSol, kwOnd: kwOnd ? fmtNum(kwOnd) : "", complet: M.complet, sec }),
          inclusions: [M.aSol ? X.luxIncBatt : X.luxIncOnd(kwOnd ? fmtNum(kwOnd) : ""), X.luxIncUl(kwh), X.transfertPrio, X.permisHQ, X.luxIncConfig, X.luxIncTests].map(t => puce(t)),
          photo: null, recap: X.luxRecap
        };
      }
      return { titre: X.stoTitre, sous: `${kwh} kWh`, desc: X.stoDesc(kwh), inclusions: [X.stoIncTransfert, X.stoIncRacc, X.permisHQ, X.essaisMes].map(t => puce(t)), photo: null, recap: X.stoTitre };
    }
    if (v.id === "solaire") {
      const pan = M.panneau; const mp = pan ? marquePanneau(pan.nom) : ""; const w = pan && pan.article && pan.article.watts;
      const bif = pan && /bifacial/i.test(pan.nom || "");
      const kwO = M.ondSol ? kwDe(M.ondSol.nom) : null;
      const ondTxt = M.marqueOnd === "tesla" ? X.ondTesla
        : M.marqueOnd === "fox" ? X.ondHybride("Fox ESS", kwO ? fmtNum(kwO) : "")
        : M.marqueOnd === "sigenergy" ? X.ondHybride("Sigenergy", kwO ? fmtNum(kwO) : "")
        : M.marqueOnd === "lux" ? X.ondHybride("Lux Power", kwO ? fmtNum(kwO) : "") : "";
      const rsd = v.lignes.some(l => /Arrêt rapide|RSD|\bMCI\b|TS4-A-2F/i.test(l.nom || ""));
      const opt = v.lignes.some(l => /Optimiseur/i.test(l.nom || ""));
      const inc = [X.solIncStructure, rsd ? X.solIncRsd : opt ? X.solIncOpt : X.solIncDc, X.solIncDcProt, M.marqueOnd && M.marqueOnd !== "tesla" && M.ondSol ? X.solIncOnd(NOM_MARQUE[M.marqueOnd].replace(" et Volthium", ""), kwO ? fmtNum(kwO) : "") : X.solIncAutoprod, M.marqueOnd && M.marqueOnd !== "tesla" && M.ondSol ? X.solIncAutoprod : X.solIncTests, X.solIncMes];
      const uniq = inc.filter((t, i) => inc.indexOf(t) === i);
      return {
        titre: X.solTitre(fmtNum(M.kw)), sous: X.solSous(ctx.panneaux, fmtNum(M.kw)),
        // w vient de la fiche d'article (catalogue, champ watts) : échappé comme toute donnée insérée dans desc (HTML de gabarit)
        desc: X.solDesc({ n: esc(ctx.panneaux), mp: esc(mp), w: w == null || w === "" ? w : esc(w), bif, ondTxt }),
        inclusions: uniq.slice(0, 6).map(t => puce(t)), recap: X.solTitre(fmtNum(M.kw)), solaire: true
      };
    }
    if (v.id === "borne") {
      const b = v.lignes.find(l => !estMO(l) && !(l.article && l.article.famille === "travaux") && !/Câblage/i.test(l.nom || ""));
      const img = b && window.ParcoursRE && window.ParcoursRE.imageBorne ? window.ParcoursRE.imageBorne(b.article && b.article.nom ? b.article : { nom: b.nom }) : null;
      return {
        titre: X.borneTitre, sous: X.borneSous,
        desc: X.borneDesc,
        inclusions: [b ? X.borneIncBorne : X.borneIncCablage, X.borneIncDisj, X.borneIncInst, X.borneIncEssais, X.borneIncExpl].map(t => puce(t)),
        photo: img ? { src: img, alt: X.borneAlt, fit: "contain", fond: C.light } : { src: A.recharge, alt: X.borneAltVe }, recap: X.borneTitre
      };
    }
    return {
      titre: v.numero ? X.travTitreN : X.travTitre, sous: X.travSous,
      desc: X.travDesc,
      inclusions: X.travInc.map(t => puce(t)), photo: null, recap: v.numero ? X.travTitreN : X.travRecap
    };
  }

  // ─── Diapos ───
  function diapoTitre(M, ctx) {
    const fond = M.tesla ? prendre(tourner([A.teslaNuit, A.teslaAerien]), A.teslaNuit) // toujours une des deux maisons Powerwall de soir
      : marquer(M.marque === "sigenergy" && M.v2x && !M.aSol ? A.recharge : A.maisonNuit);
    return diapo("Titre", C.navy, `<img src="${fond}" alt="" style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;"><div style="position:absolute;inset:0;background:linear-gradient(100deg,rgba(12,35,64,.94) 0%,rgba(12,35,64,.78) 45%,rgba(12,35,64,.25) 100%);"></div>${LIS_MARINE_BAS}
      <div style="position:relative;height:100%;display:flex;flex-direction:column;justify-content:space-between;padding:80px 100px;box-sizing:border-box;">
        <div style="align-self:flex-start;background:#FFF;border-radius:12px;padding:22px 34px;box-shadow:0 6px 30px rgba(0,0,0,.35);"><img src="${A.logo}" alt="Raycom Électrique inc." style="width:300px;display:block;"></div>
        <div><div style="font-size:26px;font-weight:700;letter-spacing:6px;color:${C.sky};text-transform:uppercase;">${X.surProposition}</div>
          <div style="${T}font-size:92px;line-height:1.05;margin-top:20px;max-width:1150px;color:#FFF;">${esc(titreAccrocheur(M))}</div>
          <div style="font-size:32px;color:${C.s3};margin-top:26px;">${ctx.nom ? `${X.preparePour} <strong style="color:#FFF;">${esc(ctx.nom)}</strong>${ctx.adresse ? ` · ${esc(ctx.adresse)}` : ""}` : (ctx.adresse ? esc(ctx.adresse) : X.prepareParRaycom)}</div></div>
        <div style="font-size:24px;color:${C.s2};">${X.propositionNo(esc(ctx.num))} · <span data-date-proposition>${esc(ctx.date)}</span> · ${X.valide30} · ${RAYCOM.web}</div>
      </div>`, true);
  }

  function diapoRaycom(M) {
    const photo = M.tesla ? prendre(tourner([A.raycomPw, ...RAYCOM_INST], 2), A.raycomPw) : M.marque === "sigenergy" ? prendre([A.sigStor, A.sigHub, A.solaire], A.sigStor) : M.gabarit === "borne" ? prendre([A.recharge, A.teslaRecharge], A.recharge) : prendre([A.solaire, A.maisonJour], A.solaire);
    const tuile = (val, coul, txt) => `<div style="flex:1;background:${C.navy};border-radius:12px;padding:24px 28px;color:#FFF;text-align:center;"><div style="${T}font-size:52px;color:${coul};">${val}</div><div style="font-size:24px;color:${C.s3};margin-top:4px;">${txt}</div></div>`;
    return diapo("Qui est Raycom", "#FFF", `${LIS_CLAIR}<div style="display:grid;grid-template-columns:1fr 740px;height:100%;box-sizing:border-box;">
      <div style="padding:90px 90px 70px;display:flex;flex-direction:column;">
        ${surtitre(X.raycomSur)}
        ${grandTitre(M.aSol ? X.raycomTitreSol : X.raycomTitre, false, 60, 16)}
        <div style="font-size:27px;color:${C.g1};line-height:1.6;margin-top:24px;max-width:860px;">${X.raycomTexte}</div>
        <div style="display:flex;gap:20px;margin-top:40px;">${tuile(X.tuileAns, C.sky, X.tuileExp)}${tuile("★★★★★", C.yellow, X.tuileAvis)}${tuile("2008", C.sky, X.tuileDepuis)}</div>
        <div style="flex:1;"></div>
        <div style="display:flex;align-items:center;gap:36px;margin-top:36px;border-top:2px solid ${C.trait};padding-top:30px;">
          ${M.tesla ? `<img src="${A.tesla}" alt="${X.altTesla}" style="width:330px;display:block;">` : ""}
          <img src="${A.cmeq}" alt="${X.altCmeq}" style="height:96px;width:96px;object-fit:contain;display:block;">
          <div style="font-size:24px;color:${C.g2};line-height:1.5;">${X.membreCmeqLic}</div>
        </div>
      </div>
      <div style="position:relative;"><img src="${photo}" alt="${X.altInstallation}" style="position:absolute;inset:0;width:100%;height:100%;object-fit:${photo === A.fox ? "contain" : "cover"};"><div style="position:absolute;inset:0;background:linear-gradient(90deg,#FFF 0%,rgba(255,255,255,0) 12%);pointer-events:none;"></div></div>
    </div>`);
  }

  function photosRealisations(M) {
    const reelles = Array.isArray(window.PROPOSITION_PHOTOS) ? window.PROPOSITION_PHOTOS.filter(Boolean).slice(0, 3) : [];
    if (reelles.length >= 2) return reelles;
    // Candidats par modèle, sans aucune photo déjà montrée ailleurs dans la proposition (titre, Raycom, technologie, volets)
    // Tesla : grande tuile = Powerwall en situation, puis une vraie installation Raycom (petite tuile), puis une autre photo
    // en situation. Les photos d'installation Raycom se ressemblent toutes (deux batteries grises au mur) : une seule ici,
    // la diapo « Qui est Raycom » en montre déjà une (JF, 8 nov. 2026 : « c'est tout le temps les mêmes »).
    const reelle = tourner([...RAYCOM_INST, A.raycomPw], 1).filter(x => !VUS.has(x));
    const memeMaison = VUS.has(A.teslaAerien) || VUS.has(A.teslaNuit); // les deux photos montrent la même maison : une seule par proposition
    const situ = tourner([A.teslaRecharge, A.teslaGarage, A.teslaTerrasse, A.teslaMur, ...(memeMaison ? [] : [A.teslaAerien]), A.teslaFacade, ...(M.aSol ? [A.teslaSolaire] : [])], 3).filter(x => !VUS.has(x));
    const cands = M.tesla ? [situ[0], reelle[0], ...situ.slice(1), ...reelle.slice(1)]
      : M.marque === "sigenergy" ? [A.sigStor, A.sigHub, M.v2x ? A.sigV2x : A.recharge, A.solaire, A.maisonJour]
      : M.aSol ? [A.solaire, A.maisonJour, ...(M.marque === "fox" || M.marqueOnd === "fox" ? [A.fox] : [])] : [];
    const out = cands.filter(s => s && !VUS.has(s)).slice(0, 3);
    out.forEach(marquer);
    return out;
  }
  function diapoRealisations(M, photos) {
    const titre = M.tesla ? X.realTesla : M.marque === "sigenergy" ? X.realSig : X.realSol;
    const img = (src, extra) => `<div style="position:relative;border-radius:12px;overflow:hidden;${extra || ""}"><img src="${esc(src)}" alt="${X.altRealisation}" style="position:absolute;inset:0;width:100%;height:100%;object-fit:${src === A.fox ? "contain" : "cover"};${src === A.fox ? "background:#FFF;" : ""}"></div>`;
    const grille = photos.length >= 3
      ? `<div style="flex:1;display:grid;grid-template-columns:1.5fr 1fr;grid-template-rows:1fr 1fr;gap:22px;margin-top:44px;">${img(photos[0], "grid-row:1/3;")}${img(photos[1])}${img(photos[2])}</div>`
      : `<div style="flex:1;display:grid;grid-template-columns:1.4fr 1fr;gap:22px;margin-top:44px;">${img(photos[0])}${img(photos[1])}</div>`;
    return diapo("Réalisations", C.navy, `<div style="height:100%;display:flex;flex-direction:column;padding:80px 100px;box-sizing:border-box;">
      <div style="display:flex;justify-content:space-between;align-items:baseline;"><div>${surtitre(X.realSur, true)}${grandTitre(titre, true, 60, 10)}</div><div style="font-size:24px;color:${C.s2};">${X.regions}</div></div>${grille}</div>`, true);
  }

  function diapoTechnologie(M) {
    const cartes = [];
    const carte = (titre, sous, img, lignes, chiffre, fit = "contain", fond = "#FFF") => (marquer(img), `<div style="background:#FFF;border-radius:14px;box-shadow:0 4px 24px rgba(12,35,64,.08);display:flex;flex-direction:column;overflow:hidden;">
      <div style="position:relative;height:380px;background:${img ? fond : C.navy};">${img ? `<img src="${esc(img)}" alt="${esc(titre)}" style="position:absolute;${fit === "cover" ? "inset:0;width:100%;height:100%" : "inset:4%;width:92%;height:92%"};object-fit:${fit};">` : `<div style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;"><div style="${T}font-size:96px;color:${C.sky};line-height:1;">${chiffre || ""}</div><div style="font-size:24px;color:${C.s3};margin-top:10px;">${esc(sous)}</div></div>`}</div>
      <div style="padding:26px 32px 30px;border-top:1px solid ${C.bord};"><div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${esc(sous)}</div><div style="${T}font-size:36px;color:${C.navy};margin-top:4px;line-height:1.15;">${esc(titre)}</div>
      <div style="display:flex;flex-direction:column;gap:6px;margin-top:14px;font-size:22px;color:${C.g1};">${lignes.map(t => puce(t)).join("")}</div></div></div>`);
    if (M.marque === "sigenergy") {
      const kwOnd = M.ondStock ? (kwDe(M.ondStock.nom) || 11.5) : (M.ondSol ? kwDe(M.ondSol.nom) || 11.5 : 11.5);
      cartes.push(carte("SigenStor", X.techSigStorSous, A.sigStor, X.techSigStor(fmtNum(kwOnd), fmtNum(M.kwh), M.aSol), null, "cover"));
      if (M.loadhub) cartes.push(carte("LoadHub 200 A", X.techHubSous, A.sigHub, X.techHub, null, "cover"));
      if (M.v2x) cartes.push(carte(X.techV2xTitre, X.techV2xSous, A.sigV2x, X.techV2x, null, "contain", "#000"));
      if (cartes.length < 2) return "";
    } else if (M.marque === "lux") {
      const ond = M.ondStock || M.ondSol; const kwOnd = ond ? kwDe(ond.nom) : null;
      const imgOnd = ond && ond.article && ond.article.image_url;
      const bat = M.volets.flatMap(v => v.lignes).find(l => l.article && l.article.est_batterie);
      cartes.push(carte("Lux Power", X.techLuxSous, imgOnd || null, X.techLux, kwOnd ? `${fmtNum(kwOnd)} kW` : X.techLuxHybride));
      cartes.push(carte("Volthium", X.techVolSous, (bat && bat.article && bat.article.image_url) || null, X.techVol, `${fmtNum(M.kwh)} kWh`));
    } else return "";
    const titre = M.marque === "sigenergy" ? X.techTitreSig : X.techTitreLux;
    return diapo("Technologie proposée", C.light, `${LIS_CLAIR}<div style="height:100%;display:flex;flex-direction:column;padding:80px 100px;box-sizing:border-box;">${surtitre(X.techSur)}${grandTitre(titre, false, 58)}
      <div style="flex:1;display:grid;grid-template-columns:repeat(${cartes.length},1fr);gap:26px;margin-top:40px;">${cartes.join("")}</div></div>`);
  }

  function blocsPrix(v, M) {
    return `<div style="font-size:26px;color:#24303E;">${v.blocs.map((b, i) => `<div style="display:flex;justify-content:space-between;gap:24px;padding:7px 0;${i < v.blocs.length - 1 ? `border-bottom:2px solid ${C.trait};` : ""}${b.montant < 0 ? `color:${C.blue};` : ""}" data-bloc="${esc(b.cle)}" data-montant="${b.montant}"><span>${esc(b.label)}</span><strong style="white-space:nowrap;">${fmt(b.montant)}</strong></div>`).join("")}</div>
      <div style="display:flex;justify-content:space-between;align-items:center;background:${C.navy};color:#FFF;padding:20px 30px;border-radius:10px;margin-top:14px;"><span style="${T}font-weight:700;font-size:30px;">${v.numero ? X.voletN(Number(v.numero)) : (v.id === "borne" || v.id === "travaux" ? X.votreProjet : X.votreSysteme)} <span style="font-family:'Barlow',Arial,sans-serif;font-size:24px;color:${C.s2};font-weight:400;">${X.avantTaxesParen}</span></span><span style="${T}font-size:42px;color:${C.sky};" data-volet-ht="${v.ht}">${fmt(v.ht)}</span></div>`;
  }

  function diapoVolet(M, v, ctx) {
    const c = contenuVolet(M, v, ctx);
    const entete = `<div style="display:flex;align-items:baseline;gap:20px;">${v.numero ? `<div style="${T}font-size:72px;color:${C.sky};">${v.numero}</div>` : ""}<div><div style="${T}font-size:52px;color:${C.navy};line-height:1.1;">${esc(c.titre)}</div><div style="font-size:24px;color:${C.g2};margin-top:6px;">${X.propositionNo(esc(ctx.num))} · ${esc(c.sous)}</div></div></div>`;
    const inclusions = c.riche
      ? `<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px 34px;margin-top:20px;background:${C.light};border-radius:12px;padding:22px 30px;">${c.inclusions.join("")}</div>`
      : `<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px 30px;margin-top:30px;background:${C.light};border-radius:12px;padding:28px 34px;font-size:24px;color:${C.g1};">${c.inclusions.join("")}</div>`;
    // c.desc est du HTML de gabarit (balises <strong> des dictionnaires FR et EN) : il n'est donc pas échappé ici ; chaque valeur
    // variable qui y entre (nombres formatés, marque du panneau, puissance du catalogue) est échappée dans contenuVolet.
    const texte = `<div style="font-size:26px;color:${C.g1};line-height:1.5;margin-top:22px;">${c.desc}</div>`;
    const label = v.numero ? `Volet ${Number(v.numero)} · ${c.recap}` : c.recap;
    if (c.solaire) {
      const sol = ctx.sol;
      const img = sol.aurora_image || null;
      const google = sol.production_source === "google";
      const carteToit = `<div style="position:absolute;top:24px;left:24px;width:400px;z-index:1;background:#FFF;border-radius:12px;padding:14px 16px;box-shadow:0 8px 26px rgba(0,0,0,.45);"><div style="font-size:22px;color:${C.g2};padding:0 6px 8px;line-height:1.4;border-bottom:1px solid ${C.bord};">${google ? `${X.ensoleillementMesure}${sol.acces_pct != null ? `<br>${X.accesSolaire} <strong style="color:${C.navy};">${X.pct(fmtNum(sol.acces_pct))}</strong>` : ""}` : `${X.irradianceMoy} <strong style="color:${C.navy};">${fmtInt(sol.irradiance || 1311)} ${X.kwhM2An}</strong><br>${X.accesSolaire} <strong style="color:${C.navy};">${X.pct(fmtNum(sol.acces_pct == null ? 100 : sol.acces_pct))}</strong>`}</div><div style="font-size:22px;color:${C.g2};padding:8px 6px 0;line-height:1.25;">${X.prodMoyEstimee}</div><div style="${T}font-size:32px;color:${C.navy};padding:0 6px 4px;line-height:1.2;">≈ ${fmtInt(ctx.production)} ${X.kwhAn}</div></div>`;
      // Image du design (copiée d'Aurora ou du studio) : montrée ENTIÈRE (contain) dans un cadre clair, jamais rognée ni trop zoomée (JF, 6 nov. 2026).
      const legende = `${fmtNum(M.kw)} kW · ${ctx.panneaux} ${X.panneaux}${ctx.production > 0 ? ` · ≈ ${fmtInt(ctx.production)} ${X.kwhAn}` : ""}`;
      const gauche = img
        ? `<div style="position:relative;background:${C.light};display:flex;flex-direction:column;padding:56px 40px 40px;box-sizing:border-box;gap:22px;min-height:0;"><div style="flex:1;min-height:0;display:flex;align-items:center;justify-content:center;"><img src="${esc(img)}" alt="${X.altConception}" style="display:block;max-width:100%;max-height:100%;object-fit:contain;box-sizing:border-box;background:#FFF;padding:12px;border-radius:14px;box-shadow:0 8px 30px rgba(12,35,64,.16);"></div>${ctx.production > 0 ? carteToit.replace("position:absolute;top:24px;left:24px;width:400px;z-index:1;", "position:relative;width:auto;box-shadow:0 4px 18px rgba(12,35,64,.10);") : ""}<div style="font-size:24px;font-weight:600;color:${C.navy};text-align:center;">${ctx.production > 0 ? `${fmtNum(M.kw)} kW · ${ctx.panneaux} ${X.panneaux}` : legende}</div></div>`
        : `<div style="position:relative;background:#33373E;"><img src="${esc(prendre([A.solaire, A.maisonJour, A.teslaSolaire], A.solaire))}" alt="${X.altSolaire}" style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;">${ctx.production > 0 ? carteToit : ""}<div style="position:absolute;left:0;right:0;bottom:0;background:linear-gradient(0deg,rgba(12,35,64,.8),rgba(12,35,64,0));padding:20px 26px;color:#FFF;font-size:24px;font-weight:600;">${legende}</div><div style="position:absolute;inset:0;background:linear-gradient(270deg,#FFF 0%,rgba(255,255,255,0) 12%);pointer-events:none;"></div></div>`;
      return diapo(label, "#FFF", `${LIS_CLAIR}<div style="display:grid;grid-template-columns:${img ? "860px" : "700px"} 1fr;height:100%;box-sizing:border-box;">${gauche}<div style="padding:56px 80px 48px;display:flex;flex-direction:column;min-height:0;">${entete}${texte}${inclusions}<div style="flex:1;"></div>${blocsPrix(v, M)}</div></div>`);
    }
    const contenu = `${entete}${texte}${inclusions}<div style="flex:1;"></div>${blocsPrix(v, M)}`;
    if (!c.photo) return diapo(label, "#FFF", `${LIS_CLAIR}<div style="height:100%;display:flex;flex-direction:column;padding:70px 140px 60px;box-sizing:border-box;">${contenu}</div>`);
    return diapo(label, "#FFF", `${LIS_CLAIR}<div style="display:grid;grid-template-columns:1fr 700px;height:100%;box-sizing:border-box;"><div style="padding:52px 80px 48px;display:flex;flex-direction:column;min-height:0;">${contenu}</div>${photoPanneau(marquer(c.photo.src), c.photo.alt, "90deg", c.photo.fit || "cover", c.photo.fond || "")}</div>`);
  }

  // ─── Autonomie en panne (charges cochées au configurateur, calc-re.jsx : calcAutonomie) ───
  const autoLib = (r) => r ? (LOC === "en-CA" ? r.libelle_en : r.libelle_fr) : "";
  const autoPct = (r) => !r || r.vide ? 0 : (r.illimitee || r.plusieurs) ? 100 : Math.max(10, Math.min(100, r.jours / 7 * 100));
  function listeCharges(a, max) {
    const en = LOC === "en-CA";
    const noms = (a.charges || []).map((c, i) => { let n = en ? c.court_en : c.court_fr; if (i === 0) n = n.charAt(0).toUpperCase() + n.slice(1); n = esc(n);
      return `<span style="white-space:nowrap;">${c.qty > 1 ? `${n} (${c.qty})` : n}</span>`; });
    if (!noms.length) return "";
    return noms.length > max ? noms.slice(0, max).join(", ") + X.autoEtAutres(noms.length - max) : noms.join(", ");
  }
  const barreAuto = (pct, coul, h) => `<div style="height:${h}px;border-radius:5px;background:#E8EEF6;margin-top:6px;"><div style="width:${pct.toFixed(0)}%;height:100%;background:${coul};border-radius:5px;"></div></div>`;

  function diapoSecours(M) {
    const a = M.autonomie && M.autonomie.duree ? M.autonomie : null;
    const app = X.app[M.marque] || X.appFabricant;
    const evol = M.marque === "tesla" ? X.evolTesla
      : M.marque === "fox" ? X.evolFox
      : M.marque === "sigenergy" ? X.evolSig
      : M.marque === "lux" ? X.evolLux : "";
    const reno = M.subv.reno > 0 ? `<div style="background:rgba(255,201,60,.12);border:1px solid rgba(255,201,60,.55);border-radius:12px;padding:20px 26px;margin-top:22px;font-size:23px;color:${C.s3};line-height:1.45;"><div style="font-weight:700;color:${C.yellow};font-size:24px;">${X.renoJusqua(fmt0(M.subv.reno))}</div><div style="margin-top:6px;">${X.renoTexte(M.subv.renoRaccord > 0)}</div></div>` : "";
    return diapo("Secours et évolutivité", C.light, `${LIS_CLAIR}<div style="height:100%;display:flex;flex-direction:column;padding:80px 100px;box-sizing:border-box;">${surtitre(M.marque === "sigenergy" ? X.secSurSig : X.secSur)}${grandTitre(X.secTitre, false, 60)}
      <div style="flex:1;display:grid;grid-template-columns:1fr 1fr;gap:30px;margin-top:44px;">
        <div style="background:#FFF;border-radius:14px;padding:40px 44px;box-shadow:0 4px 24px rgba(12,35,64,.08);display:flex;flex-direction:column;">
          <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.secCarte}</div>
          ${a ? `<div style="font-size:24px;color:${C.g2};margin-top:10px;">${X.autoBatterie(fmtNum(a.kwh_utilisable))}</div>
          ${(a.avec_solaire ? [[X.autoBattSeule, a.batterie_seule, C.blue], [X.autoBattSol(fmtNum(a.kw_solaire)), a.duree, C.sky]] : [[X.autoEstimee, a.duree, C.blue]]).map(([lib, r, coul]) => `<div style="display:flex;justify-content:space-between;align-items:baseline;margin-top:10px;font-size:26px;color:${C.g1};"><span>${lib}</span><span style="${T}font-size:38px;color:${C.navy};">${autoLib(r)}</span></div>${barreAuto(autoPct(r), coul, 16)}`).join("")}
          ${a.charges.length ? `<div style="font-size:22px;color:${C.g1};margin-top:12px;line-height:1.35;">${X.chargesCouvertes(listeCharges(a, 10))}</div>` : ""}
          <div style="font-size:22px;color:${C.g2};margin-top:6px;line-height:1.3;">${X.autoNote}</div>`
          : `<div style="display:flex;justify-content:space-between;align-items:baseline;margin-top:16px;font-size:26px;color:${C.g1};"><span>${X.batterieSeule(fmtNum(M.kwh))}</span></div><div style="font-size:22px;color:${C.g2};margin-top:8px;">${X.selonCircuits}</div>`}
          <div style="display:flex;flex-direction:column;gap:10px;margin-top:26px;font-size:24px;color:${C.g1};">${[M.marque === "sigenergy" ? X.secTransfertInst : X.secBascule, M.complet ? X.secMaison : X.secPrio, X.secNiveau(app)].map(t => puce(t)).join("")}</div>
          ${evol ? `<div style="font-size:24px;color:${C.g1};line-height:1.5;margin-top:22px;"><strong style="color:${C.navy};">${X.besoinAutonomie}</strong> ${evol}</div>` : ""}
        </div>
        <div style="background:${C.navy};border-radius:14px;padding:40px 44px;color:#FFF;display:flex;flex-direction:column;">
          <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.sky};text-transform:uppercase;">${X.pretSolaire}</div>
          <div style="${T}font-size:44px;margin-top:12px;line-height:1.15;">${X.pretSolaireTitre}</div>
          <div style="font-size:24px;color:${C.s3};line-height:1.55;margin-top:16px;">${X.pretSolaireTexte({ tesla: M.marque === "tesla", v2x: M.v2x })}</div>
          ${reno}
        </div>
      </div></div>`);
  }

  function diapoSubventions(M, ctx, state) {
    const s = M.subv; const sub = (state && state.subventions) || {};
    const batt = M.aBatt;
    const rows = batt ? [
      { k: "principale", t: X.subPrincipale, d: s.reno > 0 ? `LogisVert + Rénoclimat · ${fmt(s.logisvert + s.reno)}` : `LogisVert · ${fmt(s.logisvert)}`, m: s.logisvert + s.reno },
      { k: "secondaire", t: X.subSecondaire, d: `${X.lvSeulement} · ${fmt(s.logisvert)}`, m: s.logisvert },
      { k: "saisonnier", t: X.subSaisonnier, d: X.subAucune, m: 0 }
    ] : [
      { k: "annee", t: X.subAnnee, d: `LogisVert · ${fmt(s.logisvert)}`, m: s.logisvert },
      { k: "saisonnier", t: X.subSaisonnier, d: X.subAucune, m: 0 }
    ];
    const situation = sub.situation || (sub.logisvert_admissible === false ? "saisonnier" : (batt && sub.renoclimat_admissible === false ? "secondaire" : null));
    const choisis = situation && rows.some(r => r.k === situation) ? rows.filter(r => r.k === situation) : rows;
    const ligne = (r, i) => {
      const actif = situation ? true : i === 0;
      const style = situation ? `background:rgba(62,207,142,.14);border:2px solid ${C.green};` : actif ? `background:${C.light};` : `border:1px solid ${C.bord};`;
      return `<div style="display:grid;grid-template-columns:1fr auto;gap:4px 16px;padding:14px 18px;border-radius:10px;${style}"><div style="grid-column:1/3;font-size:22px;color:${C.navy};font-weight:700;line-height:1.3;">${esc(r.t)}</div><div style="font-size:22px;color:${C.g2};">${esc(r.d)}</div><div style="${T}font-size:30px;color:${C.blue};text-align:right;white-space:nowrap;">${fmt(M.ttc - r.m - s.autres)}</div></div>`;
    };
    const carteReno = batt ? `<div style="background:#FFF;border-radius:14px;padding:30px 34px;box-shadow:0 4px 24px rgba(12,35,64,.08);display:flex;flex-direction:column;">
        <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.renoCarte}</div>
        <div style="${T}font-size:54px;color:${C.navy};margin-top:8px;">${X.jusquaCap(fmt0(s.reno > 0 ? s.reno : 5000))}</div>
        <div style="display:flex;flex-direction:column;gap:12px;margin-top:10px;font-size:22px;color:${C.g1};line-height:1.35;">
          ${puce(X.renoPuceBatt(`color:${C.navy};`))}
          ${s.renoRaccord > 0 || s.reno === 0 ? puce(X.renoPuceRacc(`color:${C.navy};`)) : ""}
        </div>
        <div style="flex:1;"></div>
        <div style="background:${C.light};border-radius:10px;padding:14px 20px;margin-top:14px;font-size:22px;color:${C.g1};line-height:1.4;">${X.renoConditions}</div>
      </div>` : `<div style="background:#FFF;border-radius:14px;padding:30px 34px;box-shadow:0 4px 24px rgba(12,35,64,.08);display:flex;flex-direction:column;">
        <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.mesurageCarte}</div>
        <div style="${T}font-size:54px;color:${C.navy};margin-top:8px;">${X.surplusCredits}</div>
        <div style="font-size:24px;color:${C.g1};line-height:1.55;margin-top:10px;">${X.mesurageTexte}</div>
      </div>`;
    return diapo("Subventions", C.light, `${LIS_VERT}<div style="height:100%;display:flex;flex-direction:column;padding:56px 100px 36px;box-sizing:border-box;">
      <div style="display:flex;justify-content:space-between;align-items:baseline;">
        <div>${surtitre(X.subSur(esc(ctx.mois)))}${grandTitre(X.subTitre, false, 58)}</div>
        <div style="text-align:right;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.g2};text-transform:uppercase;">${X.subEstimees}</div><div style="${T}font-size:54px;color:${C.blue};">${X.jusqua(fmt0(s.total))}</div></div>
      </div>
      <div style="flex:1;min-height:0;display:grid;grid-template-columns:1.15fr 1fr 1.1fr;gap:24px;margin-top:20px;">
        <div style="background:${C.navy};border-radius:14px;padding:30px 34px;color:#FFF;display:flex;flex-direction:column;">
          <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.green};text-transform:uppercase;">${X.lvCarte}</div>
          <div style="${T}font-size:54px;margin-top:8px;">${X.lvParKw}</div>
          <div style="font-size:22px;color:${C.s3};line-height:1.45;margin-top:6px;">${X.lvTexte}</div>
          <div style="flex:1;"></div>
          <div style="background:rgba(62,207,142,.12);border:1px solid rgba(62,207,142,.45);border-radius:10px;padding:14px 20px;margin-top:14px;font-size:22px;color:${C.s3};">
            <div style="display:flex;justify-content:space-between;gap:12px;padding:3px 0;"><span>${X.lvKwFois(fmtNum(M.kw))}</span><strong style="color:#FFF;white-space:nowrap;">${fmt(s.lvKw)}</strong></div>
            <div style="display:flex;justify-content:space-between;gap:12px;padding:3px 0;"><span>${X.lv40de(fmt(s.solHT))}</span><strong style="color:#FFF;white-space:nowrap;">${fmt(s.lv40)}</strong></div>
            <div style="display:flex;justify-content:space-between;align-items:baseline;gap:12px;border-top:1px solid rgba(127,184,240,.35);margin-top:6px;padding-top:6px;"><span>${X.plafondApplique}<strong style="color:#FFF;">${s.plafondKw ? X.plafondKw : X.plafond40}</strong></span><span style="${T}font-size:38px;color:${C.green};white-space:nowrap;" data-logisvert="${s.logisvert}">${fmt(s.logisvert)}</span></div>
          </div>
          <div style="font-size:22px;color:${C.s2};margin-top:12px;line-height:1.4;">${X.lvVersee}</div>
        </div>
        ${carteReno}
        <div style="background:#FFF;border-radius:14px;padding:30px 34px;box-shadow:0 4px 24px rgba(12,35,64,.08);display:flex;flex-direction:column;">
          <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.subSituation}</div>
          <div style="display:flex;justify-content:space-between;font-size:22px;color:${C.g2};margin-top:14px;padding:0 18px;"><span>${X.subEstimees}</span><span>${X.netTaxesIncl}</span></div>
          <div style="display:flex;flex-direction:column;gap:12px;margin-top:8px;flex:1;">${choisis.map(ligne).join("")}</div>
          ${s.autres > 0 ? `<div style="font-size:22px;color:${C.g1};margin-top:10px;">${X.autresInclus(esc((state.subventions || {}).autres_libelle || X.autreSubvention), fmt(s.autres))}</div>` : ""}
        </div>
      </div>
      <div style="font-size:22px;color:${C.g2};margin-top:12px;">${X.subSources}</div>
    </div>`);
  }

  function diapoRendement(M, ctx) {
    const R = M.rendement, s = M.subv;
    const rng = (n) => n == null ? X.plusDe40 : n <= 1 ? X.moinsDe2 : X.ansEntre(n - 1, n + 1);
    const kpi = (titre, val, sous, coul) => `<div style="background:#FFF;border:1px solid ${C.bord};border-top:6px solid ${coul};border-radius:8px;padding:16px 20px;min-width:0;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.g2};text-transform:uppercase;line-height:1.2;min-height:53px;">${titre}</div><div style="${T}font-size:40px;color:${C.navy};margin-top:4px;white-space:nowrap;">${val}</div><div style="font-size:22px;color:${C.g2};line-height:1.25;">${sous}</div></div>`;
    const sol = ctx.sol;
    const srcProd = sol.production_source === "google" ? X.mesureeToit : `${fmtNum(M.kw)} kW × ${fmtInt(sol.irradiance || 1311)} × ${X.pct(fmtNum(sol.acces_pct == null ? 100 : sol.acces_pct))} × ${X.zeroVirgule80}`;
    // Graphique à barres des économies cumulées, taxes incluses, axe dynamique
    const maxV = Math.max(R.barres[4].ttc, R.netRoi, 1);
    const brut = maxV / 4, p10 = Math.pow(10, Math.floor(Math.log10(brut))), m = brut / p10;
    const pas = (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p10, axe = pas * 4;
    const pct = (v) => Math.max(0, Math.min(100, v / axe * 100));
    const couleurs = [C.sky, C.sky, "#1E86D9", C.blue, C.yellow];
    const barres = R.barres.map((b, i) => `<div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:8px;height:100%;"><div style="font-size:22px;font-weight:700;color:${i === 4 ? C.yellow : C.s1};line-height:1.15;text-align:center;white-space:nowrap;">${fmt0(b.ttc)}${i === 1 || i === 4 ? `<div style="font-size:22px;font-weight:400;color:${C.s2};">${fmt0(b.ht)} ${X.avantTaxes}</div>` : ""}</div><div style="width:100%;height:${pct(b.ttc).toFixed(1)}%;background:${couleurs[i]};"></div></div>`).join("");
    const axeTxt = [4, 3, 2, 1].map(i => `<div style="border-top:1px solid rgba(159,180,204,.25);font-size:22px;color:${C.s2};">${fmt0(pas * i)}</div>`).join("");
    const yNet = 100 - pct(R.netRoi);
    // Coût net ligne par ligne
    const vSol = M.vSol, vSto = M.vSto;
    const colonnes = [{ t: X.colSolaire, ht: vSol.ht, moins: s.logisvert }].concat(vSto ? [{ t: X.colStockage, ht: vSto.ht, moins: s.reno }] : []);
    const ligneT = (lib, vals, gras, coul) => `<tr style="${gras ? `font-weight:700;color:${C.navy};` : ""}${coul ? `color:${coul};` : ""}"><td style="padding:3px 0;${gras ? `border-top:1px solid ${C.bord};` : ""}">${lib}</td>${vals.map(v => `<td style="padding:3px 0 3px 14px;text-align:right;white-space:nowrap;${gras ? `border-top:1px solid ${C.bord};` : ""}">${v}</td>`).join("")}</tr>`;
    const tableau = `<table style="width:100%;border-collapse:collapse;font-size:22px;color:${C.g1};margin-top:8px;"><thead><tr><th></th>${colonnes.map(c => `<th style="text-align:right;color:${C.navy};padding:0 0 4px 14px;border-bottom:1px solid ${C.bord};">${c.t}</th>`).join("")}</tr></thead><tbody>
      ${ligneT(X.tSousTotal, colonnes.map(c => fmt(c.ht)))}
      ${ligneT(X.tTaxes, colonnes.map(c => fmt(taxesDe(c.ht))))}
      ${ligneT(X.tTotal, colonnes.map(c => fmt(r2(c.ht + taxesDe(c.ht)))))}
      ${ligneT(vSto ? X.tMoinsSub : X.tMoinsLv, colonnes.map(c => c.moins > 0 ? `− ${fmt(c.moins)}` : fmt(0)), false, C.blue)}
      ${ligneT(X.tCoutNet, colonnes.map(c => fmt(r2(c.ht + taxesDe(c.ht) - c.moins))), true)}</tbody></table>
      <div style="display:flex;justify-content:space-between;margin-top:8px;padding-top:6px;border-top:2px solid ${C.navy};font-size:22px;font-weight:700;color:${C.navy};"><span>${X.projetCompletTI}</span><span style="white-space:nowrap;">${fmt(M.ttc)}</span></div>
      <div style="display:flex;justify-content:space-between;font-size:22px;font-weight:700;color:${C.blue};"><span>${vSto ? X.coutNetPrincipale : X.coutNetApresLv}</span><span style="white-space:nowrap;">${fmt(M.ttc - s.total)}</span></div>`;
    // Carte « Autonomie en cas de panne » : charges cochées au configurateur, batterie seule puis batterie + solaire,
    // une seule valeur (journée moyenne de panne, JF 6 nov. 2026).
    const a = M.aBatt && M.autonomie && M.autonomie.duree ? M.autonomie : null;
    const bs = a ? a.batterie_seule : null;
    // Carte compacte (la colonne de droite est pleine) : batterie seule puis avec le solaire ; ligne de production solaire ;
    // liste des charges sur une ligne.
    const td = (v, st) => `<td style="padding:2px 0 2px 14px;text-align:right;white-space:nowrap;${st || ""}">${v}</td>`;
    const autonomie = a ? `<div style="background:#FFF;border:1px solid ${C.bord};border-radius:8px;padding:10px 24px;min-width:0;">
        <div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.autonomieCarte}</div>
        <table style="width:100%;border-collapse:collapse;font-size:22px;color:${C.g1};margin-top:4px;"><tbody>
          <tr><td style="padding:2px 0;">${X.autoBattSeule} · ${fmtNum(a.kwh_utilisable)} kWh</td>${td(autoLib(a.avec_solaire ? bs : a.duree), a.avec_solaire ? `color:${C.g2};` : `color:${C.navy};font-weight:700;`)}</tr>
          ${a.avec_solaire ? `<tr><td style="padding:2px 0;">${X.autoBattSol(fmtNum(a.kw_solaire))}</td>${td(autoLib(a.duree), `color:${C.sky};font-weight:700;`)}</tr>` : ""}</tbody></table>
        ${a.avec_solaire ? `<div style="font-size:22px;color:${C.g2};margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${X.autoSolaireLigne(fmtNum(a.duree.solaire_kwh))}</div>` : ""}
        ${a.charges.length ? `<div style="font-size:22px;color:${C.g1};margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${X.chargesCouvertes(listeCharges(a, 3))}</div>` : ""}</div>` : "";
    return diapo("Rendement et économies", C.light, `${LIS_CLAIR}<div style="height:100%;display:flex;flex-direction:column;padding:50px 90px 34px;box-sizing:border-box;">
      ${surtitre(X.rendSur)}${grandTitre(X.rendTitre, false, 52, 8)}
      <div style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:16px;margin-top:20px;">
        ${kpi(X.kpiProd, `≈ ${fmtInt(R.prod)} kWh`, esc(srcProd), C.sky)}
        ${kpi(X.kpiEco, `≈ ${X.parMois(fmt0(R.moisT))}`, X.inclTaxesAvant(fmt0(R.moisHT)), C.s1)}
        ${kpi(X.kpiLv, fmt0(s.logisvert), X.kpiLvSous, C.yellow)}
        ${kpi(R.onduleurPw ? X.kpiNetRenta : X.kpiNetSol, fmt0(R.netRoi), R.onduleurPw ? X.kpiNetPw(fmt0(R.baseTTC), fmt0(s.logisvert)) : X.kpiNet(fmt0(R.baseTTC), fmt0(s.logisvert)), C.blue)}
        ${kpi(X.kpiRoi, rng(R.roiT), X.inclTaxesAvant(rng(R.roiH)), C.navy)}
      </div>
      <div style="flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:20px;margin-top:16px;">
        <div style="background:${C.navy};border-radius:8px;padding:22px 30px;color:#FFF;display:flex;flex-direction:column;min-height:0;">
          <div style="font-size:23px;font-weight:700;letter-spacing:2px;color:${C.sky};text-transform:uppercase;">${X.ecoCumulees}</div>
          <div style="font-size:22px;color:${C.s2};margin-top:4px;">${X.ecoCalcul(fmtInt(R.prod), fmtTarif(R.tarif), fmt0(R.ecoAn1), fmt0(R.ecoAn1T))}</div>
          <div style="display:flex;gap:30px;font-size:22px;color:${C.s2};margin-top:6px;"><span style="display:flex;align-items:center;gap:10px;"><span style="width:22px;height:14px;background:${C.sky};"></span>${X.legEco}</span><span style="display:flex;align-items:center;gap:10px;"><span style="width:30px;border-top:3px dashed #FFF;"></span>${R.onduleurPw ? X.legNetRenta : X.legNetSol} ${fmt0(R.netRoi)}</span></div>
          <div style="flex:1;position:relative;margin-top:16px;min-height:0;">
            <div style="position:absolute;inset:0;display:flex;flex-direction:column;justify-content:space-between;">${axeTxt}<div></div></div>
            <div style="position:absolute;inset:0;display:flex;align-items:flex-end;gap:26px;padding:0 20px 0 150px;">${barres}</div>
            <div style="position:absolute;left:150px;right:20px;top:${yNet.toFixed(1)}%;border-top:3px dashed #FFF;z-index:1;"></div>
          </div>
          <div style="display:flex;gap:26px;padding:8px 20px 0 150px;">${R.barres.map((b, i) => `<div style="flex:1;text-align:center;font-size:22px;color:${i === 4 ? C.yellow : C.s2};border-top:2px solid ${i === 4 ? C.yellow : "rgba(159,180,204,.4)"};padding-top:6px;${i === 4 ? "font-weight:700;" : ""}">${X.nAns(b.an)}</div>`).join("")}</div>
        </div>
        <div style="display:flex;flex-direction:column;gap:14px;min-height:0;">
          <div style="background:#FFF;border:1px solid ${C.bord};border-radius:8px;padding:16px 24px;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.blue};text-transform:uppercase;">${X.calculLigne}</div>${tableau}</div>
          ${autonomie}
        </div>
      </div>
      <div style="font-size:22px;color:${C.g2};margin-top:12px;line-height:1.35;">${X.hypotheses({ c: C.g1, kw: fmtNum(M.kw), google: sol.production_source === "google", irr: fmtInt(sol.irradiance || 1311), acces: fmtNum(sol.acces_pct == null ? 100 : sol.acces_pct), tarif: fmtTarif(R.tarif), idx: fmtNum(R.idx * 100), deg: fmtNum(R.deg * 100), pw: R.onduleurPw })}</div>
    </div>`);
  }

  function diapoEtapes(M) {
    const std = M.aBatt || M.aSol;
    const etapes = std ? X.etapesStd : X.etapesSimples;
    const coul = ["#2F7FD9", C.sky, "#59B9E8", C.green];
    const cartes = etapes.map(([t, items], i) => `<div style="flex:1;display:flex;flex-direction:column;align-items:center;position:relative;">
      <div style="${T}font-size:64px;color:${coul[i]};line-height:1;">${i + 1}</div>
      <div style="width:22px;height:22px;border-radius:50%;background:${coul[i]};border:4px solid ${coul[i]};margin-top:18px;position:relative;z-index:1;"></div>
      <div style="margin-top:26px;${i === 3 ? "background:rgba(62,207,142,.12);border:1px solid rgba(62,207,142,.55);border-radius:12px;" : CARTE_MARINE + "border-radius:12px;"}padding:28px 26px;width:100%;box-sizing:border-box;flex:1;display:flex;flex-direction:column;gap:12px;">
        <div style="font-weight:700;font-size:29px;color:#FFF;text-align:center;">${t}</div>${items.map(x => crochet(x, i === 3)).join("")}</div></div>`).join("");
    return diapo("Étapes du projet", C.navy, `<div style="height:100%;display:flex;flex-direction:column;justify-content:center;padding:90px 100px;box-sizing:border-box;">${surtitre(X.etapesSur, true)}${grandTitre(X.etapesTitre, true, 60)}
      <div style="position:relative;display:flex;gap:26px;margin-top:60px;align-items:stretch;"><div style="position:absolute;top:93px;left:10%;right:10%;height:3px;background:linear-gradient(90deg,#2F7FD9 0%,${C.sky} 33%,#59B9E8 66%,${C.green} 100%);"></div>${cartes}</div></div>`, true);
  }

  function diapoGaranties(M, ctx, state, calc) {
    const L = M.volets.flatMap(v => v.lignes).filter(l => !estMO(l));
    const has = (re) => L.some(l => re.test(l.nom || ""));
    const g = [], b = (x) => `<strong style="color:#FFF;">${x}</strong>`;
    if (M.tesla) g.push(X.gTesla(b, M.gw));
    if (has(/Fox ESS/i)) g.push(X.gFox(b));
    if (has(/Sigenergy/i)) g.push(X.gSig(b));
    if (has(/Lux Power|Volthium/i)) g.push(X.gLux(b));
    if (has(/LONGi/i)) g.push(X.gLongi(b));
    if (has(/JA Solar/i)) g.push(X.gJa(b));
    if (has(/Wall Connector/i)) g.push(X.gWall(b));
    if (has(/\bFLO\b/)) g.push(X.gFlo(b));
    if (has(/Wallbox/i)) g.push(X.gWallbox(b));
    g.push(X.gMo(b));
    const std = M.aBatt || M.aSol;
    const paiement = std
      ? X.paiementStd(b)
      : X.paiementSimple(b);
    const app = X.app[M.marque] || X.app[M.marqueOnd] || null;
    const apres = std
      ? X.apresStd(b, X.suiviQuoi(M.aSol, M.aBatt), app)
      : X.apresSimple;
    const f = calc.financement || {};
    const promo = f.promo && f.monthly > 0 && calc.ttc >= 1000;
    const exemple = calc.ttc >= 1000 && f.monthly > 0
      ? (promo ? X.finPromo(`color:${C.navy};`, f.differe_mois || 3, fmt(f.monthly), fmtTaux(f.taux), f.mois)
        : X.finExemple(`color:${C.navy};`, fmt(f.monthly), f.mois, f.taux ? fmtTaux(f.taux) : "")) : "";
    const nV = M.volets.length;
    const carte = (t, html) => `<div style="${CARTE_MARINE}padding:32px 36px;"><div style="font-weight:700;font-size:29px;color:${C.sky};">${t}</div><div style="font-size:24px;color:${C.s3};line-height:1.55;margin-top:12px;">${html}</div></div>`;
    return diapo("Garanties et modalités", C.navy, `${LIS_MARINE_HAUT}<div style="height:100%;display:flex;flex-direction:column;padding:70px 100px 56px;box-sizing:border-box;">
      ${surtitre(X.garSur, true)}${grandTitre(X.garTitre, true, 60)}
      <div style="flex:1;display:grid;grid-template-columns:1.15fr 1fr 1fr;gap:26px;margin-top:36px;">
        ${carte(X.carteGaranties, g.join("<br>"))}${carte(X.carteModalites, paiement)}${carte(X.carteApres, apres)}
      </div>
      <div style="display:flex;align-items:center;gap:34px;background:#FFF;border-radius:14px;border-left:8px solid ${C.green};padding:26px 40px;margin-top:26px;">
        <img src="${A.financeit}" alt="Financeit" style="width:260px;height:72px;object-fit:contain;flex-shrink:0;">
        <div style="flex:1;font-size:24px;color:${C.g1};line-height:1.5;"><strong style="color:${C.navy};font-size:27px;">${X.financeitTitre}</strong><br>${X.financeitTexte}${exemple}</div>
      </div>
      ${state.notes_client ? `<div style="font-size:22px;color:${C.s3};margin-top:16px;line-height:1.4;"><strong style="color:#FFF;">${X.note}</strong> ${esc(String(state.notes_client).replace(/\s*\n\s*/g, " ")).slice(0, 420)}</div>` : ""}
      <div style="font-size:22px;color:${C.s2};margin-top:16px;line-height:1.4;">${X.conformite(RAYCOM.rbq, nV)}</div>
    </div>`, true);
  }

  function diapoRecap(M, ctx, calc) {
    const s = M.subv;
    const lignes = M.volets.map(v => { const c = contenuVolet(M, v, ctx); return `<div style="display:flex;justify-content:space-between;gap:20px;padding:12px 0;border-bottom:1px solid rgba(127,184,240,.3);" data-recap-ht="${v.ht}"><span>${v.numero ? `<strong style="color:${C.sky};">${v.numero}</strong> · ` : ""}${esc(c.recap)}</span><strong style="white-space:nowrap;">${fmt(v.ht)}</strong></div>`; }).join("");
    const bandeauSub = M.aSol && s.total > 0
      ? `<div style="flex:1;background:rgba(255,201,60,.12);border:1px solid rgba(255,201,60,.55);border-radius:12px;padding:20px 26px;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.yellow};text-transform:uppercase;">${X.subEstimees}</div><div style="${T}font-size:40px;color:${C.yellow};margin-top:6px;">− ${fmt(s.total)}</div><div style="font-size:22px;color:${C.s2};margin-top:4px;">${X.recapLv(fmt(s.logisvert), s.reno > 0 ? fmt0(s.reno) : "", s.autres > 0 ? fmt(s.autres) : "", fmt(M.ttc - s.total))}</div></div>`
      : (M.aBatt && s.reno > 0 ? `<div style="flex:1;background:rgba(255,201,60,.12);border:1px solid rgba(255,201,60,.55);border-radius:12px;padding:20px 26px;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.yellow};text-transform:uppercase;">${X.renoEstime}</div><div style="${T}font-size:40px;color:${C.yellow};margin-top:6px;">${X.jusquaMoins(fmt0(s.reno))}</div><div style="font-size:22px;color:${C.s2};margin-top:4px;">${X.renoSiAdmissible(fmt(M.ttc - s.reno - s.autres))}</div></div>` : "");
    const f = calc.financement || {};
    const fin = calc.ttc >= 1000 && f.monthly > 0 ? `<div style="flex:1;background:rgba(62,207,142,.12);border:1px solid rgba(62,207,142,.6);border-radius:12px;padding:20px 26px;"><div style="font-size:22px;font-weight:700;letter-spacing:2px;color:${C.green};text-transform:uppercase;">${X.finCarte}</div><div style="${T}font-size:40px;color:#FFF;margin-top:6px;">${f.promo ? X.finPromoCourt(f.differe_mois || 3) : X.parMois(fmt(f.monthly))}</div><div style="font-size:22px;color:${C.s3};margin-top:4px;">${f.promo ? X.finPuis(fmt(f.monthly)) : ""}${X.surApprobation}</div></div>` : "";
    return diapo("Récapitulatif et acceptation", C.navy, `${LIS_MARINE_BAS}<div style="height:100%;display:grid;grid-template-columns:1.35fr 1fr;gap:70px;padding:72px 100px 70px;box-sizing:border-box;">
      <div style="display:flex;flex-direction:column;min-width:0;">
        ${surtitre(X.recapSur, true)}${grandTitre(X.recapTitre, true, 56)}
        <div style="margin-top:26px;font-size:27px;color:#FFF;">${lignes}
          <div style="display:flex;justify-content:space-between;align-items:baseline;padding:14px 0;border-bottom:1px solid rgba(127,184,240,.3);color:${C.s3};font-size:30px;"><span style="font-weight:600;">${X.sousTotalAvant}</span><strong style="color:#FFF;${T}font-size:38px;" data-sous-total="${M.ht}">${fmt(M.ht)}</strong></div>
          <div style="display:flex;justify-content:space-between;padding:12px 0;border-bottom:1px solid rgba(127,184,240,.3);color:${C.s3};"><span>${X.tpsTvq}</span><strong style="color:#FFF;">${fmt(calc.taxes)}</strong></div>
          <div style="display:flex;justify-content:space-between;align-items:baseline;gap:20px;padding:20px 0 0;"><span style="${T}font-weight:700;font-size:32px;">${X.projetCompletTICap}</span><span style="${T}font-size:60px;color:${C.sky};white-space:nowrap;" data-ttc="${calc.ttc}">${fmt(calc.ttc)}</span></div>
        </div>
        ${bandeauSub || fin ? `<div style="display:flex;gap:22px;margin-top:34px;">${bandeauSub}${fin}</div>` : ""}
      </div>
      <div style="display:flex;flex-direction:column;background:#FFF;border-radius:16px;padding:40px 46px;">
        <img src="${A.logo}" alt="Raycom Électrique inc." style="width:260px;display:block;">
        <div style="font-size:24px;color:${C.g1};line-height:1.5;margin-top:22px;"><strong style="color:${C.navy};">${X.siege}</strong><br>${RAYCOM.siege}<br><strong style="color:${C.navy};">${X.bureaux}</strong><br>${RAYCOM.entrepot}<br>${RAYCOM.tel} · ${X.texto} ${RAYCOM.texto}<br>${RAYCOM.courriel}<br><span style="color:${C.sky};">${RAYCOM.web}</span></div>
        <div style="flex:1;"></div>
        <div data-rp-lien data-rp-texte="${esc(X.lienEnLigne)}"></div>
        ${/* JF, 7 nov. 2026 : plus de phrase « En signant… » ni de lignes de signature ; l'acceptation se fait en ligne (code QR). */""}
        <div style="font-size:22px;color:${C.g2};margin-top:18px;">${RAYCOM.rbq} · ${X.membreCmeq}</div>
      </div>
    </div>`, true);
  }

  const CSS = `
    @page { size: 1920px 1080px; margin: 0; }
    :root { --s: .5; }
    * { box-sizing: border-box; }
    html, body { margin: 0; }
    body { background: #D9E1EA; font-family: 'Barlow', Arial, sans-serif; -webkit-print-color-adjust: exact; print-color-adjust: exact; -webkit-text-size-adjust: 100%; }
    .toolbar { position: sticky; top: 0; z-index: 5; background: #0C2340; color: #FFF; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 14px; }
    .toolbar button { background: #1568C8; color: #FFF; border: 0; border-radius: 9px; padding: 9px 16px; font-weight: 700; cursor: pointer; font-size: 14px; font-family: inherit; }
    .slide-wrap { position: relative; width: calc(1920px * var(--s)); height: calc(1080px * var(--s)); margin: 16px auto; overflow: hidden; box-shadow: 0 18px 50px rgba(12,35,64,.22); background: #FFF; }
    .slide-wrap > section.slide { position: absolute; left: 0; top: 0; transform: scale(var(--s)); transform-origin: 0 0; }
    @media print {
      html, body { background: #FFF; }
      .toolbar { display: none !important; }
      .slide-wrap { width: 1920px; height: 1080px; margin: 0; box-shadow: none; page-break-after: always; break-after: page; page-break-inside: avoid; break-inside: avoid; }
      .slide-wrap:last-child { page-break-after: auto; break-after: auto; }
      .slide-wrap > section.slide { transform: none; }
    }
  `;
  const ECHELLE = `<script>(function(){function f(){var w=Math.max(320,Math.min((window.innerWidth||1600)-32,1920));document.documentElement.style.setProperty('--s',String(w/1920));}f();window.addEventListener('resize',f);})();</script>`;

  function html(state, calc) {
    state = state || {};
    appliquerLangue(state);
    const c = state.client || {}, sol = state.solaire || {};
    const adresse = (c.address_civic || c.address_street || c.address_city)
      ? [c.address_civic, c.address_street].filter(Boolean).join(" ") + (c.address_city ? `, ${c.address_city}` : "") + (c.address_postal ? ` ${c.address_postal}` : "")
      : (c.address_full || "");
    const num = state.qbo_doc_number || state.quote_id || X.brouillon;
    const M = modele(state, calc);
    const ctx = { nom: c.name || "", adresse, num, date: dateFR(state.created_at), mois: dateFR(state.created_at, { month: "long", year: "numeric" }), sol, panneaux: calc.panneaux || 0, production: calc.production || 0 };
    const d = [];
    VUS = new Set();
    GRAINE = graineDe(state.quote_id || state.submission_id || c.name || num);
    // Ordre de calcul : titre, technologie et volets (photos de produit imposées) d'abord, puis Raycom et réalisations
    // choisissent parmi les photos pas encore montrées. L'ordre des diapos reste le même.
    const titre = diapoTitre(M, ctx);
    const techno = diapoTechnologie(M);
    const volets = M.volets.map(v => diapoVolet(M, v, ctx));
    const raycom = diapoRaycom(M);
    const photos = photosRealisations(M);
    d.push(titre);
    d.push(raycom);
    if (photos.length >= 2) d.push(diapoRealisations(M, photos));
    if (techno) d.push(techno);
    for (const v of volets) d.push(v);
    if (M.aBatt && !M.aSol) d.push(diapoSecours(M));
    if (M.aSol && M.vSol) d.push(diapoSubventions(M, ctx, state));
    if (M.rendement && M.vSol) d.push(diapoRendement(M, ctx));
    d.push(diapoEtapes(M));
    d.push(diapoGaranties(M, ctx, state, calc));
    d.push(diapoRecap(M, ctx, calc));
    const out = `<!doctype html><html lang="${X.htmlLang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${X.propositionNo(esc(num))}${c.name ? ` · ${esc(c.name)}` : ""}</title><link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700&family=Barlow+Semi+Condensed:wght@600;700;800&display=swap" rel="stylesheet"><style>${CSS}</style>${ECHELLE}</head><body data-gabarit="${M.gabarit}"><div class="toolbar noprint"><span>${X.propositionNo(esc(num))} · ${d.length} ${X.diapositives} · ${X.apercu}</span><button onclick="window.print()">${X.imprimer}</button></div>${d.join("")}</body></html>`;
    return out.replace(/\u2014/g, ",");
  }

  /** Convertit les images relatives (assets/…) en data: pour le rendu PDF côté worker. */
  const cacheData = new Map();
  async function toDataUrl(src) {
    if (cacheData.has(src)) return cacheData.get(src);
    const p = (async () => {
      try {
        const r = await fetch(src); if (!r.ok) throw new Error(r.status);
        const b = await r.blob();
        return await new Promise((res, rej) => { const fr = new FileReader(); fr.onload = () => res(fr.result); fr.onerror = rej; fr.readAsDataURL(b); });
      } catch (e) { console.warn("[proposition] image non intégrée", src, e); return src; }
    })();
    cacheData.set(src, p); return p;
  }
  async function htmlInline(state, calc) {
    let out = html(state, calc);
    const refs = Array.from(new Set((out.match(/(?:src="|url\()(assets\/[^")]+)/g) || []).map(m => m.replace(/^(src="|url\()/, ""))));
    for (const src of refs) { const d = await toDataUrl(src); out = out.split(`src="${src}"`).join(`src="${d}"`).split(`url(${src})`).join(`url(${d})`); }
    return out;
  }

  function ouvrir(state, calc) {
    const w = window.open("", "_blank");
    if (!w) { alert("Le navigateur a bloqué l'ouverture de l'aperçu. Autorise les fenêtres pop-up pour Raycast."); return; }
    const base = `<base href="${location.origin}${location.pathname.replace(/[^/]*$/, "")}">`;
    w.document.open(); w.document.write(html(state, calc).replace("<head>", "<head>" + base)); w.document.close();
  }

  window.PropositionRE = { html, htmlInline, ouvrir, modele, langue: langueDe, TEXTES: TXT };
})();
