/* global React */
// Solar data — bases et formules portées 1:1 de public/audits-energies.html (pg-solaire).
// Règle CLAUDE.md : UI Claude Design IMMUTABLE, on injecte les données backend dans les zones existantes.

// ─── Catalogue 40+ panneaux photovoltaïques ──────────────────
const PANNEAUX_DB = {
  // Premium
  sunpower_maxeon6: { b: 'SunPower', m: 'Maxeon 6', wc: 440, gar: 40, rdt: 22.8, prix: 320 },
  sunpower_maxeon3: { b: 'SunPower', m: 'Maxeon 3', wc: 400, gar: 40, rdt: 22.6, prix: 305 },
  meyer_white:      { b: 'Meyer Burger', m: 'White', wc: 400, gar: 25, rdt: 21.8, prix: 330 },
  meyer_black:      { b: 'Meyer Burger', m: 'Black', wc: 395, gar: 25, rdt: 21.7, prix: 325 },
  rec_alphapure:    { b: 'REC', m: 'Alpha Pure-R', wc: 430, gar: 25, rdt: 22.3, prix: 280 },
  rec_alphapure2:   { b: 'REC', m: 'Alpha Pure 2', wc: 460, gar: 25, rdt: 22.6, prix: 295 },
  lg_neon_h:        { b: 'LG', m: 'NeON H', wc: 380, gar: 25, rdt: 21.7, prix: 260 },
  panasonic_hit:    { b: 'Panasonic', m: 'HIT N340', wc: 340, gar: 25, rdt: 20.3, prix: 250 },
  // Longi
  longi_himo6_410:  { b: 'Longi Solar', m: 'Hi-MO 6', wc: 410, gar: 30, rdt: 21.0, prix: 170 },
  longi_himo6_420:  { b: 'Longi Solar', m: 'Hi-MO 6', wc: 420, gar: 30, rdt: 21.3, prix: 180 },
  longi_himo6_440:  { b: 'Longi Solar', m: 'Hi-MO 6 Explorer', wc: 440, gar: 30, rdt: 22.6, prix: 195 },
  longi_himo7_580:  { b: 'Longi Solar', m: 'Hi-MO 7', wc: 580, gar: 30, rdt: 22.4, prix: 210 },
  longi_himo9_660:  { b: 'Longi Solar', m: 'Hi-MO 9', wc: 660, gar: 30, rdt: 24.4, prix: 240 },
  // Jinko
  jinko_tn54_440:   { b: 'Jinko Solar', m: 'Tiger Neo 54', wc: 440, gar: 30, rdt: 22.3, prix: 185 },
  jinko_tn72_575:   { b: 'Jinko Solar', m: 'Tiger Neo 72', wc: 575, gar: 30, rdt: 22.3, prix: 215 },
  jinko_tn72_580:   { b: 'Jinko Solar', m: 'Tiger Neo 72', wc: 580, gar: 30, rdt: 22.5, prix: 220 },
  jinko_tn78_620:   { b: 'Jinko Solar', m: 'Tiger Neo 78', wc: 620, gar: 30, rdt: 22.8, prix: 235 },
  // JA Solar
  ja_jam54d40_430:  { b: 'JA Solar', m: 'JAM54D40', wc: 430, gar: 30, rdt: 22.0, prix: 180 },
  ja_jam72d40_550:  { b: 'JA Solar', m: 'JAM72D40', wc: 550, gar: 30, rdt: 21.5, prix: 200 },
  ja_jam72d40_575:  { b: 'JA Solar', m: 'JAM72D40', wc: 575, gar: 30, rdt: 22.3, prix: 210 },
  ja_deepblue4_625: { b: 'JA Solar', m: 'DeepBlue 4.0', wc: 625, gar: 30, rdt: 23.0, prix: 235 },
  // Canadian
  canadian_hiku6_450: { b: 'Canadian Solar', m: 'HiKu6', wc: 450, gar: 25, rdt: 20.9, prix: 185 },
  canadian_hiku7_600: { b: 'Canadian Solar', m: 'HiKu7', wc: 600, gar: 25, rdt: 21.1, prix: 215 },
  canadian_hiku7_665: { b: 'Canadian Solar', m: 'HiKu7', wc: 665, gar: 25, rdt: 21.4, prix: 240 },
  canadian_tmh_580:   { b: 'Canadian Solar', m: 'TOPHiKu6', wc: 580, gar: 30, rdt: 22.5, prix: 225 },
  // Trina
  trina_vertexs_430:  { b: 'Trina Solar', m: 'Vertex S+', wc: 430, gar: 25, rdt: 22.0, prix: 180 },
  trina_vertex_550:   { b: 'Trina Solar', m: 'Vertex', wc: 550, gar: 25, rdt: 21.3, prix: 195 },
  trina_vertex_615:   { b: 'Trina Solar', m: 'Vertex DE21', wc: 615, gar: 25, rdt: 21.9, prix: 210 },
  trina_vertexn_720:  { b: 'Trina Solar', m: 'Vertex N', wc: 720, gar: 30, rdt: 23.2, prix: 260 },
  // Q.CELLS
  qcells_g11_400:   { b: 'Q.CELLS', m: 'Q.PEAK DUO G11', wc: 400, gar: 25, rdt: 20.6, prix: 195 },
  qcells_ml_410:    { b: 'Q.CELLS', m: 'Q.PEAK DUO ML-G11+', wc: 410, gar: 25, rdt: 21.0, prix: 205 },
  qcells_xl_500:    { b: 'Q.CELLS', m: 'Q.PEAK DUO XL-G11.3', wc: 500, gar: 25, rdt: 21.5, prix: 225 },
  qcells_neo_430:   { b: 'Q.CELLS', m: 'Q.TRON M-G2+ TOPCon', wc: 430, gar: 25, rdt: 22.5, prix: 220 },
  // Autres
  dmegc_410:         { b: 'DMEGC', m: 'DM-410M10-54HBB', wc: 410, gar: 25, rdt: 21.0, prix: 165 },
  astronergy_440:    { b: 'Astronergy', m: 'ASTRO N5s', wc: 440, gar: 30, rdt: 22.5, prix: 175 },
  risen_titan_590:   { b: 'Risen Energy', m: 'Titan', wc: 590, gar: 25, rdt: 22.0, prix: 195 },
  suntech_ultraV_440:{ b: 'Suntech', m: 'Ultra V', wc: 440, gar: 25, rdt: 22.5, prix: 170 },
  aesolar_aurora_440:{ b: 'AE Solar', m: 'Aurora', wc: 440, gar: 25, rdt: 22.5, prix: 175 },
  solarwatt_vision:  { b: 'Solarwatt', m: 'Vision 60M', wc: 380, gar: 30, rdt: 20.5, prix: 260 },
  heckert_nemo4_400: { b: 'Heckert Solar', m: 'NeMo 4.2 80M', wc: 400, gar: 30, rdt: 20.8, prix: 230 },
  voltec_tarka_420:  { b: 'Voltec Solar', m: 'Tarka', wc: 420, gar: 25, rdt: 21.5, prix: 240 },
  silfab_sil_430:    { b: 'Silfab', m: 'Prime', wc: 430, gar: 25, rdt: 21.8, prix: 245 },
  bisol_premium_420: { b: 'BISOL', m: 'Premium', wc: 420, gar: 25, rdt: 21.3, prix: 215 },
  sharp_nuqc_440:    { b: 'Sharp', m: 'NU-QC', wc: 440, gar: 25, rdt: 22.2, prix: 220 },
  // Saisie manuelle
  custom:            { b: 'Personnalisé', m: 'Saisie manuelle', wc: 420, gar: 25, rdt: 21.0, prix: 200 },
};

// Groupes pour l'affichage regroupé dans le select
const PANNEAUX_GROUPES = [
  { label: 'Premium (21+ %, garantie 25–40 ans)', keys: ['sunpower_maxeon6','sunpower_maxeon3','meyer_white','meyer_black','rec_alphapure','rec_alphapure2','lg_neon_h','panasonic_hit'] },
  { label: 'Longi Hi-MO', keys: ['longi_himo6_410','longi_himo6_420','longi_himo6_440','longi_himo7_580','longi_himo9_660'] },
  { label: 'Jinko Tiger Neo', keys: ['jinko_tn54_440','jinko_tn72_575','jinko_tn72_580','jinko_tn78_620'] },
  { label: 'JA Solar', keys: ['ja_jam54d40_430','ja_jam72d40_550','ja_jam72d40_575','ja_deepblue4_625'] },
  { label: 'Canadian Solar HiKu', keys: ['canadian_hiku6_450','canadian_hiku7_600','canadian_hiku7_665','canadian_tmh_580'] },
  { label: 'Trina Vertex', keys: ['trina_vertexs_430','trina_vertex_550','trina_vertex_615','trina_vertexn_720'] },
  { label: 'Q.CELLS', keys: ['qcells_g11_400','qcells_ml_410','qcells_xl_500','qcells_neo_430'] },
  { label: 'Autres marques', keys: ['dmegc_410','astronergy_440','risen_titan_590','suntech_ultraV_440','aesolar_aurora_440','solarwatt_vision','heckert_nemo4_400','voltec_tarka_420','silfab_sil_430','bisol_premium_420','sharp_nuqc_440'] },
  { label: 'Personnalisé', keys: ['custom'] },
];

// ─── Onduleurs (sélection auto selon puissance) ──────────────
const ONDULEURS_DB = [
  { pmin:   0, pmax:   6, marque: 'SMA',     modele: 'Sunny Boy 5.0 / 6.0',       puiss: '5–6 kW',  type: 'String monophasé',            prix: '~900 €',   tag: 'ta' },
  { pmin:   6, pmax:  20, marque: 'SMA',     modele: 'Sunny Tripower 8.0–20TL',   puiss: '8–20 kW', type: 'String triphasé',             prix: '~1 600 €', tag: 'tb' },
  { pmin:  20, pmax:  50, marque: 'SMA',     modele: 'Sunny Tripower 25000TL',    puiss: '25 kW',   type: 'String triphasé multi-MPPT',  prix: '~2 200 €', tag: 'tb' },
  { pmin:  50, pmax: 120, marque: 'Fronius', modele: 'Symo Advanced 50.0',        puiss: '50 kW',   type: 'String centralisé',           prix: '~3 800 €', tag: 'tg' },
  { pmin: 120, pmax:9999, marque: 'Huawei',  modele: 'SUN2000-100KTL',            puiss: '100 kW',  type: 'String haute puissance',      prix: '~6 500 €', tag: 'tg' },
];

// ─── Batteries — capacités constructeur réelles ──────────────
// Règle : toujours proposer les paliers officiels du fabricant, jamais un
// champ libre. MyLight Systems = batterie virtuelle (abonnement kWh/an).
// MyLight MSB = batterie physique LFP (modules 5,12 kWh empilables).

const BATTERIES_DB = {
  mylight_virtuelle: {
    marque: 'MyLight Systems',
    type: 'virtuelle',
    label: 'MyLight 150 (batterie virtuelle)',
    desc: 'Stockage virtuel · rendement 85 % · abonnement 35 €/mois',
    abonnementMensuel: 35,
    rendement: 0.85,
    // Paliers officiels MyLight 150 (kWh/an)
    capacites: [
      { kwh: 150, label: '150 kWh/an (entrée de gamme)' },
      { kwh: 350, label: '350 kWh/an' },
      { kwh: 500, label: '500 kWh/an' },
      { kwh: 1000, label: '1 000 kWh/an' },
      { kwh: 1500, label: '1 500 kWh/an' },
      { kwh: 2000, label: '2 000 kWh/an' },
      { kwh: 3000, label: '3 000 kWh/an' },
      { kwh: 5000, label: '5 000 kWh/an (tertiaire/industriel)' },
    ],
  },
  mylight_msb: {
    marque: 'MyLight Systems',
    type: 'physique',
    label: 'MyLight MSB (batterie physique LFP)',
    desc: 'Modules LFP 5,12 kWh empilables · garantie 10 ans · DoD 90 %',
    rendement: 0.94,
    dod: 0.9,
    capacites: [
      { kwh: 5.12, label: '1 module · 5,12 kWh' },
      { kwh: 10.24, label: '2 modules · 10,24 kWh' },
      { kwh: 15.36, label: '3 modules · 15,36 kWh' },
      { kwh: 20.48, label: '4 modules · 20,48 kWh' },
      { kwh: 25.6, label: '5 modules · 25,6 kWh' },
      { kwh: 30.72, label: '6 modules · 30,72 kWh' },
    ],
  },
  tesla_powerwall: {
    marque: 'Tesla',
    type: 'physique',
    label: 'Tesla Powerwall 3',
    desc: 'Batterie LFP · onduleur hybride intégré · DoD 100 %',
    rendement: 0.975,
    dod: 1,
    capacites: [
      { kwh: 13.5, label: '1 Powerwall · 13,5 kWh' },
      { kwh: 27, label: '2 Powerwalls · 27 kWh' },
      { kwh: 40.5, label: '3 Powerwalls · 40,5 kWh' },
      { kwh: 54, label: '4 Powerwalls · 54 kWh' },
    ],
  },
  byd_hvs: {
    marque: 'BYD',
    type: 'physique',
    label: 'BYD Battery-Box Premium HVS',
    desc: 'LFP · haute tension 150–500 V · modules 2,56 kWh',
    rendement: 0.96,
    dod: 0.95,
    capacites: [
      { kwh: 5.12, label: '2 modules · 5,12 kWh' },
      { kwh: 7.68, label: '3 modules · 7,68 kWh' },
      { kwh: 10.24, label: '4 modules · 10,24 kWh' },
    ],
  },
  byd_hvm: {
    marque: 'BYD',
    type: 'physique',
    label: 'BYD Battery-Box Premium HVM',
    desc: 'LFP · modules 2,76 kWh (3–8 modules)',
    rendement: 0.96,
    dod: 0.95,
    capacites: [
      { kwh: 8.28, label: '3 modules · 8,28 kWh' },
      { kwh: 11.04, label: '4 modules · 11,04 kWh' },
      { kwh: 13.8, label: '5 modules · 13,8 kWh' },
      { kwh: 16.56, label: '6 modules · 16,56 kWh' },
      { kwh: 19.32, label: '7 modules · 19,32 kWh' },
      { kwh: 22.08, label: '8 modules · 22,08 kWh' },
    ],
  },
  pylontech_us: {
    marque: 'Pylontech',
    type: 'physique',
    label: 'Pylontech US Series',
    desc: 'LFP · modules 2,4 / 3,55 kWh · BMS intégré',
    rendement: 0.95,
    dod: 0.9,
    capacites: [
      { kwh: 3.55, label: 'US3000C · 3,55 kWh' },
      { kwh: 7.1, label: '2× US3000C · 7,1 kWh' },
      { kwh: 10.65, label: '3× US3000C · 10,65 kWh' },
      { kwh: 14.2, label: '4× US3000C · 14,2 kWh' },
      { kwh: 17.75, label: '5× US3000C · 17,75 kWh' },
    ],
  },
  enphase_iq: {
    marque: 'Enphase',
    type: 'physique',
    label: 'Enphase IQ Battery',
    desc: 'LFP · microonduleurs intégrés · modules 3,4 / 5 / 10 kWh',
    rendement: 0.96,
    dod: 0.95,
    capacites: [
      { kwh: 3.36, label: 'IQ Battery 3T · 3,36 kWh' },
      { kwh: 5.0, label: 'IQ Battery 5P · 5 kWh' },
      { kwh: 10.0, label: 'IQ Battery 10T · 10 kWh' },
      { kwh: 20.0, label: '2× IQ 10T · 20 kWh' },
    ],
  },
  huawei_luna: {
    marque: 'Huawei',
    type: 'physique',
    label: 'Huawei LUNA2000',
    desc: 'LFP · modules 5 kWh empilables (5–30 kWh)',
    rendement: 0.96,
    dod: 1,
    capacites: [
      { kwh: 5, label: '1 module · 5 kWh' },
      { kwh: 10, label: '2 modules · 10 kWh' },
      { kwh: 15, label: '3 modules · 15 kWh' },
      { kwh: 20, label: '4 modules · 20 kWh (2 colonnes)' },
      { kwh: 30, label: '6 modules · 30 kWh (2 colonnes)' },
    ],
  },
};

// ─── Fixations selon type d'installation ─────────────────────
const FIXATIONS_DB = {
  toiture_res: { nom: 'Structure surimposition tuile/ardoise', desc: 'Fixation Schletter ou K2 Systems, rail alu anodisé', prix: '~8 €/m²' },
  toiture_ter: { nom: 'Structure bac acier / étanchéité',      desc: 'Fixation IsoRoof ou Aerocompact, lest ou ancrage',    prix: '~12 €/m²' },
  ombriere:    { nom: 'Charpente ombrière galvanisée',         desc: 'Poteaux acier, poutrelles, couverture PV intégrée',   prix: '~180 €/pl.' },
  sol:         { nom: 'Structure sol fixe ou tracker',         desc: 'Fondations béton ou vissées, montants galva',         prix: '~15 €/m²' },
};

// ─── Irradiation annuelle (kWh/m²/an) par zone × orientation ──
const IRRADIATION = {
  H1: { S: 1200, SE: 1130, SO: 1130, E:  950, O:  950 },
  H2: { S: 1390, SE: 1310, SO: 1310, E: 1100, O: 1100 },
  H3: { S: 1620, SE: 1530, SO: 1530, E: 1280, O: 1280 },
};

// ─── Facteur d'inclinaison ───────────────────────────────────
const INCLIN_FACTOR = { '0': 0.87, '15': 0.95, '30': 1.00, '45': 0.97, '60': 0.89 };

// ─── Répartition mensuelle (facteur relatif) ─────────────────
const MOIS_FACTOR = [0.6, 0.7, 0.9, 1.1, 1.2, 1.3, 1.3, 1.2, 1.0, 0.8, 0.6, 0.5];
const MOIS_NOM    = ['Janv','Févr','Mars','Avr','Mai','Juin','Juil','Août','Sept','Oct','Nov','Déc'];

// ─── Types d'installation + options selects ──────────────────
const TYPES_INSTALLATION = [
  { v: 'toiture_res', label: 'Toiture résidentielle (< 36 kWc)' },
  { v: 'toiture_ter', label: 'Toiture tertiaire (36–500 kWc)' },
  { v: 'ombriere',    label: 'Ombrière de parking' },
  { v: 'sol',         label: 'Installation au sol' },
];
const ZONES = [
  { v: 'H1', label: 'H1 — Île-de-France / Nord' },
  { v: 'H2', label: 'H2 — Ouest / Centre' },
  { v: 'H3', label: 'H3 — Méditerranée / Sud' },
];
const ORIENTATIONS = [
  { v: 'S',  label: 'Sud (optimal)' },
  { v: 'SE', label: 'Sud-Est' },
  { v: 'SO', label: 'Sud-Ouest' },
  { v: 'E',  label: 'Est' },
  { v: 'O',  label: 'Ouest' },
];
const INCLINAISONS = [
  { v: '0',  label: '0° (plat)' },
  { v: '15', label: '15°' },
  { v: '30', label: '30° (optimal)' },
  { v: '45', label: '45°' },
  { v: '60', label: '60°' },
];

// ─── Moteur de calcul — porté 1:1 de calcSolaire() ───────────
function calcSolaire(inputs) {
  const {
    type = 'toiture_ter',
    zone = 'H2',
    orient = 'S',
    inclin = '30',
    panneauKey = 'longi_himo6_440',
    wc: wcOverride,
    nb = 50,
    pertes = 14,
    conso = 85000,
    tachat = 0.2276,
    trevente = 0.1307,
    cout = 31200,
    myLight = false,
    battKwh = 150,
  } = inputs;

  const p = PANNEAUX_DB[panneauKey] || PANNEAUX_DB.custom;
  const wc = Number(wcOverride != null ? wcOverride : p.wc) || 420;
  const puissKwc = (nb * wc / 100) / 10; // = nb * wc / 1000
  const irrad = (IRRADIATION[zone] && IRRADIATION[zone][orient]) || 1200;
  const incFact = INCLIN_FACTOR[String(inclin)] || 1.0;
  const prod = Math.round(puissKwc * irrad * incFact * (1 - pertes / 100));

  // Autoconsommation (max 90 % théorique, plafonnée par ratio conso/prod × 0.45)
  const tauxAutocons = Math.min(0.9, Math.min(0.45, prod > 0 ? conso / prod : 0));
  const autoconsSans = Math.round(prod * tauxAutocons);
  const surplusSans = Math.max(0, prod - autoconsSans);
  const revSans = Math.round(surplusSans * trevente);
  const ecoSans = Math.round(autoconsSans * tachat + surplusSans * trevente);

  // MyLight 150 : batterie virtuelle
  let mlRecTotal = 0, ecoAvec = ecoSans, autoconsAvec = autoconsSans, surplusAvec = surplusSans, gainMyLight = 0;
  if (myLight) {
    const stockageAnnuel = Math.min(surplusSans * 0.72, battKwh * 12 * 0.85);
    mlRecTotal = Math.round(stockageAnnuel * 0.85);
    autoconsAvec = autoconsSans + mlRecTotal;
    surplusAvec = Math.max(0, prod - autoconsAvec);
    const abonnementMyLight = 420; // 35 € × 12 mois
    ecoAvec = Math.round(autoconsAvec * tachat + surplusAvec * trevente - abonnementMyLight);
    gainMyLight = ecoAvec - ecoSans;
  }

  const autosuffisance = conso > 0 ? Math.min(100, (autoconsAvec / conso) * 100) : 0;
  const tauxAutoconsFinal = prod > 0 ? (autoconsAvec / prod) * 100 : 0;
  const surface = Math.round(nb * (wc <= 430 ? 1.7 : 1.9));
  const coutKwc = puissKwc > 0 ? Math.round(cout / puissKwc) : 0;
  const roi = ecoAvec > 0 ? (cout / ecoAvec).toFixed(1) : '—';

  // Production mensuelle détaillée
  const totalFact = MOIS_FACTOR.reduce((s, f) => s + f, 0);
  const prodMax = Math.max(...MOIS_FACTOR.map(f => prod * f / totalFact));
  const mensuel = MOIS_FACTOR.map((f, i) => {
    const pm = prod * f / totalFact;
    // Répartition MyLight mensuelle proportionnelle
    const mlRec = myLight ? (mlRecTotal * f / totalFact) : 0;
    const am = Math.round(pm * tauxAutocons + mlRec);
    const sm = Math.max(0, Math.round(pm - am));
    return {
      mois: MOIS_NOM[i],
      prod: Math.round(pm),
      intensite: prodMax > 0 ? (pm / prodMax) * 100 : 0,
      autocons: am,
      surplus: sm,
    };
  });

  // Onduleur auto
  const onduleur = ONDULEURS_DB.find(o => puissKwc >= o.pmin && puissKwc < o.pmax) || ONDULEURS_DB[0];

  return {
    puissKwc: Number(puissKwc.toFixed(1)),
    prod,
    wc,
    panneau: p,
    surface,
    coutKwc,
    autoconsSans,
    autoconsAvec,
    surplusSans,
    surplusAvec,
    revSans,
    ecoSans,
    ecoAvec,
    gainMyLight,
    mlRec: mlRecTotal,
    autosuffisance: Number(autosuffisance.toFixed(1)),
    tauxAutocons: Number(tauxAutoconsFinal.toFixed(1)),
    roi,
    mensuel,
    onduleur,
    fixation: FIXATIONS_DB[type] || FIXATIONS_DB.toiture_ter,
  };
}

// Expose pour ExportPane et composants externes
window.SOLAR_DATA = {
  PANNEAUX_DB, PANNEAUX_GROUPES, ONDULEURS_DB, FIXATIONS_DB, BATTERIES_DB,
  IRRADIATION, INCLIN_FACTOR, MOIS_FACTOR, MOIS_NOM,
  TYPES_INSTALLATION, ZONES, ORIENTATIONS, INCLINAISONS,
  calcSolaire,
};
