// preview.jsx — QuotePreview central : document façon PDF papier.

const QuotePreview = ({ state, calc, viewMode }) => {
  const { fmtCAD, fmtCAD0, fmtPct, fmtNum } = window.RAYCAST_CALC;
  const { client, solar, project_type, building_type, ve, options, quote_id, created_at } = state;
  const bldg = window.RAYCOM_DATA.building_types.find(b => b.key === building_type);
  const roof = window.RAYCOM_DATA.roof_types.find(r => r.key === solar.roof_type);
  const pack = window.RAYCAST_CALC.lookupBatteryPack(solar.battery_brand, solar.battery_preset_id);
  const brand = window.RAYCOM_DATA.battery_brands.find(b => b.key === solar.battery_brand);
  const tariff = window.RAYCOM_DATA.hq_tariffs.find(t => t.id === client.hq_tariff);
  const fin = window.RAYCOM_DATA.financeit_plans.find(p => p.id === client.financing_plan_id);
  const isBorne = project_type === "borne";
  const isBatt = project_type === "batterie";
  const hasSolar = project_type === "solaire" || project_type === "solaire_batterie";
  const hasBattery = (project_type === "solaire_batterie" && solar.battery_brand !== "none") || project_type === "batterie";
  const internal = viewMode === "internal";

  // Scope narratif
  let scope;
  if (hasSolar) {
    scope = `Installation d'un système solaire photovoltaïque de ${solar.kw.toFixed(1).replace(".", ",")} kW DC (${Math.ceil(solar.kw * 2)} panneaux de 500 W)`;
    if (hasBattery && pack) scope += ` avec stockage ${pack.kwh.toFixed(1).replace(".", ",")} kWh (${brand.name})`;
    scope += `. Inclut câblage DC/AC, sectionneurs, ingénierie scellée OIQ, schéma unifilaire E.12-07, démarches Hydro-Québec mesurage net et mise en service.`;
  } else if (isBatt) {
    scope = `Installation d'un système de stockage ${brand?.name || ""} de ${pack?.kwh.toFixed(1).replace(".", ",") || ""} kWh avec onduleur hybride ${pack?.kw_inv || ""} kW. Inclut Gateway/Hub DIM HQ, configuration backup ${solar.backup_mode === "whole_home" ? "complet" : solar.backup_mode === "partial" ? "charges critiques" : "mesurage net"}, mise en service et formation.`;
  } else {
    const list = ve.bornes_selected || [];
    const qty = list.reduce((s, x) => s + x.qty, 0);
    scope = `Installation de ${qty} borne${qty > 1 ? "s" : ""} de recharge VÉ niveau 2 ${ve.scenario_post_2018 ? "(préfilage 2018+ réutilisé)" : "(fil neuf complet)"}, ${ve.dcc_option === "dcc12" ? "avec DCC-12 RVE pour éviter la hausse de service" : ve.dcc_option === "dsdc" ? "avec Tesla DSDC Remote Meter" : "sans DCC"}. Inclut conduit, disjoncteur dédié, mise à la terre, mise en service.`;
  }

  // Table de composants
  const lineItems = buildLineItems({ state, calc, internal });

  return (
    <div className="qp shadow-premium-lg">
      {/* Header */}
      <div className="qp-header">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
          <RaycomLogo size={42}/>
          <div style={{ textAlign: "right" }}>
            <div className="doc-title">Soumission</div>
            <div className="doc-no">{quote_id}</div>
            <div className="meta" style={{ marginTop: 6, fontSize: 11 }}>
              Date : {created_at}<br/>
              Validité : 30 jours
            </div>
          </div>
        </div>
        <div className="meta" style={{ fontSize: 11, lineHeight: 1.55 }}>
          <span className="ink">Raycom Électrique Inc.</span> · RBQ 5590-9402-01 · Membre CMEQ<br/>
          3321 Av. de la Gare #112, Mascouche (QC) J7K 0K3<br/>
          450-474-8470 · info@raycomelectrique.com
        </div>
      </div>

      {/* Destinataire + projet */}
      <div className="qp-block">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
          <div>
            <h3>Destinataire</h3>
            <p>
              <span className="ink">{client.name || "—"}</span><br/>
              {client.phone || "—"}<br/>
              {client.email || "—"}
            </p>
          </div>
          <div>
            <h3>Adresse du projet</h3>
            <p>
              <span className="ink">{client.project_address || "—"}</span><br/>
              {bldg?.label}{hasSolar && roof ? ` · ${roof.label}` : ""}
            </p>
          </div>
        </div>
      </div>

      {/* Scope */}
      <div className="qp-block">
        <h3>Scope du projet</h3>
        <p style={{ fontSize: 12.5, color: "var(--raycom-ink)", lineHeight: 1.6 }}>{scope}</p>
      </div>

      {/* Composants */}
      <div className="qp-block">
        <h3>Détail des composants</h3>
        <table className="qp-table">
          <thead>
            <tr><th>Qté</th><th>Description</th><th>Un.</th></tr>
          </thead>
          <tbody>
            {lineItems.map((li, i) => (
              <tr key={i}>
                <td className="qty">{li.qty}</td>
                <td>
                  {li.desc}
                  {internal && li.internal_note && <span className="internal-note">interne : {li.internal_note}</span>}
                </td>
                <td className="un">{li.unit}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Sommaire financier */}
      <div className="qp-block">
        <h3>Sommaire financier</h3>
        <div className="totals">
          <span className="lbl">Sous-total HT</span><span className="val tnum">{fmtCAD(calc.ht)}</span>
          <span className="lbl">TPS 5,000 % (n° 830847828RT0001)</span><span className="val tnum">{fmtCAD(calc.tps)}</span>
          <span className="lbl">TVQ 9,975 % (n° 1214661795TQ0001)</span><span className="val tnum">{fmtCAD(calc.tvq)}</span>
          <span className="grand-lbl">Total TTC</span><span className="grand tnum">{fmtCAD(calc.ttc)}</span>
        </div>
      </div>

      {/* Subventions */}
      {calc.total_grant > 0 && (
        <div className="qp-block">
          <h3>Subventions applicables (informatif)</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {calc.logisvert > 0 && (
              <div className="grant-card">
                <div className="icon"><Icon name="leaf" size={14}/></div>
                <div>
                  <div className="title">Hydro-Québec LogisVert</div>
                  <div className="sub">1 000 $/kW · jusqu'à 40 % du coût HT · demande dans 9 mois post-mise en service · versée directement au client.</div>
                </div>
                <div className="amt">{fmtCAD0(calc.logisvert)}</div>
              </div>
            )}
            {calc.rve > 0 && (
              <div className="grant-card">
                <div className="icon"><Icon name="plug" size={14}/></div>
                <div>
                  <div className="title">Programme Roulez Vert (RVÉ)</div>
                  <div className="sub">600 $/borne unifamilial · plafond 5 000 $/projet multilog/condo · pré-approbation MERN requise pour multilog.</div>
                </div>
                <div className="amt">{fmtCAD0(calc.rve)}</div>
              </div>
            )}
            <div style={{ fontSize: 10.5, color: "var(--raycom-ink-dim)", fontStyle: "italic", marginTop: 2 }}>
              Les subventions sont versées au client par les programmes respectifs et ne réduisent pas le montant TTC payable à Raycom.
            </div>
          </div>
        </div>
      )}

      {/* Modalités de paiement */}
      <div className="qp-block">
        <h3>Modalités de paiement</h3>
        <ol className="steps">
          <li><span className="num">1</span><span>Dépôt à la signature (Interac / carte)</span><span className="amt">{fmtCAD0(1000)}</span></li>
          {fin.id === "comptant" ? (
            <>
              <li><span className="num">2</span><span>Versement à l'approbation Hydro-Québec</span><span className="amt">{fmtCAD0((calc.ttc - 1000) * 0.5)}</span></li>
              <li><span className="num">3</span><span>Versement à la mise en service</span><span className="amt">{fmtCAD0((calc.ttc - 1000) * 0.5)}</span></li>
            </>
          ) : (
            <li><span className="num">2</span><span>Solde par Financeit après mise en service</span><span className="amt">{fmtCAD0(calc.ttc - 1000)}</span></li>
          )}
        </ol>
        {fin.id !== "comptant" && (
          <div className="fin-banner">
            Avec <b>Financeit {fin.label}</b> : <b>{fmtCAD(calc.fin.monthly)}/mois</b> ({fin.months} mois · {fin.apr.toFixed(2).replace(".", ",")} % APR).
          </div>
        )}
      </div>

      {/* Rendement estimé */}
      {hasSolar && calc.production > 0 && (
        <div className="qp-block">
          <h3>Rendement estimé (indicatif)</h3>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <div className="cap">Production annuelle</div>
              <div className="tnum" style={{ fontSize: 22, fontWeight: 700, color: "var(--raycom-ink)", marginTop: 2 }}>
                {fmtNum(calc.production)} kWh
              </div>
              <div className="dim">≈ {(calc.production / 1000).toFixed(2).replace(".", ",")} MWh/an</div>
            </div>
            <div>
              <div className="cap">Économies + revenus annuels</div>
              <div className="tnum" style={{ fontSize: 22, fontWeight: 700, color: "var(--raycom-energy)", marginTop: 2 }}>
                {fmtCAD0(calc.savings.total)}
              </div>
              <div className="dim">{fmtCAD0(calc.savings.base)} économies HQ
                {calc.savings.peak_bonus > 0 && ` · ${fmtCAD0(calc.savings.peak_bonus)} pointe`}
                {calc.savings.v2x > 0 && ` · ${fmtCAD0(calc.savings.v2x)} V2X`}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="qp-footer">
        Validité 30 jours · Garantie 10 ans main-d'œuvre Raycom · 15 ans produit panneaux Thornova · 25 ans performance linéaire (≥ 84,8 %) · 10 ans onduleur / batterie<br/>
        Avenants de scope &gt; 150 $ documentés et signés avant exécution.
      </div>
    </div>
  );
};

// Construction des line items selon le type de projet
function buildLineItems({ state, calc, internal }) {
  const { solar, project_type, ve, options } = state;
  const items = [];
  const pack = window.RAYCAST_CALC.lookupBatteryPack(solar.battery_brand, solar.battery_preset_id);
  const brand = window.RAYCOM_DATA.battery_brands.find(b => b.key === solar.battery_brand);
  const roof = window.RAYCOM_DATA.roof_types.find(r => r.key === solar.roof_type);
  const hasSolar = project_type === "solaire" || project_type === "solaire_batterie";
  const hasBattery = (project_type === "solaire_batterie" && solar.battery_brand !== "none") || project_type === "batterie";

  if (hasSolar) {
    const panels = Math.ceil(solar.kw * 2);
    items.push({
      qty: panels,
      desc: "Panneau solaire monocristallin bifacial Thornova TS-BB66 All Black 500 W — cellules PERC 132 (182×91 mm) · rendement 21,06 % · cadre alu anodisé · backsheet noir transparent · connecteurs MC4 EVO2 · charges 5400 Pa avant / 2400 Pa arrière · bifacialité 70 ± 5 % · garantie produit 15 ans · garantie performance linéaire 25 ans (≥ 84,8 % à la 25e année · dégradation 0,55 %/an) · certifié CSA, IEC 61215/61730, ISO 9001/14001/45001",
      unit: "ch"
    });
    items.push({
      qty: solar.kw.toFixed(1).replace(".", ","),
      desc: `Système de fixation et câblage solaire — racking ${roof?.flat ? "IronRidge BX flat-roof avec ballast lesté" : "IronRidge XR-Lug ou équivalent certifié pour " + (roof?.label.toLowerCase() || "toit angle")}, optimiseurs/micro-onduleurs selon design, câblage DC PV Wire 10 AWG, câblage AC THWN-2, sectionneurs AC/DC, protections surtension classe II, conduits EMT/PVC selon code CSA Z32`,
      unit: "kW"
    });
  }

  if (hasBattery && pack && brand) {
    let battDesc;
    if (solar.battery_brand === "tesla") {
      battDesc = `Système hybride tout-en-un Tesla Powerwall 3 — onduleur intégré 11,5 kW continu + batterie LiFePO4 13,5 kWh utilisable par unité, Gateway 3 inclus — capacité utile ${pack.kwh.toFixed(1).replace(".", ",")} kWh · garantie 10 ans / 70 % capacité résiduelle`;
    } else if (solar.battery_brand === "fox") {
      battDesc = `Système Fox ESS AIO FLEX — onduleur hybride 11,4 kW + modules ECS LiFePO4 (${(pack.kwh / 4.03).toFixed(0)} × 4 kWh nominal) · capacité utile ${pack.kwh.toFixed(2).replace(".", ",")} kWh · Hub G2 DIM intégré · garantie 10 ans / 80 % capacité`;
    } else if (solar.battery_brand === "sig") {
      battDesc = `Système Sigenergy SigenStor — onduleur ${pack.kw_inv} kW hybride + stack batterie modulaire LiFePO4 ${pack.kwh} kWh · LoadHub avec DIM HQ intégré${pack.v2x ? " · port V2X bidirectionnel 25 kW (programme Roulez Électrique)" : ""} · garantie 10 ans`;
    } else if (solar.battery_brand === "solark") {
      battDesc = `Onduleur hybride Sol-Ark ${pack.kw_inv}K-2P + stockage HomeGrid ${pack.kwh.toFixed(1).replace(".", ",")} kWh (LiFePO4) · DIM externe homologué HQ · garantie 10 ans onduleur / 10 ans batterie`;
    } else {
      battDesc = `Système de stockage ${brand.name} — onduleur ${pack.kw_inv} kW · batterie ${pack.kwh} kWh LiFePO4 · DIM conforme HQ · garantie 10 ans`;
    }
    items.push({
      qty: 1,
      desc: battDesc,
      unit: "ens",
      internal_note: `${pack.label} · cost_inv ${calc.costs.inverter} $ · cost_batt ${calc.costs.batteries} $`
    });

    items.push({
      qty: 1,
      desc: `Dispositif d'interconnexion HQ (DIM) — ${brand.dim_label || "DIM externe"} · 200 A · transfert automatique · backup configurable selon mode sélectionné`,
      unit: "ens"
    });

    if (solar.backup_mode === "partial") {
      items.push({
        qty: 1,
        desc: "Sous-panneau 100 A dédié aux charges critiques (frigo, congélateur, fournaise/thermopompe, éclairage essentiel, prises critiques) — disjoncteurs Square D QO / Eaton CH, étiquetage CSA, transfert automatique via Gateway/LoadHub",
        unit: "ens"
      });
    }
    if (solar.backup_mode === "whole_home" && solar.service_amperage > 200) {
      items.push({
        qty: 1,
        desc: "Commutateur de transfert automatique commercial (ATS) — bobine sous tension permanente, contacteurs 400 A avec interverrouillage mécanique, conforme CSA C22.2 No 178",
        unit: "ens"
      });
    }
  }

  if (project_type === "borne") {
    const list = ve.bornes_selected || [];
    list.forEach(s => {
      const b = window.RAYCOM_DATA.bornes.find(x => x.key === s.key);
      if (!b) return;
      items.push({
        qty: s.qty,
        desc: `${b.brand} ${b.model} — borne de recharge VÉ niveau 2 · connecteur ${b.connector} · ${b.kw} kW max · admissible programme Roulez Vert · ENERGY STAR · Wi-Fi/Bluetooth pour monitoring`,
        unit: "ch"
      });
    });
    items.push({
      qty: 1,
      desc: `Installation électrique borne(s) — ${ve.scenario_post_2018 ? "Réutilisation du préfilage 2018+ (Code de construction du Québec, ch. V) avec disjoncteur 40 A dédié et mise à la terre" : "Câblage neuf NMD-90 ou RW-90 8 AWG, conduit EMT/ENT selon parcours, disjoncteur 60 A dédié, mise à la terre selon CSA C22.1"} · 50 pi de câble inclus${ve.cable_length_pi > 50 ? ` · ${ve.cable_length_pi - 50} pi additionnels facturés ${(ve.cable_length_pi - 50) * 18} $` : ""}`,
      unit: "ens"
    });
    if (ve.dcc_option !== "aucun") {
      items.push({
        qty: 1,
        desc: ve.dcc_option === "dcc12"
          ? "Dispositif de Contrôle de Charge DCC-12 (RVE) homologué Hydro-Québec — permet l'installation d'une borne 40 A sans hausse de l'entrée électrique 200 A · interruption automatique en surcharge"
          : "Tesla Dynamic Service Demand Control (DSDC) Remote Meter — équivalent fonctionnel du DCC-12 pour borne Tesla Wall Connector · gestion dynamique de l'ampérage selon la charge maison",
        unit: "ens"
      });
    }
  }

  // Forfait install + démarches (toujours)
  items.push({
    qty: 1,
    desc: "Schéma unifilaire E.12-07 conforme Hydro-Québec — plan signé et scellé par ingénieur OIQ, calculs d'ampacité, étude de coordination des protections, validation NEC/CSA",
    unit: "ens"
  });
  if (hasSolar) {
    items.push({
      qty: 1,
      desc: "Démarches administratives complètes — demande d'autorisation HQ mesurage net (formulaire E.12-07-MN), permis municipal d'électricité, inspection RBQ, coordination installation compteur bidirectionnel",
      unit: "ens"
    });
  }
  items.push({
    qty: 1,
    desc: `Mise en service et formation client — tests fonctionnels DC/AC, vérification production, configuration monitoring (app ${solar.battery_brand === "tesla" ? "Tesla" : solar.battery_brand === "fox" ? "FoxCloud" : solar.battery_brand === "sig" ? "mySigen" : "fabricant"} selon écosystème), formation à l'utilisation, remise des manuels et certificats de garantie`,
    unit: "ens"
  });
  items.push({
    qty: 1,
    desc: "Main-d'œuvre installateur certifié — équipe d'électriciens compagnons licenciés RBQ Raycom Électrique (RBQ 5590-9402-01), travaux en hauteur sécurisés CNESST, nettoyage et disposition des résidus",
    unit: "ens",
    internal_note: calc.costs.forfait ? `forfait ${calc.costs.forfait.code} · cout ${calc.costs.forfait.cost_total} $ · vendant ${calc.costs.forfait.sell_total} $` : null
  });

  // Options retenues
  (options || []).forEach(o => {
    items.push({ qty: 1, desc: o.label, unit: "ens" });
  });

  return items;
}

window.QuotePreview = QuotePreview;
