// configurator.jsx — Colonne gauche : sections 1-10 du configurateur.

const Configurator = ({ state, setState, calc, viewMode }) => {
  const { fmtCAD, fmtCAD0, fmtPct } = window.RAYCAST_CALC;
  const { client, solar, project_type, building_type, ve, options } = state;
  const setClient = (k, v) => setState({ ...state, client: { ...client, [k]: v } });
  const setSolar = (patch) => setState({ ...state, solar: { ...solar, ...patch } });
  const setVe = (newVe) => setState({ ...state, ve: newVe });
  const setOptions = (newOpts) => setState({ ...state, options: newOpts });

  const bldg = window.RAYCOM_DATA.building_types.find(b => b.key === building_type);
  const hasSolar = project_type === "solaire" || project_type === "solaire_batterie";
  const hasBattery = (project_type === "solaire_batterie" && solar.battery_brand !== "none") || project_type === "batterie";
  const isBorne = project_type === "borne";

  // Adresse structurée — détection auto via code postal
  const fullAddress = [
    client.address_civic,
    client.address_apt ? `apt. ${client.address_apt}` : null,
    client.address_street,
    client.address_city,
    client.address_province || "QC",
    client.address_postal
  ].filter(Boolean).join(" ").trim();

  // Validation code postal QC (G/H/J)
  const postalClean = (client.address_postal || "").toUpperCase().replace(/\s+/g, "");
  const postalRegex = /^([GHJ]\d[A-Z])(\d[A-Z]\d)$/;
  const postalMatch = postalClean.match(postalRegex);
  const postalOk = postalMatch !== null;

  // Détection région + zone par préfixe code postal (3 chars puis 2)
  const detected = React.useMemo(() => {
    if (!postalOk) return null;
    const D = window.RAYCOM_DATA;
    const p3 = postalMatch[1]; // ex "J7K"
    const p2 = p3.slice(0, 2); // ex "J7"
    return D.address_lookup.find(x => x.prefix === p3)
        || D.address_lookup.find(x => x.prefix.length === 2 && x.prefix === p2)
        || null;
  }, [postalClean]);

  // Auto-set region_id quand le code postal change
  React.useEffect(() => {
    if (detected && detected.region_id !== client.region_id) {
      setClient("region_id", detected.region_id);
    }
  }, [detected?.region_id]);

  const detectedRegion = detected ? window.RAYCOM_DATA.regions.find(r => r.key === detected.region_id) : null;
  const detectedZone = detected ? window.RAYCOM_DATA.zones.find(z => z.key === detected.zone) : null;

  // Synchroniser project_address (string concat) pour QuotePreview
  React.useEffect(() => {
    if (fullAddress !== client.project_address) {
      setClient("project_address", fullAddress);
    }
  }, [fullAddress]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* === Section 1 — Client === */}
      <SectionBlock num="1" title="Informations client" sub="Coordonnées et adresse du projet">
        {window.ClientPickerButton && (
          <div style={{ marginBottom: 12 }}>
            <ClientPickerButton onPick={(c) => window.RAYCAST_PICK_CLIENT?.(c)}/>
          </div>
        )}
        <div className="grid2">
          <label className="field">
            <span className="lbl">Nom complet<span className="req">*</span></span>
            <input className="input" value={client.name} onChange={(e) => setClient("name", e.target.value)} placeholder="Marie Bouchard"/>
          </label>
          <label className="field">
            <span className="lbl">Téléphone<span className="req">*</span></span>
            <input className="input" value={client.phone} onChange={(e) => setClient("phone", e.target.value)} placeholder="514 555-0124"/>
          </label>
          <label className="field">
            <span className="lbl">Courriel</span>
            <input className="input" value={client.email} onChange={(e) => setClient("email", e.target.value)} placeholder="marie@exemple.ca"/>
          </label>
          <label className="field">
            <span className="lbl">Source du lead</span>
            <select className="select" value={client.source} onChange={(e) => setClient("source", e.target.value)}>
              {window.RAYCOM_DATA.lead_sources.map(s => <option key={s}>{s}</option>)}
            </select>
          </label>
          <div className="col-span-2" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ display: "grid", gridTemplateColumns: "90px 80px 1fr", gap: 10 }}>
              <label className="field">
                <span className="lbl">N° civique<span className="req">*</span></span>
                <input className="input" value={client.address_civic} onChange={(e) => setClient("address_civic", e.target.value)} placeholder="127"/>
              </label>
              <label className="field">
                <span className="lbl">App.</span>
                <input className="input" value={client.address_apt} onChange={(e) => setClient("address_apt", e.target.value)} placeholder="2"/>
              </label>
              <label className="field">
                <span className="lbl">Rue<span className="req">*</span></span>
                <input className="input" value={client.address_street} onChange={(e) => setClient("address_street", e.target.value)} placeholder="rue des Cèdres" list="qc-streets"/>
              </label>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 90px 130px", gap: 10 }}>
              <label className="field">
                <span className="lbl">Ville<span className="req">*</span></span>
                <input className="input" value={client.address_city} onChange={(e) => setClient("address_city", e.target.value)} placeholder="Mascouche" list="qc-cities"/>
                <datalist id="qc-cities">
                  {Array.from(new Set(window.RAYCOM_DATA.address_lookup.map(x => x.city))).map(c => <option key={c} value={c}/>)}
                </datalist>
              </label>
              <label className="field">
                <span className="lbl">Province</span>
                <select className="select" value={client.address_province || "QC"} onChange={(e) => setClient("address_province", e.target.value)}>
                  <option value="QC">QC</option>
                  <option value="ON">ON</option>
                  <option value="NB">NB</option>
                </select>
              </label>
              <label className="field">
                <span className="lbl">Code postal<span className="req">*</span>
                  {client.address_postal && (
                    <span style={{ marginLeft: 6, fontSize: 10, color: postalOk ? "var(--raycom-energy)" : "var(--margin-yellow)", fontWeight: 600 }}>
                      {postalOk ? "✓" : "⚠"}
                    </span>
                  )}
                </span>
                <input
                  className="input mono"
                  style={{ textTransform: "uppercase" }}
                  value={client.address_postal}
                  onChange={(e) => {
                    let v = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, "");
                    if (v.length > 3) v = v.slice(0,3) + " " + v.slice(3,6);
                    setClient("address_postal", v);
                  }}
                  placeholder="J7K 0K3"
                  maxLength="7"
                />
              </label>
            </div>
            {detected ? (
              <div style={{
                display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center",
                fontSize: 11.5, color: "var(--raycom-ink-muted)", padding: "8px 12px",
                background: "var(--raycom-accent-dim)", borderRadius: 9, border: "1px solid rgba(26,111,196,0.15)"
              }}>
                <Icon name="check-circle" size={13} color="var(--raycom-accent-dark)"/>
                <span><b style={{ color: "var(--raycom-accent-dark)" }}>Détection automatique :</b></span>
                <Badge kind="blue">📍 {detected.city}</Badge>
                <Badge kind="blue">☀ {detectedRegion?.label} · {detectedRegion?.kwh_per_kw} kWh/kW/an</Badge>
                <Badge kind={detected.zone === "Z1" ? "green" : detected.zone === "Z5" ? "amber" : "blue"}>
                  🚚 Zone {detected.zone} {detectedZone && detectedZone.sell > 0 ? `(+${detectedZone.sell} $)` : "(inclus)"}
                </Badge>
              </div>
            ) : client.address_postal ? (
              <div style={{
                fontSize: 11, color: "var(--margin-yellow)", padding: "6px 10px",
                background: "rgba(217,119,6,0.06)", borderRadius: 8,
                display: "flex", gap: 6, alignItems: "center"
              }}>
                <Icon name="alert-triangle" size={12}/>
                Code postal non reconnu — vérifier (doit commencer par G, H ou J pour le Québec).
              </div>
            ) : null}
            <datalist id="qc-streets">
              <option value="rue Principale"/>
              <option value="boulevard des Seigneurs"/>
              <option value="rue de la Gare"/>
              <option value="avenue du Parc"/>
              <option value="rang Saint-Joseph"/>
            </datalist>
          </div>
          <label className="field col-span-2">
            <span className="lbl">Type de bâtiment</span>
            <select className="select" value={building_type} onChange={(e) => setState({ ...state, building_type: e.target.value })}>
              {window.RAYCOM_DATA.building_types.map(b => (
                <option key={b.key} value={b.key}>{b.label}</option>
              ))}
            </select>
          </label>
        </div>
      </SectionBlock>

      {/* === Section 2 — Type de projet === */}
      <SectionBlock num="2" title="Type de projet" sub="Choisissez la nature du système">
        <div className="grid4">
          {[
            { key: "solaire", title: "Solaire", sub: "Sans batterie", icon: "sun" },
            { key: "solaire_batterie", title: "Solaire + Batterie", sub: "Hybride", icon: "battery" },
            { key: "batterie", title: "Batterie seule", sub: "Tesla / Fox / Sig", icon: "zap" },
            { key: "borne", title: "Borne VÉ", sub: "Niveau 2 / DCC", icon: "plug" }
          ].map(c => (
            <PickerCard
              key={c.key}
              active={project_type === c.key}
              onClick={() => setState({ ...state, project_type: c.key })}
              icon={c.icon}
              title={c.title}
              sub={c.sub}
            />
          ))}
        </div>
      </SectionBlock>

      {/* === Section 3 — Configuration solaire === */}
      {hasSolar && (
        <SectionBlock
          num="3"
          title="Configuration solaire"
          sub={`${solar.kw} kW · ${Math.ceil(solar.kw * 2)} × panneaux Thornova TS-BB66 All Black 500 W bifacial${solar.kw > 20 ? " · ⚠ au-delà du plafond mesurage net 20 kW" : ""}`}
        >
          <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
            {/* Slider kW */}
            <RCSlider
              label="Puissance installée"
              value={solar.kw}
              min={3} max={Math.max(40, bldg.kw_max)}
              step={0.5}
              suffix=" kW"
              onChange={(v) => setSolar({ kw: v })}
              hint={<><span>{Math.ceil(solar.kw * 2)} × Thornova TS-BB66 500 W bifacial</span><span>{(solar.kw * 1).toFixed(1).replace(".", ",")} kW DC</span></>}
              warn={solar.kw > 20 && building_type !== "com_grand" && building_type !== "com_moyen" ? "Au-delà du plafond mesurage net résidentiel (20 kW)" : null}
              ticks={["3 kW", "10 kW", "20 kW", "30 kW", "40 kW"]}
            />

            {/* Pente + étages (caché si toit plat) */}
            {(() => {
              const roof = window.RAYCOM_DATA.roof_types.find(r => r.key === solar.roof_type);
              if (roof?.flat) {
                return <div style={{ fontSize: 11.5, fontStyle: "italic", color: "var(--raycom-ink-muted)" }}>Toiture plate — pente et étages cosmétiques.</div>;
              }
              return (
                <div className="grid2">
                  <RCSlider
                    label="Pente du toit (sur 12)"
                    value={solar.slope}
                    min={0} max={12}
                    onChange={(v) => setSolar({ slope: v })}
                    hint={<><span>{solar.slope}/12 ({Math.round(Math.atan(solar.slope/12) * 180 / Math.PI)}°)</span><span/></>}
                  />
                  <RCSlider
                    label="Nombre d'étages"
                    value={solar.floors}
                    min={1} max={6}
                    onChange={(v) => setSolar({ floors: v })}
                    warn={solar.floors > 2 ? "Surcharge installation au-delà de 2 étages" : null}
                  />
                </div>
              );
            })()}

            {/* Toiture */}
            <div>
              <div className="cap" style={{ marginBottom: 8 }}>Type de toiture</div>
              <RoofPicker value={solar.roof_type} onChange={(v) => setSolar({ roof_type: v })}/>
            </div>

            {/* Marque batterie (si solaire+batterie ou solaire avec choix) */}
            {project_type === "solaire_batterie" && (
              <div>
                <div className="cap" style={{ marginBottom: 8 }}>Marque batterie (3 × 2)</div>
                <BatteryBrandPicker
                  value={solar.battery_brand}
                  onChange={(b) => {
                    const firstPack = window.RAYCOM_DATA.battery_packs[b]?.[0];
                    const newBackup = b === "none" ? "none" : (solar.backup_mode === "none" ? "partial" : solar.backup_mode);
                    setSolar({ battery_brand: b, battery_preset_id: firstPack?.id, with_v2x: firstPack?.v2x || false, backup_mode: newBackup });
                  }}
                />
              </div>
            )}

            {/* Packs batterie */}
            {project_type === "solaire_batterie" && solar.battery_brand !== "none" && solar.battery_brand !== "other" && (
              <BatteryPackSelector
                brand={solar.battery_brand}
                value={solar.battery_preset_id}
                onChange={(id) => {
                  const pack = window.RAYCOM_DATA.battery_packs[solar.battery_brand].find(p => p.id === id);
                  setSolar({ battery_preset_id: id, with_v2x: pack?.v2x || false });
                }}
                viewMode={viewMode}
              />
            )}

            {/* Ecosystem comparison */}
            {project_type === "solaire_batterie" && ["tesla", "fox", "sig"].includes(solar.battery_brand) && solar.battery_preset_id && (() => {
              const pack = window.RAYCAST_CALC.lookupBatteryPack(solar.battery_brand, solar.battery_preset_id);
              if (!pack || pack.kwh < 5) return null;
              return (
                <EcosystemComparison
                  currentBrand={solar.battery_brand}
                  targetKwh={pack.kwh}
                  viewMode={viewMode}
                  onSwitch={(b, pid) => setSolar({ battery_brand: b, battery_preset_id: pid })}
                />
              );
            })()}

            {/* Entrée service + backup */}
            {project_type === "solaire_batterie" && solar.battery_brand !== "none" && (
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <div className="cap">Entrée de service</div>
                  <select className="select" style={{ width: 140 }} value={solar.service_amperage} onChange={(e) => setSolar({ service_amperage: parseInt(e.target.value) })}>
                    {window.RAYCOM_DATA.service_options.map(a => <option key={a} value={a}>{a} A</option>)}
                  </select>
                </div>
                <BackupModePicker
                  value={solar.backup_mode}
                  onChange={(v) => setSolar({ backup_mode: v })}
                  serviceAmperage={solar.service_amperage}
                  viewMode={viewMode}
                  hasBattery={true}
                />
              </div>
            )}

            {/* Live preview */}
            <div className="live-preview">
              <div className="row">
                <span className="k">Prix vente HT estimé</span>
                <span className="v">{fmtCAD0(calc.ht)}</span>
              </div>
              <div className="row">
                <span className="k">Taux $/W vente</span>
                <span className="v">{fmtCAD(calc.ht / (solar.kw * 1000), 2)}/W</span>
              </div>
              {viewMode === "internal" && calc.costs.forfait && (
                <>
                  <div className="row">
                    <span className="k">Forfait Larks v16</span>
                    <span className="v mono">{calc.costs.forfait.code}</span>
                  </div>
                  <div className="row">
                    <span className="k">Coût / Vendant forfait</span>
                    <span className="v">{fmtCAD0(calc.costs.forfait.cost_total)} / {fmtCAD0(calc.costs.forfait.sell_total)}</span>
                  </div>
                  {calc.zone && calc.zone.sell > 0 && (
                    <div className="row">
                      <span className="k">Déplacement {calc.zone.key}</span>
                      <span className="v">{fmtCAD0(calc.zone.sell)}</span>
                    </div>
                  )}
                </>
              )}
            </div>

            {viewMode === "internal" && calc.costs.forfait && (
              <div className="hint">
                <Icon name="info" size={14}/>
                <div>
                  <b>Configuration détectée :</b> {solar.kw} kW ({calc.costs.panel_count} × {window.RAYCOM_DATA.panel_ref.watts} W) · {calc.costs.onds || 1} onduleur{(calc.costs.onds || 1) > 1 ? "s" : ""} → forfait <b>{calc.costs.forfait.label}</b> ({calc.costs.forfait.code}). {calc.costs.forfait.larks_eligible ? "Solaire Larks ; install électrique Raycom." : "Raycom direct (toit plat ou commercial)."}
                </div>
              </div>
            )}
          </div>
        </SectionBlock>
      )}

      {/* === Section 3-bis — Batterie seule === */}
      {project_type === "batterie" && (
        <SectionBlock num="3" title="Configuration batterie seule" sub="Stockage sans solaire — peak shaving, secours panne">
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <BatteryBrandPicker
              value={solar.battery_brand}
              onChange={(b) => {
                const firstPack = window.RAYCOM_DATA.battery_packs[b]?.[0];
                setSolar({ battery_brand: b, battery_preset_id: firstPack?.id });
              }}
              filter={(b) => ["tesla", "fox", "sig", "solark"].includes(b.key)}
            />
            {solar.battery_brand !== "none" && (
              <BatteryPackSelector
                brand={solar.battery_brand}
                value={solar.battery_preset_id}
                onChange={(id) => setSolar({ battery_preset_id: id })}
                viewMode={viewMode}
              />
            )}
            <div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                <div className="cap">Entrée de service</div>
                <select className="select" style={{ width: 140 }} value={solar.service_amperage} onChange={(e) => setSolar({ service_amperage: parseInt(e.target.value) })}>
                  {window.RAYCOM_DATA.service_options.map(a => <option key={a} value={a}>{a} A</option>)}
                </select>
              </div>
              <BackupModePicker
                value={solar.backup_mode}
                onChange={(v) => setSolar({ backup_mode: v })}
                serviceAmperage={solar.service_amperage}
                viewMode={viewMode}
                hasBattery={true}
              />
            </div>
            <div className="hint">
              <Icon name="sparkles" size={14}/>
              <div>
                <b>Argument client :</b> protection en panne (autonomie {calc.autonomy_days.toFixed(1).replace(".", ",")} j en mode éco), peak shaving Flex D/DP (économies en heures de pointe jusqu'à 50 ¢/kWh), prêt pour ajout solaire futur.
              </div>
            </div>
          </div>
        </SectionBlock>
      )}

      {/* === Section 3-ter — Borne VÉ === */}
      {isBorne && (
        <SectionBlock num="3" title="Configuration borne VÉ" sub="Niveau 2 résidentiel ou multilogement">
          <EvChargerSection ve={ve} setVe={setVe} viewMode={viewMode} building={building_type}/>
        </SectionBlock>
      )}

      {/* === Section 4 — Profil énergétique === */}
      {hasSolar && (
        <SectionBlock num="4" title="Profil énergétique" sub="Région, orientation, tarif HQ, consommation actuelle">
          <div className="grid2">
            <label className="field">
              <span className="lbl">Région QC</span>
              <select className="select" value={client.region_id} onChange={(e) => setClient("region_id", e.target.value)}>
                {window.RAYCOM_DATA.regions.map(r => <option key={r.key} value={r.key}>{r.label} · {r.kwh_per_kw} kWh/kW/an</option>)}
              </select>
            </label>
            <label className="field">
              <span className="lbl">Orientation principale</span>
              <select className="select" value={client.orientation} onChange={(e) => setClient("orientation", e.target.value)}>
                {["S", "SE", "SO", "E", "O", "NE", "NO", "N"].map(o => <option key={o}>{o}</option>)}
              </select>
            </label>
            <label className="field col-span-2">
              <span className="lbl">Tarif HQ actuel</span>
              <select className="select" value={client.hq_tariff} onChange={(e) => setClient("hq_tariff", e.target.value)}>
                {window.RAYCOM_DATA.hq_tariffs.map(t => <option key={t.id} value={t.id}>{t.label} · {t.rate.toFixed(2).replace(".", ",")} ¢/kWh</option>)}
              </select>
            </label>
            <label className="field">
              <span className="lbl">Mode saisie facture</span>
              <SegmentedToggle
                value={client.bill_input_mode}
                options={[{ value: "dollars", label: "$/an" }, { value: "kwh", label: "kWh/an" }]}
                onChange={(v) => setClient("bill_input_mode", v)}
              />
            </label>
            <label className="field">
              <span className="lbl">{client.bill_input_mode === "dollars" ? "Facture HQ annuelle ($)" : "Consommation annuelle (kWh)"}</span>
              <input
                className="input tnum"
                type="number"
                value={client.bill_input_mode === "dollars" ? client.annual_hq_bill : client.annual_hq_kwh}
                onChange={(e) => setClient(client.bill_input_mode === "dollars" ? "annual_hq_bill" : "annual_hq_kwh", parseFloat(e.target.value) || 0)}
              />
            </label>
            <label className="field">
              <span className="lbl">Km / an du VÉ</span>
              <input className="input tnum" type="number" value={client.ev_km_per_year} onChange={(e) => setClient("ev_km_per_year", parseFloat(e.target.value) || 0)}/>
            </label>
            <label className="field">
              <span className="lbl">kWh / 100 km</span>
              <input className="input tnum" type="number" step="0.1" value={client.ev_kwh_per_100km} onChange={(e) => setClient("ev_kwh_per_100km", parseFloat(e.target.value) || 0)}/>
            </label>
          </div>
        </SectionBlock>
      )}

      {/* === Section 5 — Options === */}
      {hasSolar && (
        <SectionBlock num="5" title="Options solaires" sub="Ajouts hors forfait standard">
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {window.RAYCOM_DATA.options_solaire.map(opt => {
              const checked = (options || []).some(o => o.id === opt.id);
              return (
                <label key={opt.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 8, background: checked ? "var(--raycom-accent-dim)" : "transparent", border: "1px solid " + (checked ? "rgba(26,111,196,0.18)" : "var(--raycom-border)"), cursor: "default" }}>
                  <input
                    type="checkbox"
                    checked={checked}
                    onChange={(e) => {
                      if (e.target.checked) setOptions([...(options || []), opt]);
                      else setOptions((options || []).filter(o => o.id !== opt.id));
                    }}
                    style={{ accentColor: "var(--raycom-accent)" }}
                  />
                  <span style={{ flex: 1, fontSize: 12.5 }}>{opt.label}</span>
                  {viewMode === "internal" && (
                    <span style={{ fontSize: 11, color: "var(--raycom-ink-dim)", fontVariantNumeric: "tabular-nums" }}>
                      coût {fmtCAD0(opt.cost)} → vente {fmtCAD0(opt.sell)}
                    </span>
                  )}
                  {viewMode === "client" && (
                    <span style={{ fontSize: 12, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
                      {fmtCAD0(opt.sell)}
                    </span>
                  )}
                </label>
              );
            })}
          </div>
        </SectionBlock>
      )}

      {/* === Section 6 — Financement === */}
      <SectionBlock num="6" title="Financement" sub="Choix du mode de paiement">
        {(() => {
          const isComptant = client.financing_plan_id === "comptant";
          return (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {/* Étape 1 : Comptant vs Financement */}
              <div>
                <div className="cap" style={{ marginBottom: 8 }}>Étape 1 — Mode de paiement</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div
                    className={`pcard ${isComptant ? "active" : ""}`}
                    onClick={() => setClient("financing_plan_id", "comptant")}
                  >
                    <div className="pcard-icon"><Icon name="coins" size={16}/></div>
                    <div className="pcard-title">Comptant</div>
                    <div className="pcard-sub">Paiement en 3 versements (dépôt 1 000 $, approbation HQ, mise en service)</div>
                  </div>
                  <div
                    className={`pcard ${!isComptant ? "active" : ""}`}
                    onClick={() => {
                      if (isComptant) setClient("financing_plan_id", "240m"); // défaut populaire
                    }}
                  >
                    <div className="pcard-icon"><Icon name="receipt" size={16}/></div>
                    <div className="pcard-title">Financement Financeit</div>
                    <div className="pcard-sub">Plans mensualisés · sans frais marchand sur le crédit standard</div>
                  </div>
                </div>
              </div>

              {/* Étape 2 : Choix du plan (uniquement si financement) */}
              {!isComptant && (
                <div>
                  <div className="cap" style={{ marginBottom: 8 }}>Étape 2 — Plan choisi</div>
                  <label className="field">
                    <select
                      className="select"
                      value={client.financing_plan_id}
                      onChange={(e) => setClient("financing_plan_id", e.target.value)}
                    >
                      {(() => {
                        const plans = window.RAYCOM_DATA.financeit_plans.filter(p => p.id !== "comptant");
                        const byCat = {};
                        plans.forEach(p => {
                          const cat = p.popular ? "★ Populaires" : (p.category || "Autres");
                          (byCat[cat] = byCat[cat] || []).push(p);
                        });
                        const order = ["★ Populaires", "Standard", "Promo sans paiement", "Rachat de taux", "Autres"];
                        return order.filter(c => byCat[c]).map(cat => (
                          <optgroup key={cat} label={cat}>
                            {byCat[cat].map(p => (
                              <option key={p.id} value={p.id}>
                                {p.label}{viewMode === "internal" && p.fee_pct > 0 ? ` · frais marchand ${p.fee_pct.toFixed(2).replace(".",",")} %` : ""}
                              </option>
                            ))}
                          </optgroup>
                        ));
                      })()}
                    </select>
                  </label>
                  {(() => {
                    const p = window.RAYCOM_DATA.financeit_plans.find(x => x.id === client.financing_plan_id);
                    if (!p) return null;
                    return (
                      <div style={{ marginTop: 10, padding: "10px 12px", borderRadius: 8, background: "var(--raycom-accent-dim)", border: "1px solid rgba(26,111,196,0.15)", display: "grid", gridTemplateColumns: "auto 1fr", gap: 8, fontSize: 12 }}>
                        <Icon name="info" size={13} color="var(--raycom-accent-dark)"/>
                        <div style={{ color: "var(--raycom-ink)" }}>
                          <b>{p.label}</b>{" — "}
                          {p.fee_pct > 0
                            ? `Promo client : ${p.apr === 0 ? "0 % d'intérêt" : "rachat de taux"}. ${viewMode === "internal" ? `Frais marchand ${p.fee_pct.toFixed(2).replace(".",",")} % prélevés sur Raycom.` : ""}`
                            : "Crédit standard Financeit Québec — taux de base 4,45 % + 8,54 % = 12,99 %. Sans frais marchand."
                          }
                        </div>
                      </div>
                    );
                  })()}
                </div>
              )}

              {/* Aperçu paiement (si financement) */}
              {calc.fin.monthly > 0 && (
                <div className="live-preview">
                  <div className="row"><span className="k">Mensualité</span><span className="v">{fmtCAD(calc.fin.monthly)}</span></div>
                  <div className="row"><span className="k">Bimensuel</span><span className="v">{fmtCAD(calc.fin.biweekly)}</span></div>
                  <div className="row"><span className="k">Hebdomadaire</span><span className="v">{fmtCAD(calc.fin.weekly)}</span></div>
                  <div className="row"><span className="k">Intérêt total payé par le client</span><span className="v">{fmtCAD0(calc.fin.total_interest)}</span></div>
                  {viewMode === "internal" && calc.fin.fee > 0 && (
                    <div className="row"><span className="k" style={{ color: "var(--margin-yellow)" }}>Frais marchand (impact marge)</span><span className="v" style={{ color: "var(--margin-yellow)" }}>−{fmtCAD0(calc.fin.fee)}</span></div>
                  )}
                </div>
              )}
            </div>
          );
        })()}
      </SectionBlock>

      {/* === Section 10 — Sommaire financier (interne) === */}
      {viewMode === "internal" && (
        <SectionBlock num="10" title="Sommaire financier interne" sub="Décomposition coûts → marge → commission">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 12 }}>
            {hasSolar && (
              <div style={{ background: "rgba(217,119,6,0.06)", borderRadius: 8, padding: 10 }}>
                <div className="cap">🌞 Solaire</div>
                <div className="tnum" style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{fmtCAD0(calc.costs.solar)}</div>
              </div>
            )}
            {(hasBattery || hasSolar) && (
              <div style={{ background: "rgba(26,111,196,0.06)", borderRadius: 8, padding: 10 }}>
                <div className="cap">🔌 Onduleur / AIO</div>
                <div className="tnum" style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{fmtCAD0(calc.costs.inverter)}</div>
              </div>
            )}
            {hasBattery && (
              <div style={{ background: "rgba(124,58,237,0.06)", borderRadius: 8, padding: 10 }}>
                <div className="cap">🔋 Batteries</div>
                <div className="tnum" style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{fmtCAD0(calc.costs.batteries)}</div>
              </div>
            )}
            <div style={{ background: "rgba(5,150,105,0.06)", borderRadius: 8, padding: 10 }}>
              <div className="cap">🛠 Install Raycom</div>
              <div className="tnum" style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{fmtCAD0(calc.costs.install + (calc.costs.backup_extra || 0) + (calc.costs.wiring || 0))}</div>
              {calc.costs.forfait && <div className="dim mono" style={{ marginTop: 2 }}>{calc.costs.forfait.code}</div>}
            </div>
          </div>
          <div className="totals">
            <span className="lbl">Coût total</span><span className="val">{fmtCAD(calc.cost_total)}</span>
            <span className="lbl">Prix vente HT</span><span className="val">{fmtCAD(calc.ht)}</span>
            <span className="lbl">TPS 5,000 %</span><span className="val">{fmtCAD(calc.tps)}</span>
            <span className="lbl">TVQ 9,975 %</span><span className="val">{fmtCAD(calc.tvq)}</span>
            <span className="grand-lbl">Total TTC</span><span className="grand tnum">{fmtCAD(calc.ttc)}</span>
          </div>
          <div className="hr"/>
          <div className="totals">
            <span className="lbl">Marge brute</span>
            <span className={`val tnum m-${window.RAYCAST_CALC.margeColor(calc.marge_pct, building_type)}`}>
              {fmtCAD(calc.marge_brute)} · {fmtPct(calc.marge_pct)}
            </span>
            {calc.fin.fee > 0 && (
              <>
                <span className="lbl">Frais marchand Financeit</span>
                <span className="val tnum" style={{ color: "var(--margin-yellow)" }}>−{fmtCAD(calc.fin.fee)}</span>
                <span className="lbl">Marge ajustée</span>
                <span className={`val tnum m-${window.RAYCAST_CALC.margeColor(calc.marge_aj_pct, building_type)}`}>
                  {fmtCAD(calc.marge_ajustee)} · {fmtPct(calc.marge_aj_pct)}
                </span>
              </>
            )}
            <span className="lbl">Commission Marc-André ({calc.com.label} · {fmtPct(calc.com.rate, 1)})</span>
            <span className="val tnum" style={{ color: "var(--raycom-accent-dark)", fontWeight: 700 }}>{fmtCAD(calc.commission)}</span>
          </div>
        </SectionBlock>
      )}
    </div>
  );
};

window.Configurator = Configurator;
