// solaire-3d-re.jsx — Vue 3D réaliste du toit (three.js), « comme Aurora ou Solargraf », lecture seule.
//
// Données : couches Google Solar relayées par le worker (photo aérienne RGB, relief DSM, masque de toit, flux annuel)
// lues avec geotiff.js, et un MODÈLE VECTORIEL du bâtiment (window.SolaireModele.construire(...) ou prop `batiment`) :
// faces de toit = polygones 3D en mètres locaux (est, nord, z relatif au sol), arêtes typées, murs, arbres, obstacles.
// Tant que le modèle n'est pas fourni, un modèle de secours crédible est construit à partir des pans de buildingInsights
// (plans des pans, enveloppe inférieure, emprise = enveloppe convexe des boîtes), suffisant pour le rendu.
//
// Scène « maquette » : sol = terrain lissé (sans arbres ni bâtiments) couleur gazon avec la photo aérienne en transparence (rues et
// entrées lisibles), aplati sous la maison ; maison = faces du toit (photo projetée assombrie par la pente, ou bardeaux gris :
// bascule « Photo / Modèle »), arêtes blanches fines, murs beige mat avec corniche, cheminées ; voisins = volumes simples (murs
// beige clair, toit gris plat / deux pans / quatre pans / monopente) ; arbres = feuillus (couronne ellipsoïdale irrégulière,
// vert mat) et conifères (cône) à hauteur réelle, avec tronc ; tout projette des ombres ; panneaux = plaques sur le plan exact
// de la face, cadre, cellules, reflet. Soleil : curseurs mois et heure (heure de Mascouche), position NOAA pour le site,
// lecture animée de la journée, calque « Soleil » (dégradé jaune du flux annuel), encart au survol d'un panneau.
// Caméra : orbite (glisser), zoom (molette), déplacement (bouton droit ou Maj), vues Perspective, Dessus, Sud, Nord, Vue rue
// (1,8 m depuis la rue : arbres et voisins devant la maison translucides), Recentrer. Tout est libéré au démontage.
//
// Exposé : window.Solaire3DRE ({ lat, lng, panneaux, modele, orientation, pans, toit, batiment })
//   panneaux = [{ lat, lng, pan, coins?: [{lat,lng}×4], watts? }] ; modele = { w, h, watts? } (dimensions du panneau en m)
//   pans = segments de buildingInsights ; toit = réponse complète de /raycast/solaire/toit (pour le modèle de secours)
//   batiment = modèle vectoriel (voir adapterBatiment pour le contrat accepté)
// Évènement écouté : window « raycast:editeur » (detail = { centre, modele, orientation, panneaux, pans, batiment? }).
(function () {
  const { useState, useEffect, useRef } = React;
  const WORKER_URL = window.RAYCAST_WORKER_URL || "https://raycom-ghl-qbo-worker.proud-leaf-b313.workers.dev";
  const SOUS_ECH = 2;          // sous-échantillonnage du relief (2 × 0,1 m = 0,2 m par sommet)
  const RAYON_VUE_M = 40;      // rayon des couches demandées
  const MOIS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
  const fmtInt = (n) => Math.round(Number(n) || 0).toLocaleString("fr-CA");

  async function jwt() { const { data } = await window.RAYCAST_SUPABASE.auth.getSession(); return data && data.session ? data.session.access_token : null; }
  async function getJson(path) {
    const t = await jwt(); if (!t) throw new Error("Session expirée");
    const r = await fetch(WORKER_URL + path, { headers: { Authorization: "Bearer " + t } });
    const j = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
    return j;
  }

  // ───────────────────────── Géodésie ─────────────────────────
  /** UTM (WGS84) → latitude, longitude. Formules USGS (Snyder), précision millimétrique sur 80 m. */
  function utmVersLatLng(x, y, zone, nord) {
    const a = 6378137, f = 1 / 298.257223563, k0 = 0.9996, e2 = f * (2 - f), ep2 = e2 / (1 - e2);
    const e1 = (1 - Math.sqrt(1 - e2)) / (1 + Math.sqrt(1 - e2));
    const xm = x - 500000, ym = nord ? y : y - 10000000;
    const M = ym / k0, mu = M / (a * (1 - e2 / 4 - 3 * e2 * e2 / 64 - 5 * e2 * e2 * e2 / 256));
    const phi1 = mu + (3 * e1 / 2 - 27 * Math.pow(e1, 3) / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * Math.pow(e1, 4) / 32) * Math.sin(4 * mu) + (151 * Math.pow(e1, 3) / 96) * Math.sin(6 * mu) + (1097 * Math.pow(e1, 4) / 512) * Math.sin(8 * mu);
    const sin1 = Math.sin(phi1), cos1 = Math.cos(phi1), tan1 = Math.tan(phi1);
    const N1 = a / Math.sqrt(1 - e2 * sin1 * sin1), T1 = tan1 * tan1, C1 = ep2 * cos1 * cos1, R1 = a * (1 - e2) / Math.pow(1 - e2 * sin1 * sin1, 1.5), D = xm / (N1 * k0);
    const lat = phi1 - (N1 * tan1 / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * ep2) * Math.pow(D, 4) / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * ep2 - 3 * C1 * C1) * Math.pow(D, 6) / 720);
    const lng0 = ((zone - 1) * 6 - 180 + 3) * Math.PI / 180;
    const lng = lng0 + (D - (1 + 2 * T1 + C1) * Math.pow(D, 3) / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * ep2 + 24 * T1 * T1) * Math.pow(D, 5) / 120) / cos1;
    return { lat: lat * 180 / Math.PI, lng: lng * 180 / Math.PI };
  }
  /** Mètres locaux (est, nord) autour d'une origine lat/lng, et retour. */
  const metres = (origine) => {
    const mLat = 111320, mLng = 111320 * Math.cos(origine.lat * Math.PI / 180);
    return {
      versLocal: (lat, lng) => ({ e: (lng - origine.lng) * mLng, n: (lat - origine.lat) * mLat }),
      versLatLng: (e, n) => ({ lat: origine.lat + n / mLat, lng: origine.lng + e / mLng }),
    };
  };

  /** Lecture d'une couche GeoTIFF par le worker : { w, h, bbox (lat/lng), bandes[] }. */
  async function getTiff(id) {
    const t = await jwt(); if (!t) throw new Error("Session expirée");
    const r = await fetch(`${WORKER_URL}/raycast/solaire/geotiff?id=${encodeURIComponent(id)}`, { headers: { Authorization: "Bearer " + t } });
    if (!r.ok) throw new Error(`Couche ${r.status}`);
    const buf = await r.arrayBuffer();
    const G = window.GeoTIFF; if (!G) throw new Error("Bibliothèque GeoTIFF absente");
    const tiff = await G.fromArrayBuffer(buf);
    const img = await tiff.getImage();
    const w = img.getWidth(), hgt = img.getHeight();
    let bbox = img.getBoundingBox();
    const keys = img.getGeoKeys ? (img.getGeoKeys() || {}) : {};
    const epsg = keys.ProjectedCSTypeGeoKey || keys.GeographicTypeGeoKey || 4326;
    if (epsg === 3857) {
      const toLng = (x) => x / 20037508.34 * 180, toLat = (y) => (Math.atan(Math.exp(y / 20037508.34 * Math.PI)) * 360 / Math.PI) - 90;
      bbox = [toLng(bbox[0]), toLat(bbox[1]), toLng(bbox[2]), toLat(bbox[3])];
    } else if ((epsg >= 32601 && epsg <= 32660) || (epsg >= 32701 && epsg <= 32760)) {
      const zone = epsg % 100, nord = epsg < 32700;
      const sw = utmVersLatLng(bbox[0], bbox[1], zone, nord), ne = utmVersLatLng(bbox[2], bbox[3], zone, nord);
      bbox = [sw.lng, sw.lat, ne.lng, ne.lat];
    }
    const rasters = await img.readRasters();
    return { w, h: hgt, bbox, bandes: rasters.length ? rasters : [rasters], nb: rasters.length || 1 };
  }
  /** Repère du raster : pixel ↔ lat/lng, mètres par pixel. Scène : x = est, z = sud, origine au coin nord-ouest du raster. */
  function repere(c) {
    const [minLng, minLat, maxLng, maxLat] = c.bbox;
    const latC = (minLat + maxLat) / 2;
    const mLat = 111320, mLng = 111320 * Math.cos(latC * Math.PI / 180);
    const dLngPx = (maxLng - minLng) / c.w, dLatPx = (maxLat - minLat) / c.h;
    return {
      w: c.w, h: c.h, mPxX: dLngPx * mLng, mPxY: dLatPx * mLat, largeurM: c.w * dLngPx * mLng, hauteurM: c.h * dLatPx * mLat, latC,
      pxDe: (lat, lng) => ({ x: (lng - minLng) / dLngPx, y: (maxLat - lat) / dLatPx }),
      sceneDe: (lat, lng) => ({ x: (lng - minLng) * mLng, z: (maxLat - lat) * mLat }),
      latLngDe: (x, z) => ({ lat: maxLat - z / mLat, lng: minLng + x / mLng }),
    };
  }
  /** Valeur bilinéaire d'une bande au pixel flottant (x, y) ; NaN hors raster ou sans donnée. */
  function valeurA(c, x, y, bande = 0) {
    const w = c.w, h = c.h, b = c.bandes[bande];
    const x0 = Math.max(0, Math.min(w - 2, Math.floor(x))), y0 = Math.max(0, Math.min(h - 2, Math.floor(y)));
    const fx = Math.max(0, Math.min(1, x - x0)), fy = Math.max(0, Math.min(1, y - y0));
    const v = (i, j) => { const z = b[j * w + i]; return isFinite(z) && z > -1000 ? z : NaN; };
    const z00 = v(x0, y0), z10 = v(x0 + 1, y0), z01 = v(x0, y0 + 1), z11 = v(x0 + 1, y0 + 1);
    const vals = [z00, z10, z01, z11].filter(isFinite);
    if (vals.length < 4) return vals.length ? vals.reduce((s, q) => s + q, 0) / vals.length : NaN;
    return z00 * (1 - fx) * (1 - fy) + z10 * fx * (1 - fy) + z01 * (1 - fx) * fy + z11 * fx * fy;
  }

  // ───────────────────────── Géométrie 2D / 3D ─────────────────────────
  const aire2 = (P) => { let a = 0; for (let i = 0, n = P.length; i < n; i++) { const p = P[i], q = P[(i + 1) % n]; a += p.e * q.n - q.e * p.n; } return a / 2; };
  const dansPolygone = (P, e, n) => { let c = false; for (let i = 0, j = P.length - 1; i < P.length; j = i++) { const a = P[i], b = P[j]; if ((a.n > n) !== (b.n > n) && e < (b.e - a.e) * (n - a.n) / (b.n - a.n) + a.e) c = !c; } return c; };
  const distSegment = (p, a, b) => { const dx = b.e - a.e, dn = b.n - a.n, l2 = dx * dx + dn * dn; const t = l2 ? Math.max(0, Math.min(1, ((p.e - a.e) * dx + (p.n - a.n) * dn) / l2)) : 0; const x = a.e + t * dx - p.e, y = a.n + t * dn - p.n; return Math.sqrt(x * x + y * y); };
  const distPolygone = (P, e, n) => { let d = Infinity; for (let i = 0; i < P.length; i++) d = Math.min(d, distSegment({ e, n }, P[i], P[(i + 1) % P.length])); return dansPolygone(P, e, n) ? 0 : d; };
  /** Enveloppe convexe (Andrew) de points {e,n}. */
  function enveloppeConvexe(pts) {
    const P = pts.slice().sort((a, b) => a.e - b.e || a.n - b.n);
    if (P.length < 3) return P;
    const cross = (o, a, b) => (a.e - o.e) * (b.n - o.n) - (a.n - o.n) * (b.e - o.e);
    const bas = []; for (const p of P) { while (bas.length >= 2 && cross(bas[bas.length - 2], bas[bas.length - 1], p) <= 0) bas.pop(); bas.push(p); }
    const haut = []; for (let i = P.length - 1; i >= 0; i--) { const p = P[i]; while (haut.length >= 2 && cross(haut[haut.length - 2], haut[haut.length - 1], p) <= 0) haut.pop(); haut.push(p); }
    bas.pop(); haut.pop(); return bas.concat(haut);
  }
  /** Découpe d'un polygone convexe par le demi-plan f(p) ≤ 0 (Sutherland–Hodgman). f linéaire en (e, n). */
  function decouper(P, f) {
    const out = [];
    for (let i = 0; i < P.length; i++) {
      const a = P[i], b = P[(i + 1) % P.length], fa = f(a), fb = f(b);
      if (fa <= 0) out.push(a);
      if ((fa <= 0) !== (fb <= 0)) { const t = fa / (fa - fb); out.push({ e: a.e + t * (b.e - a.e), n: a.n + t * (b.n - a.n) }); }
    }
    return out;
  }
  /** Triangulation par oreilles d'un polygone simple 2D (points {u, v}) → indices. */
  function triangulerOreilles(P) {
    const n = P.length; if (n < 3) return [];
    const idx = []; for (let i = 0; i < n; i++) idx.push(i);
    if (aire2(P.map(p => ({ e: p.u, n: p.v }))) < 0) idx.reverse();
    const tri = []; let garde = 0;
    const convexe = (a, b, c) => (b.u - a.u) * (c.v - a.v) - (b.v - a.v) * (c.u - a.u) > 1e-10;
    const dedans = (p, a, b, c) => { const s1 = (b.u - a.u) * (p.v - a.v) - (b.v - a.v) * (p.u - a.u), s2 = (c.u - b.u) * (p.v - b.v) - (c.v - b.v) * (p.u - b.u), s3 = (a.u - c.u) * (p.v - c.v) - (a.v - c.v) * (p.u - c.u); return s1 >= -1e-10 && s2 >= -1e-10 && s3 >= -1e-10; };
    while (idx.length > 3 && garde++ < 5000) {
      let coupe = false;
      for (let i = 0; i < idx.length; i++) {
        const ia = idx[(i + idx.length - 1) % idx.length], ib = idx[i], ic = idx[(i + 1) % idx.length];
        const a = P[ia], b = P[ib], c = P[ic];
        if (!convexe(a, b, c)) continue;
        let ok = true;
        for (const k of idx) { if (k === ia || k === ib || k === ic) continue; if (dedans(P[k], a, b, c)) { ok = false; break; } }
        if (!ok) continue;
        tri.push(ia, ib, ic); idx.splice(i, 1); coupe = true; break;
      }
      if (!coupe) { for (let i = 1; i + 1 < idx.length; i++) tri.push(idx[0], idx[i], idx[i + 1]); return tri; }
    }
    if (idx.length === 3) tri.push(idx[0], idx[1], idx[2]);
    return tri;
  }
  /** Plan d'un polygone 3D (Newell) : normale unitaire orientée vers le haut, centre, z(e, n), pente et azimut de descente. */
  function planDe(poly) {
    let nx = 0, ny = 0, nz = 0;
    for (let i = 0; i < poly.length; i++) { const p = poly[i], q = poly[(i + 1) % poly.length]; nx += (p.n - q.n) * (p.z + q.z); ny += (p.z - q.z) * (p.e + q.e); nz += (p.e - q.e) * (p.n + q.n); }
    const l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; nx /= l; ny /= l; nz /= l;
    if (nz < 0) { nx = -nx; ny = -ny; nz = -nz; }
    const c = poly.reduce((s, p) => ({ e: s.e + p.e / poly.length, n: s.n + p.n / poly.length, z: s.z + p.z / poly.length }), { e: 0, n: 0, z: 0 });
    const zA = (e, n) => Math.abs(nz) < 1e-6 ? c.z : c.z - (nx * (e - c.e) + ny * (n - c.n)) / nz;
    const pente = Math.acos(Math.min(1, Math.max(-1, nz))) * 180 / Math.PI;
    const azimut = ((Math.atan2(nx, ny) * 180 / Math.PI) + 360) % 360;
    return { n: { e: nx, n: ny, z: nz }, centre: c, zA, pente, azimut };
  }

  // ───────────────────────── Modèle du bâtiment ─────────────────────────
  /** Contrat accepté (window.SolaireModele.construire ou prop batiment), tolérant :
   *   { origine?: {lat,lng}, sol_m?: number, emprise?: [{e,n}],
   *     faces: [{ id?, pan?, polygone|points|sommets: [{e,n,z}|[e,n,z]], azimut_deg?, pente_deg? }],
   *     aretes?: [{ type: faite|arete|noue|rive|egout, a:{e,n,z}, b:{e,n,z} } | { type, points:[…] }],
   *     murs?: [{ polygone|points: [{e,n,z}…] }],
   *     arbres?: [{ e, n, rayon, hauteur, hauteur_tronc? }], obstacles?: [{ e, n, largeur, profondeur, hauteur, z?, azimut_deg? }] }
   *  Mètres locaux : e = est, n = nord, z = hauteur relative au sol. Origine = `origine` sinon le centre de la maison. */
  /** Sortie de SolaireModele.construire (solaire-modele-re.js) → contrat interne. Mètres locaux depuis le coin nord-ouest du raster.
   *  Transmet aussi voisins (volumes), sol (plan) et terrain (grille lissée) quand le modèle les fournit. */
  function adapterModeleVectoriel(m) {
    const som = m.sommets || [];
    const P = (i) => { const q = som[i]; if (!q) return null; const e = q.e != null ? q.e : (q.m && q.m.e), n = q.n != null ? q.n : (q.m && q.m.n); return e != null && n != null ? { e: +e, n: +n, z: +(q.z || 0) } : null; };
    const faces = m.faces.map((f, i) => ({ id: f.index ?? i, pan: f.pan ?? i, polygone: f.sommets_3d.map(q => ({ e: q.e, n: q.n, z: q.z })), azimut_deg: f.azimut_deg, pente_deg: f.pente_deg, surface_m2: f.surface_m2, acces_moyen: f.acces_moyen })).filter(f => f.polygone.length >= 3);
    const aretes = (m.aretes || []).map(a => ({ type: a.type || "arete", a: P(a.de), b: P(a.a) })).filter(a => a.a && a.b);
    const murs = (m.murs || []).map(w => ({ polygone: (w.polygone_3d || []).map(q => ({ e: q.e, n: q.n, z: q.z })) })).filter(w => w.polygone.length >= 3);
    const arbres = (m.arbres || []).map(t => ({ e: +t.e, n: +t.n, rayon: +(t.rayon_m || 2.5), hauteur: +(t.hauteur_m || 8), hauteur_tronc: t.hauteur_tronc_m != null ? +t.hauteur_tronc_m : Math.max(1.5, (+t.hauteur_m || 8) * 0.35), forme: t.forme || "feuillu" }));
    const obstacles = (m.obstacles_detectes || m.obstacles || []).map(ob => ({ e: +ob.e, n: +ob.n, largeur: 2 * (+ob.rayon_m || 0.4), profondeur: 2 * (+ob.rayon_m || 0.4), hauteur: +(ob.hauteur_m || 1), z: null, azimut_deg: 0 }));
    const voisins = (m.voisins || []).filter(v => v && Array.isArray(v.polygone_2d) && v.polygone_2d.length >= 3);
    return { origine: null, nw: true, sol_m: m.sol_m != null ? +m.sol_m : null, faces, aretes, murs, arbres, obstacles, voisins, sol: m.sol || null, terrain: m.terrain && m.terrain.z ? m.terrain : null, emprise: [], emprises: [], qualite: m.qualite || null, hauteur_egout_m: m.hauteur_egout_m, hauteur_faite_m: m.hauteur_faite_m };
  }
  /** Repère au contrat de SolaireGeom.repere (si solaire-geom-re.js n'est pas chargé). */
  function repereModele(c) {
    const [minLng, minLat, maxLng, maxLat] = c.bbox; const latC = (minLat + maxLat) / 2;
    const mLat = 111320, mLng = 111320 * Math.cos(latC * Math.PI / 180);
    const dX = (maxLng - minLng) / c.w, dY = (maxLat - minLat) / c.h;
    return { w: c.w, h: c.h, mParPx: (dX * mLng + dY * mLat) / 2, latC,
      pxDe: (lat, lng) => ({ x: (lng - minLng) / dX, y: (maxLat - lat) / dY }), geoDe: (x, y) => ({ lat: maxLat - y * dY, lng: minLng + x * dX }),
      mDe: (x, y) => ({ e: x * dX * mLng, n: -y * dY * mLat }), pxDeM: (e, n) => ({ x: e / (dX * mLng), y: -n / (dY * mLat) }) };
  }
  function adapterBatiment(m) {
    if (!m) return null;
    if (Array.isArray(m.faces) && m.faces.length && m.faces[0] && m.faces[0].sommets_3d) return adapterModeleVectoriel(m);
    const pt = (p) => Array.isArray(p) ? { e: +p[0], n: +p[1], z: +(p[2] || 0) } : { e: +(p.e ?? p.x ?? 0), n: +(p.n ?? p.y ?? 0), z: +(p.z ?? p.h ?? 0) };
    const poly = (f) => (f.polygone || f.points || f.sommets || f.polygon || []).map(pt);
    const faces = (m.faces || m.toits || []).map((f, i) => ({ id: f.id ?? i, pan: f.pan ?? f.segment ?? i, polygone: poly(f), azimut_deg: f.azimut_deg ?? f.azimut, pente_deg: f.pente_deg ?? f.pente })).filter(f => f.polygone.length >= 3);
    const typeNorm = (t) => { const s = String(t || "").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, ""); return /fait/.test(s) ? "faite" : /noue|vall/.test(s) ? "noue" : /egout|eave|gout/.test(s) ? "egout" : /rive|gable|pignon/.test(s) ? "rive" : "arete"; };
    const aretes = (m.aretes || m.edges || []).map(a => { const pts = a.points ? a.points.map(pt) : [pt(a.a || a.debut || a[0]), pt(a.b || a.fin || a[1])]; return { type: typeNorm(a.type), a: pts[0], b: pts[1] }; }).filter(a => a.a && a.b);
    const murs = (m.murs || m.walls || []).map(w => ({ polygone: poly(w) })).filter(w => w.polygone.length >= 3);
    const arbres = (m.arbres || m.trees || []).map(t => ({ e: +(t.e ?? t.x ?? 0), n: +(t.n ?? t.y ?? 0), rayon: +(t.rayon ?? t.r ?? 2.5), hauteur: +(t.hauteur ?? t.h ?? 8), hauteur_tronc: +(t.hauteur_tronc ?? t.tronc ?? Math.max(1.5, (t.hauteur ?? 8) * 0.35)), forme: t.forme || "feuillu" }));
    const obstacles = (m.obstacles || []).map(o => ({ e: +(o.e ?? o.x ?? 0), n: +(o.n ?? o.y ?? 0), largeur: +(o.largeur ?? o.l ?? o.w ?? 0.6), profondeur: +(o.profondeur ?? o.p ?? o.d ?? 0.6), hauteur: +(o.hauteur ?? o.h ?? 1), z: o.z != null ? +o.z : null, azimut_deg: +(o.azimut_deg ?? o.azimut ?? 0) }));
    const emprise = (m.emprise || m.footprint || []).map(pt);
    const emprises = (m.emprises || []).map(E => E.map(pt));
    const voisins = (m.voisins || []).filter(v => v && Array.isArray(v.polygone_2d) && v.polygone_2d.length >= 3);
    return { origine: m.origine || m.origin || null, sol_m: m.sol_m != null ? +m.sol_m : null, faces, aretes, murs, arbres, obstacles, voisins, sol: m.sol || null, terrain: m.terrain && m.terrain.z ? m.terrain : null, emprise, emprises };
  }

  /** Modèle de secours à partir des pans de buildingInsights : plans des pans, enveloppe inférieure par bloc,
   *  emprise = enveloppe convexe des boîtes, murs jusqu'au sol, arêtes typées, 3 arbres fictifs, une cheminée. Origine = centre. */
  function modeleDepuisToit(toit, zSol) {
    const segs = (toit && toit.segments) || [];
    if (!segs.length || !toit.centre) return null;
    const M = metres(toit.centre);
    const plans = segs.filter(s => s.centre && s.boite).map(s => {
      const c = M.versLocal(s.centre.lat, s.centre.lng);
      const az = (Number(s.azimut_deg) || 0) * Math.PI / 180, tan = Math.tan((Number(s.pente_deg) || 0) * Math.PI / 180);
      const d = { e: Math.sin(az), n: Math.cos(az) };
      const zc = (Number(s.hauteur_m) || zSol + 6) - zSol;
      const sw = M.versLocal(s.boite.sw.lat, s.boite.sw.lng), ne = M.versLocal(s.boite.ne.lat, s.boite.ne.lng);
      const boite = [{ e: sw.e, n: sw.n }, { e: ne.e, n: sw.n }, { e: ne.e, n: ne.n }, { e: sw.e, n: ne.n }];
      return { index: s.index, zA: (e, n) => zc - tan * ((e - c.e) * d.e + (n - c.n) * d.n), centre: c, boite, zc, pente: Number(s.pente_deg) || 0, azimut: Number(s.azimut_deg) || 0 };
    });
    if (!plans.length) return null;
    const chev = (A, B) => !(A[1].e < B[0].e - 0.3 || B[1].e < A[0].e - 0.3 || A[2].n < B[0].n - 0.3 || B[2].n < A[0].n - 0.3);
    const parent = plans.map((_, i) => i); const trouve = (i) => parent[i] === i ? i : (parent[i] = trouve(parent[i]));
    for (let i = 0; i < plans.length; i++) for (let j = i + 1; j < plans.length; j++) {
      if (chev(plans[i].boite, plans[j].boite) && Math.abs(plans[i].zc - plans[j].zc) < 2.5) parent[trouve(i)] = trouve(j);
    }
    const blocs = {}; plans.forEach((p, i) => { (blocs[trouve(i)] = blocs[trouve(i)] || []).push(p); });
    const faces = [], aretes = [], murs = [], emprises = [];
    const cle = (p) => `${p.e.toFixed(2)},${p.n.toFixed(2)}`;
    for (const liste of Object.values(blocs)) {
      const emprise = enveloppeConvexe(liste.flatMap(p => p.boite));
      if (emprise.length < 3) continue;
      const zToit = (e, n) => Math.min(...liste.map(p => p.zA(e, n)));
      const hauteurEgout = Math.max(2.6, Math.min(...emprise.map(q => zToit(q.e, q.n))));
      const zToitPlancher = (e, n) => Math.max(hauteurEgout, zToit(e, n));
      const polyFaces = [];
      for (const p of liste) {
        let poly = emprise.slice();
        for (const q of liste) { if (q === p) continue; poly = decouper(poly, (pt) => p.zA(pt.e, pt.n) - q.zA(pt.e, pt.n)); if (poly.length < 3) break; }
        if (poly.length < 3 || Math.abs(aire2(poly)) < 0.5) continue;
        if (aire2(poly) < 0) poly.reverse();
        const poly3 = poly.map(pt => ({ e: pt.e, n: pt.n, z: zToitPlancher(pt.e, pt.n) }));
        polyFaces.push({ p, poly3 });
        faces.push({ id: faces.length, pan: p.index, polygone: poly3, azimut_deg: p.azimut, pente_deg: p.pente });
      }
      const vues = new Set();
      for (const f of polyFaces) for (let i = 0; i < f.poly3.length; i++) {
        const a = f.poly3[i], b = f.poly3[(i + 1) % f.poly3.length];
        if (Math.hypot(a.e - b.e, a.n - b.n) < 0.05) continue;
        const k = [cle(a), cle(b)].sort().join("|"); if (vues.has(k)) continue; vues.add(k);
        const mil = { e: (a.e + b.e) / 2, n: (a.n + b.n) / 2 };
        const partage = polyFaces.some(g => g !== f && distPolygone(g.poly3, mil.e, mil.n) < 0.05);
        const horizontale = Math.abs(a.z - b.z) < 0.25;
        aretes.push({ type: partage ? (horizontale ? "faite" : "arete") : (horizontale ? "egout" : "rive"), a, b });
      }
      for (let i = 0; i < emprise.length; i++) {
        const a = emprise[i], b = emprise[(i + 1) % emprise.length];
        murs.push({ polygone: [{ e: a.e, n: a.n, z: 0 }, { e: b.e, n: b.n, z: 0 }, { e: b.e, n: b.n, z: zToitPlancher(b.e, b.n) }, { e: a.e, n: a.n, z: zToitPlancher(a.e, a.n) }] });
      }
      emprises.push(emprise);
    }
    const tous = emprises.flat();
    const maxE = Math.max(...tous.map(p => p.e)), minE = Math.min(...tous.map(p => p.e)), maxN = Math.max(...tous.map(p => p.n)), minN = Math.min(...tous.map(p => p.n));
    const arbres = [{ e: minE - 7, n: minN - 4, rayon: 3.2, hauteur: 9.5, hauteur_tronc: 3, forme: "feuillu" }, { e: maxE + 6, n: maxN + 5, rayon: 2.6, hauteur: 7.5, hauteur_tronc: 2.4, forme: "feuillu" }, { e: (minE + maxE) / 2 + 2, n: maxN + 9, rayon: 3.8, hauteur: 11, hauteur_tronc: 3.5, forme: "feuillu" }];
    const haut = faces.slice().sort((a, b) => planDe(b.polygone).centre.z - planDe(a.polygone).centre.z)[0];
    const obstacles = haut ? [{ e: planDe(haut.polygone).centre.e, n: planDe(haut.polygone).centre.n, largeur: 0.6, profondeur: 0.6, hauteur: 1.1, z: null, azimut_deg: 0 }] : [];
    return { origine: toit.centre, sol_m: zSol, faces, aretes, murs, arbres, obstacles, voisins: [], sol: null, terrain: null, emprise: tous.length ? enveloppeConvexe(tous) : [], emprises };
  }

  // ───────────────────────── Soleil ─────────────────────────
  /** Position du soleil (NOAA) : mois (1-12, le 15 du mois), heure décimale de Mascouche (avancée UTC-4 de mars à octobre, normale UTC-5 sinon). */
  function soleil(lat, lng, mois, heure) {
    const jour = [15, 46, 74, 105, 135, 166, 196, 227, 258, 288, 319, 349][Math.max(0, Math.min(11, mois - 1))];
    const g = 2 * Math.PI / 365 * (jour - 1 + (heure - 12) / 24);
    const eq = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g) - 0.014615 * Math.cos(2 * g) - 0.040849 * Math.sin(2 * g));
    const decl = 0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g) - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g) - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g);
    const tz = (mois >= 3 && mois <= 10) ? -4 : -5; const tst = heure * 60 + eq + 4 * lng - 60 * tz;
    const ha = (tst / 4 - 180) * Math.PI / 180, la = lat * Math.PI / 180;
    const cosZ = Math.sin(la) * Math.sin(decl) + Math.cos(la) * Math.cos(decl) * Math.cos(ha);
    const zen = Math.acos(Math.max(-1, Math.min(1, cosZ)));
    let az = 0;
    const den = Math.cos(la) * Math.sin(zen);
    if (Math.abs(den) > 1e-9) { const c = Math.max(-1, Math.min(1, (Math.sin(la) * cosZ - Math.sin(decl)) / den)); const th = Math.acos(c) * 180 / Math.PI; az = ha > 0 ? (th + 180) % 360 : (540 - th) % 360; }
    return { elevation: 90 - zen * 180 / Math.PI, azimut: az };
  }
  const webglOk = () => { try { const c = document.createElement("canvas"); return !!(window.WebGLRenderingContext && (c.getContext("webgl2") || c.getContext("webgl"))); } catch (e) { return false; } };

  /** Contrôleur d'orbite (glisser = orbite, molette = zoom, bouton droit ou Maj + glisser = déplacement), transitions douces. */
  function orbite(THREE, camera, dom, cible) {
    const INIT = { theta: -Math.PI / 4, phi: Math.PI / 3.6, r: 38 }; // 3/4 depuis le sud-ouest, maison cadrée
    const s = { ...INIT, cible: cible.clone(), drag: null, vise: null };
    const place = () => {
      s.phi = Math.max(0.03, Math.min(Math.PI / 2 - 0.01, s.phi)); s.r = Math.max(5, Math.min(220, s.r));
      camera.position.set(s.cible.x + s.r * Math.sin(s.phi) * Math.sin(s.theta), s.cible.y + s.r * Math.cos(s.phi), s.cible.z + s.r * Math.sin(s.phi) * Math.cos(s.theta));
      camera.lookAt(s.cible);
    };
    const onDown = (e) => { s.vise = null; s.drag = { x: e.clientX, y: e.clientY, mode: (e.button === 2 || e.shiftKey) ? "pan" : "orbit" }; e.preventDefault(); };
    const onMove = (e) => {
      if (!s.drag) return;
      const dx = e.clientX - s.drag.x, dy = e.clientY - s.drag.y; s.drag.x = e.clientX; s.drag.y = e.clientY;
      if (s.drag.mode === "orbit") { s.theta -= dx * 0.006; s.phi -= dy * 0.006; }
      else { const k = s.r * 0.0016; const droite = new THREE.Vector3(Math.cos(s.theta), 0, -Math.sin(s.theta)); const avant = new THREE.Vector3(-Math.sin(s.theta), 0, -Math.cos(s.theta)); s.cible.addScaledVector(droite, -dx * k).addScaledVector(avant, dy * k); }
      place();
    };
    const onUp = () => { s.drag = null; };
    const onWheel = (e) => { e.preventDefault(); s.vise = null; s.r *= Math.exp(e.deltaY * 0.0012); place(); };
    dom.addEventListener("mousedown", onDown); window.addEventListener("mousemove", onMove); window.addEventListener("mouseup", onUp);
    dom.addEventListener("wheel", onWheel, { passive: false }); dom.addEventListener("contextmenu", (e) => e.preventDefault());
    place();
    const vers = (v) => { s.vise = { ...v, t: 0, de: { theta: s.theta, phi: s.phi, r: s.r, cible: s.cible.clone() } }; };
    return {
      tick: () => {
        if (!s.vise) return; const v = s.vise; v.t = Math.min(1, v.t + 0.05); const k = 1 - Math.pow(1 - v.t, 3);
        const dth = ((v.theta - v.de.theta + Math.PI) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI) - Math.PI;
        s.theta = v.de.theta + dth * k; s.phi = v.de.phi + (v.phi - v.de.phi) * k; s.r = v.de.r + (v.r - v.de.r) * k; s.cible.lerpVectors(v.de.cible, v.cible, k); place(); if (v.t >= 1) s.vise = null;
      },
      immediat: () => { if (s.vise) { s.vise.t = 1; } },
      dessus: () => vers({ theta: 0, phi: 0.04, r: Math.min(s.r, 30), cible: cible.clone() }),
      sud: () => vers({ theta: 0, phi: Math.PI / 3.2, r: 30, cible: cible.clone() }),
      nord: () => vers({ theta: Math.PI, phi: Math.PI / 3.2, r: 30, cible: cible.clone() }),
      reset: () => vers({ ...INIT, cible: cible.clone() }),
      rue: (dir, hCam) => {
        const d = 28; const c = new THREE.Vector3(cible.x, 3.4, cible.z); const pos = new THREE.Vector3(cible.x + dir.x * d, hCam || 1.8, cible.z + dir.z * d);
        const theta = Math.atan2(pos.x - c.x, pos.z - c.z); const dy = pos.y - c.y; const horiz = Math.hypot(pos.x - c.x, pos.z - c.z); const r = Math.hypot(horiz, dy);
        vers({ theta, phi: Math.acos(Math.max(-1, Math.min(1, dy / r))), r, cible: c });
      },
      dispose: () => { dom.removeEventListener("mousedown", onDown); window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); dom.removeEventListener("wheel", onWheel); },
    };
  }

  function Solaire3DRE(props) {
    const hostRef = useRef(null);
    const sceneRef = useRef(null);
    const [etat, setEtat] = useState({ chargement: "Préparation…" });
    const [live, setLive] = useState(null);
    const [mois, setMois] = useState(6);
    const [heure, setHeure] = useState(13);
    const [lecture, setLecture] = useState(false);
    const [calqueSoleil, setCalqueSoleil] = useState(false);
    const [materiau, setMateriau] = useState("photo"); // "photo" : photo aérienne projetée sur le toit ; "modele" : bardeaux gris uniformes
    const [survol, setSurvol] = useState(null);
    const [modeRue, setModeRue] = useState(false);
    const [tick, setTick] = useState(0);
    const donnees = live || props;
    const site = { lat: props.lat, lng: props.lng };

    useEffect(() => {
      let alive = true;
      const THREE = window.THREE;
      if (!THREE) { setEtat({ err: "Bibliothèque 3D absente (three.js non chargé)." }); return; }
      if (!webglOk()) { setEtat({ err: "Ce navigateur n'a pas WebGL : la vue 3D n'est pas disponible ici." }); return; }
      if (!props.lat || !props.lng) { setEtat({ err: "Adresse sans coordonnées." }); return; }
      (async () => {
        try {
          setEtat({ chargement: "Lecture des couches Google Solar…" });
          const man = await getJson(`/raycast/solaire/couches?lat=${props.lat}&lon=${props.lng}&rayon=${RAYON_VUE_M}`);
          const c = man.couches || {};
          if (!c.rgb || !c.dsm) throw new Error("Couches photo ou relief indisponibles à cette adresse");
          const [rgb, dsm, mask, flux] = await Promise.all([getTiff(c.rgb), getTiff(c.dsm), c.mask ? getTiff(c.mask) : Promise.resolve(null), c.annualFlux ? getTiff(c.annualFlux).catch(() => null) : Promise.resolve(null)]);
          if (!alive) return;
          setEtat({ chargement: "Construction de la maison et du voisinage en 3D…" });
          await new Promise(r => setTimeout(r, 10));
          const t0 = performance.now();
          construire(THREE, { rgb, dsm, mask, flux, centre: man.centre || { lat: props.lat, lng: props.lng } });
          if (!alive) return;
          if (sceneRef.current) sceneRef.current.duree_scene_ms = Math.round(performance.now() - t0);
          setEtat({ pret: true, date: man.date_imagerie, qualite: man.qualite_imagerie });
        } catch (e) { if (alive) setEtat({ err: String(e.message || e) }); }
      })();
      return () => { alive = false; detruire(); };
    }, [props.lat, props.lng]); // eslint-disable-line

    useEffect(() => { if (sceneRef.current && etat.pret) poserPanneaux(donnees); }, [donnees.panneaux, donnees.modele, donnees.orientation, etat.pret]); // eslint-disable-line
    useEffect(() => { if (sceneRef.current && etat.pret) { construireBatiment(donnees); poserPanneaux(donnees); appliquerRue(modeRue); } }, [donnees.batiment, donnees.toit, etat.pret]); // eslint-disable-line
    useEffect(() => { if (sceneRef.current) placerSoleil(mois, heure); setTick(t => t + 1); }, [mois, heure, etat.pret]); // eslint-disable-line
    useEffect(() => { if (sceneRef.current) appliquerCalque(calqueSoleil); }, [calqueSoleil, materiau, etat.pret]); // eslint-disable-line
    useEffect(() => { if (sceneRef.current) appliquerRue(modeRue); }, [modeRue, etat.pret]); // eslint-disable-line
    useEffect(() => {
      if (!lecture) return;
      const id = setInterval(() => setHeure(h => { const n = Math.round((h + 0.25) * 4) / 4; return n > 20 ? 6 : n; }), 120);
      return () => clearInterval(id);
    }, [lecture]);
    useEffect(() => {
      const h = (e) => { if (e.detail) setLive({ ...props, ...e.detail }); };
      window.addEventListener("raycast:editeur", h);
      return () => window.removeEventListener("raycast:editeur", h);
    }, [props]); // eslint-disable-line

    /** Libère tout : boucle d'animation, écouteurs, géométries, matériaux, textures, contexte WebGL. */
    function detruire() {
      const S = sceneRef.current; if (!S) return;
      try {
        cancelAnimationFrame(S.raf); S.ctrl.dispose(); S.ro && S.ro.disconnect(); S.renderer.domElement.removeEventListener("pointermove", S.onPointer);
        const vus = new Set();
        S.scene.traverse(obj => { if (obj.geometry && !vus.has(obj.geometry)) { vus.add(obj.geometry); obj.geometry.dispose(); } const mats = Array.isArray(obj.material) ? obj.material : (obj.material ? [obj.material] : []); for (const m of mats) if (!vus.has(m)) { vus.add(m); m.dispose(); } });
        for (const k of Object.keys(S.tex)) { const t = S.tex[k]; if (t && typeof t.dispose === "function") t.dispose(); }
        if (S.geos) { for (const g of S.geos.feuillus) g.dispose(); S.geos.cone.dispose(); S.geos.tronc.dispose(); S.geos.corniche.dispose(); }
        if (S.mats) for (const m of Object.values(S.mats)) (Array.isArray(m) ? m : [m]).forEach(x => x.dispose());
        if (S.texPanneaux) S.texPanneaux.dispose(); if (S.matTop) S.matTop.dispose(); if (S.sol && S.sol.shadow) S.sol.shadow.dispose();
        S.renderer.dispose(); if (S.renderer.forceContextLoss) S.renderer.forceContextLoss(); S.renderer.domElement.remove();
      } catch (e) { /* noop */ }
      sceneRef.current = null; if (Solaire3DRE.derniereScene === S) Solaire3DRE.derniereScene = null;
    }
    const sombre = () => document.documentElement.getAttribute("data-theme") === "dark" || (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches && document.documentElement.getAttribute("data-theme") !== "light");
    const srgb = (THREE, tex) => { if ("colorSpace" in tex && THREE.SRGBColorSpace) tex.colorSpace = THREE.SRGBColorSpace; else if (THREE.sRGBEncoding) tex.encoding = THREE.sRGBEncoding; return tex; };

    /** Textures : photo aérienne (toit légèrement éclairci), variante « soleil » (dégradé jaune du flux sur le toit), sol propre (gazon
     *  mêlé à la photo : rues et entrées lisibles, couronnes d'arbres et toits effacés) et bardeaux gris (toit en mode « Modèle »). */
    function textures(THREE, rgb, mask, flux, arbres, rep) {
      const w = rgb.w, h = rgb.h;
      const R = rgb.bandes[0], Gb = rgb.bandes[1] || rgb.bandes[0], Bb = rgb.bandes[2] || rgb.bandes[0];
      const mk = mask && mask.w === w && mask.h === h ? mask.bandes[0] : null;
      const fx = flux && flux.w === w && flux.h === h ? flux.bandes[0] : null;
      let fmax = 0, fmin = Infinity;
      if (fx && mk) for (let i = 0; i < w * h; i++) if (mk[i] && isFinite(fx[i]) && fx[i] > 0) { if (fx[i] > fmax) fmax = fx[i]; if (fx[i] < fmin) fmin = fx[i]; }
      if (!isFinite(fmin)) fmin = 0;
      const canevas = () => { const cv = document.createElement("canvas"); cv.width = w; cv.height = h; const ctx = cv.getContext("2d"); return { cv, ctx, im: ctx.createImageData(w, h) }; };
      const faire = (soleilMode) => {
        const { cv, ctx, im } = canevas(); const d = im.data;
        const stops = [[64, 42, 20], [150, 80, 20], [230, 150, 30], [255, 220, 60], [255, 250, 150]];
        for (let i = 0, k = 0; i < w * h; i++, k += 4) {
          const t = mk && mk[i] ? 1 : 0;
          if (soleilMode && t && fx) {
            const v = Math.max(0, Math.min(1, (fx[i] - fmin) / Math.max(1, fmax - fmin)));
            const p = v * (stops.length - 1), i0 = Math.min(stops.length - 2, Math.floor(p)), f = p - i0;
            d[k] = stops[i0][0] + (stops[i0 + 1][0] - stops[i0][0]) * f; d[k + 1] = stops[i0][1] + (stops[i0 + 1][1] - stops[i0][1]) * f; d[k + 2] = stops[i0][2] + (stops[i0 + 1][2] - stops[i0][2]) * f; d[k + 3] = 255;
          } else { d[k] = Math.min(255, R[i] + 18 * t); d[k + 1] = Math.min(255, Gb[i] + 18 * t); d[k + 2] = Math.min(255, Bb[i] + 10 * t); d[k + 3] = 255; }
        }
        ctx.putImageData(im, 0, 0); return srgb(THREE, new THREE.CanvasTexture(cv));
      };
      // sol : gazon + photo (poids 0,5 ; 0,9 sur les surfaces grises = asphalte, béton ; 0,2 sous les couronnes et les toits), légèrement assombri
      const solTex = (() => {
        const { cv, ctx, im } = canevas(); const d = im.data; const G0 = [139, 176, 105];
        const sousArbre = new Float32Array(w * h); // 1 au centre d'une couronne, fondu jusqu'à 1,4 rayon
        if (arbres && rep) for (const t of arbres) { const p = rep.pxDe(t.lat, t.lng); if (!isFinite(p.x)) continue; const rp = 1.4 * t.rayon / rep.mPxX; const x0 = Math.max(0, Math.floor(p.x - rp)), x1 = Math.min(w - 1, Math.ceil(p.x + rp)), y0 = Math.max(0, Math.floor(p.y - rp)), y1 = Math.min(h - 1, Math.ceil(p.y + rp)); for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) { const d = Math.sqrt((x - p.x) ** 2 + (y - p.y) ** 2) / rp; if (d < 1) sousArbre[y * w + x] = Math.max(sousArbre[y * w + x], 1 - d * d); } }
        for (let i = 0, k = 0; i < w * h; i++, k += 4) {
          const r = R[i], g = Gb[i], b = Bb[i]; const mx = Math.max(r, g, b), mn = Math.min(r, g, b); const lum = (r + g + b) / 3;
          let wp = 0.42; if (mk && mk[i]) wp = 0.2; else if (mx - mn < 30 && lum > 70) wp = 0.92; wp = wp * (1 - sousArbre[i]) + 0.12 * sousArbre[i];
          const k2 = 0.93 * wp; d[k] = G0[0] * (1 - wp) + r * k2; d[k + 1] = G0[1] * (1 - wp) + g * k2; d[k + 2] = G0[2] * (1 - wp) + b * k2; d[k + 3] = 255;
        }
        ctx.putImageData(im, 0, 0); const t = srgb(THREE, new THREE.CanvasTexture(cv)); t.anisotropy = 4; return t;
      })();
      // bardeaux : rangées horizontales légèrement irrégulières, gris ardoise ; répétée tous les 0,8 m (les UV couvrent toute la tuile)
      const bardeaux = (() => {
        const cv = document.createElement("canvas"); cv.width = 128; cv.height = 128; const g = cv.getContext("2d");
        g.fillStyle = "#73777c"; g.fillRect(0, 0, 128, 128);
        for (let row = 0; row < 6; row++) { const y = Math.round(row * 128 / 6); g.fillStyle = row % 2 ? "#70747a" : "#767a80"; g.fillRect(0, y, 128, 22); g.fillStyle = "#62666c"; g.fillRect(0, y + 19, 128, 2); const dec = row % 2 ? 16 : 0; g.fillStyle = "#6a6e74"; for (let x = -1; x < 5; x++) g.fillRect(dec + x * 32, y, 1, 19); }
        const t = srgb(THREE, new THREE.CanvasTexture(cv)); t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(1, 1); if ("channel" in t) t.channel = 1; t.anisotropy = 4; return t;
      })();
      return { photo: faire(false), soleil: fx ? faire(true) : null, sol: solTex, bardeaux, fmax, fmin };
    }

    /** Hauteur du sol lissé (relative à zSol) en (e, n) mètres locaux depuis le coin nord-ouest ; 0 sans terrain. */
    function terrainA(S, e, n) {
      const T = S.terrain; if (!T) return 0;
      const fi = Math.max(0, Math.min(T.cols - 1.001, e / T.pas_e_m)), fj = Math.max(0, Math.min(T.rows - 1.001, -n / T.pas_n_m));
      const i0 = Math.floor(fi), j0 = Math.floor(fj), tx = fi - i0, ty = fj - j0; const z = (i, j) => S.terrainBase[j * T.cols + i];
      return z(i0, j0) * (1 - tx) * (1 - ty) + z(i0 + 1, j0) * tx * (1 - ty) + z(i0, j0 + 1) * (1 - tx) * ty + z(i0 + 1, j0 + 1) * tx * ty;
    }

    function construire(THREE, { rgb, dsm, mask, flux, centre }) {
      detruire();
      const host = hostRef.current; if (!host) return;
      const rep = repere(dsm);
      const w = dsm.w, h = dsm.h, b = dsm.bandes[0];
      const mk = mask && mask.w === w && mask.h === h ? mask.bandes[0] : null;
      const ech = [];
      for (let i = 0; i < w * h; i += 7) { const z = b[i]; if (isFinite(z) && z > -1000 && (!mk || !mk[i])) ech.push(z); }
      ech.sort((a, c) => a - c);
      // Modèle vectoriel (solaire-modele-re.js) : celui fourni par le studio (prop batiment) s'il est complet, sinon construit ici
      let batPre = null;
      const fourni = adapterBatiment(donnees.batiment);
      if (fourni && fourni.faces.length && fourni.nw && fourni.terrain) { batPre = fourni; batPre.duree_ms = 0; }
      else if (window.SolaireModele && typeof window.SolaireModele.construire === "function" && donnees.toit && Array.isArray(donnees.toit.segments) && mk) {
        try {
          const t0 = performance.now();
          const repM = window.SolaireGeom && window.SolaireGeom.repere ? window.SolaireGeom.repere(dsm) : repereModele(dsm);
          const mod = window.SolaireModele.construire({ rgb, dsm, masque: mask, flux: flux || null, repere: repM, segments: donnees.toit.segments });
          batPre = adapterBatiment(mod);
          if (batPre && batPre.faces.length) { batPre.nw = true; batPre.duree_ms = Math.round(performance.now() - t0); } else batPre = null;
        } catch (e) { console.warn("Modèle vectoriel indisponible, modèle approximatif utilisé :", e && e.message); batPre = null; }
      }
      const zSol = batPre && batPre.sol_m != null ? batPre.sol_m : (ech.length ? ech[Math.floor(ech.length * 0.05)] : 0);

      const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true, powerPreference: "high-performance" });
      renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
      renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      if ("outputColorSpace" in renderer && THREE.SRGBColorSpace) renderer.outputColorSpace = THREE.SRGBColorSpace;
      else if ("outputEncoding" in renderer && THREE.sRGBEncoding) renderer.outputEncoding = THREE.sRGBEncoding;
      if ("toneMapping" in renderer && THREE.ACESFilmicToneMapping) { renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05; }
      host.appendChild(renderer.domElement);
      const scene = new THREE.Scene();
      const fond = new THREE.Color(sombre() ? 0x0b1b2b : 0xdbe7f3);
      scene.background = fond; scene.fog = new THREE.Fog(fond, 160, 420);
      const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000);

      const sol = new THREE.DirectionalLight(0xffffff, 2.4);
      sol.castShadow = true; sol.shadow.mapSize.set(2048, 2048);
      const sc = sol.shadow.camera; sc.left = -62; sc.right = 62; sc.top = 62; sc.bottom = -62; sc.near = 10; sc.far = 420; sol.shadow.bias = -0.0006; sol.shadow.normalBias = 0.03; sol.shadow.radius = 2;
      scene.add(sol); scene.add(sol.target);
      const ciel = new THREE.HemisphereLight(0xdfe9f3, 0x8a7a66, 1.0); scene.add(ciel);

      const tex = textures(THREE, rgb, mask, flux, batPre ? batPre.arbres.map(t => ({ ...t, ...rep.latLngDe(t.e, -t.n) })) : [], rep);
      // Sol propre : grille lissée du terrain (41 × 41, sans arbres ni bâtiments) texturée gazon + photo ; plan de gazon à perte de vue dessous
      const T = batPre && batPre.terrain; const cols = T ? T.cols : 2, rows = T ? T.rows : 2;
      const geo = new THREE.PlaneGeometry(rep.largeurM, rep.hauteurM, cols - 1, rows - 1); geo.rotateX(-Math.PI / 2);
      const terrainBase = new Float32Array(cols * rows); if (T) terrainBase.set(T.z);
      const pos = geo.attributes.position; for (let k = 0; k < cols * rows; k++) pos.setY(k, terrainBase[k]);
      geo.computeVertexNormals();
      const relief = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: tex.sol, roughness: 1, metalness: 0 }));
      relief.receiveShadow = true; relief.position.set(rep.largeurM / 2, 0, rep.hauteurM / 2); scene.add(relief);
      const gazon = new THREE.Mesh(new THREE.PlaneGeometry(900, 900), new THREE.MeshStandardMaterial({ color: 0x86ab66, roughness: 1, metalness: 0 }));
      gazon.rotateX(-Math.PI / 2); gazon.position.set(rep.largeurM / 2, -0.12 + (T ? Math.min(...T.z) : 0), rep.hauteurM / 2); gazon.receiveShadow = true; scene.add(gazon);

      const pc = rep.sceneDe(centre.lat, centre.lng);
      const cible = new THREE.Vector3(pc.x, 4.5, pc.z);
      sol.target.position.set(pc.x, 0, pc.z);
      const ctrl = orbite(THREE, camera, renderer.domElement, cible);
      const groupes = { batiment: new THREE.Group(), voisins: new THREE.Group(), arbres: new THREE.Group(), panneaux: new THREE.Group() };
      for (const g of Object.values(groupes)) scene.add(g);

      // Direction de la rue : couloir (32 secteurs, 9 à 30 m, trois rayons parallèles) le plus bas et le plus dégagé (relief, arbres, voisins)
      let rueDir = { x: 0, z: 1 }; let meilleur = Infinity;
      const arbresNW = batPre && batPre.nw ? batPre.arbres : [], voisinsNW = batPre && batPre.nw ? batPre.voisins : [];
      for (let k = 0; k < 32; k++) {
        const a = k / 32 * 2 * Math.PI; const dx = Math.sin(a), dz = Math.cos(a); let somme = 0, n = 0;
        for (let r = 9; r <= 30; r += 1.5) for (const lat of [-3, 0, 3]) {
          const sx = pc.x + dx * r - dz * lat, sz = pc.z + dz * r + dx * lat;
          const x = sx / rep.mPxX, y = sz / rep.mPxY; const z = valeurA(dsm, x, y);
          if (isFinite(z)) { somme += Math.max(0, z - zSol - 0.4); n++; } else { somme += 6; n++; }
          for (const t of arbresNW) if (Math.hypot(t.e - sx, -t.n - sz) <= t.rayon + 1) { somme += t.hauteur; break; }
          for (const v of voisinsNW) if (dansPolygone(v.polygone_2d, sx, -sz)) { somme += v.hauteur_faite_m; break; }
        }
        if (n && somme / n < meilleur) { meilleur = somme / n; rueDir = { x: dx, z: dz }; }
      }
      // géométries partagées (couronnes légèrement irrégulières, cône, tronc, corniche) : créées une fois, libérées au démontage
      const bruit = (x, y, z) => Math.abs(Math.sin(x * 12.9898 + y * 78.233 + z * 37.719) * 43758.5453) % 1;
      const geos = { feuillus: [], cone: null, tronc: null, corniche: new THREE.BoxGeometry(1, 0.22, 0.3) };
      for (let k = 0; k < 3; k++) { const gc = new THREE.IcosahedronGeometry(1, 3); const pa = gc.attributes.position; for (let i = 0; i < pa.count; i++) { const x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i); const f = 0.94 + 0.12 * bruit(x + k, y, z); pa.setXYZ(i, x * f, y * f, z * f); } gc.computeVertexNormals(); geos.feuillus.push(gc); }
      geos.cone = new THREE.ConeGeometry(1, 1, 10); geos.cone.translate(0, 0.5, 0);
      geos.tronc = new THREE.CylinderGeometry(0.8, 1, 1, 8); geos.tronc.translate(0, 0.5, 0);
      const S = { THREE, renderer, scene, camera, ctrl, rep, dsm, mask, flux, zSol, centre, pc, groupes, relief, terrain: T || null, terrainBase, cols, rows, tex, sol, ciel, rueDir, rueH: 1.8, batPre, ro: null, raf: 0, onPointer: null, faces: [], batiment: null, matFaces: [], fmax: tex.fmax, geos, modeRue: false, materiau };
      const zCam = terrainA(S, pc.x + rueDir.x * 28, -(pc.z + rueDir.z * 28)); S.rueH = Math.max(1.8, zCam + 1.75);

      const taille = () => { const r = host.getBoundingClientRect(); const W = Math.max(320, r.width), H = Math.max(240, r.height); renderer.setSize(W, H, false); camera.aspect = W / H; camera.updateProjectionMatrix(); };
      taille();
      const ro = window.ResizeObserver ? new ResizeObserver(taille) : null; ro && ro.observe(host); S.ro = ro;
      const raycaster = new THREE.Raycaster(); const souris = new THREE.Vector2();
      const onPointer = (e) => {
        const S2 = sceneRef.current; if (!S2) return;
        const r = renderer.domElement.getBoundingClientRect(); souris.x = ((e.clientX - r.left) / r.width) * 2 - 1; souris.y = -((e.clientY - r.top) / r.height) * 2 + 1;
        raycaster.setFromCamera(souris, camera);
        const hit = raycaster.intersectObjects(groupes.panneaux.children.filter(m => m.userData.panneau), false)[0];
        if (hit && hit.object.userData && hit.object.userData.panneau) { setSurvol({ ...hit.object.userData.panneau, x: e.clientX - r.left, y: e.clientY - r.top }); renderer.domElement.style.cursor = "pointer"; }
        else { setSurvol(null); renderer.domElement.style.cursor = "grab"; }
      };
      renderer.domElement.addEventListener("pointermove", onPointer); S.onPointer = onPointer;
      sceneRef.current = S; Solaire3DRE.derniereScene = S;
      const boucle = () => { S.raf = requestAnimationFrame(boucle); ctrl.tick(); renderer.render(scene, camera); };
      boucle();
      construireBatiment(donnees);
      placerSoleil(mois, heure);
      poserPanneaux(donnees);
    }

    /** Vide un groupe en libérant géométries et matériaux propres (les matériaux partagés sont marqués userData.partage). */
    function vider(groupe) {
      groupe.traverse(obj => { if (obj === groupe) return; if (obj.geometry && !(obj.userData && obj.userData.geoPartagee)) obj.geometry.dispose(); const mats = Array.isArray(obj.material) ? obj.material : (obj.material ? [obj.material] : []); for (const m of mats) if (!(m.userData && m.userData.partage)) m.dispose(); if (obj.userData && obj.userData.matTrans) { obj.userData.matTrans.dispose(); obj.userData.matTrans = null; obj.userData.matOpaque = null; } });
      while (groupe.children.length) groupe.remove(groupe.children[0]);
    }
    const partage = (m) => { m.userData.partage = true; return m; };
    /** Matériaux partagés de la scène (murs, corniche, cheminées, voisins, arbres) : créés une fois, libérés au démontage. */
    function materiaux(S) {
      if (S.mats) return S.mats; const THREE = S.THREE;
      const M = (opts) => partage(new THREE.MeshStandardMaterial(opts));
      S.mats = { mur: M({ color: 0xe9e1d3, roughness: 0.96, metalness: 0, side: THREE.DoubleSide }), corniche: M({ color: 0xf4efe6, roughness: 0.9, metalness: 0 }), obs: M({ color: 0x8c8a86, roughness: 0.9 }), cap: M({ color: 0x5a5a5c, roughness: 0.8 }),
        murV: M({ color: 0xe4dccd, roughness: 0.95, metalness: 0 }), toitV: M({ color: 0x7c8086, roughness: 0.9, metalness: 0, side: THREE.DoubleSide }), areteV: partage(new THREE.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.5 })),
        feuillus: [0x4f8a3a, 0x5a9440, 0x47803a, 0x6b9e48].map(c => M({ color: c, roughness: 0.95, metalness: 0 })), coniferes: [0x3d7a44, 0x44844a].map(c => M({ color: c, roughness: 0.95, metalness: 0 })), tronc: M({ color: 0x5a4632, roughness: 0.95 }),
        cote: M({ color: 0xb8c4d0, roughness: 0.5, metalness: 0.5 }), cadre: partage(new THREE.LineBasicMaterial({ color: 0xd9e0e7, transparent: true, opacity: 0.9 })) };
      return S.mats;
    }

    /** Maison : faces (photo projetée ou bardeaux), arêtes typées, murs beige + corniche, cheminées ; voisins en volumes ; arbres ; sol aplati. */
    function construireBatiment(data) {
      const S = sceneRef.current; if (!S) return;
      const { THREE, rep, zSol, groupes, relief, tex } = S;
      vider(groupes.batiment); vider(groupes.voisins); vider(groupes.arbres);
      let bat = adapterBatiment(data.batiment);
      if ((!bat || !bat.faces.length) && S.batPre) bat = S.batPre;
      if (!bat || !bat.faces.length) bat = modeleDepuisToit(data.toit, zSol);
      S.matFaces = [];
      if (!bat) { S.faces = []; S.batiment = null; return; }
      // Repère du modèle : coin nord-ouest du raster (modèle vectoriel, n négatif vers le sud) ou origine lat/lng (prop batiment, modèle approximatif)
      const nw = !!bat.nw;
      const origine = nw ? null : (bat.origine || S.centre);
      const o = nw ? { x: 0, z: 0 } : rep.sceneDe(origine.lat, origine.lng);
      const M = nw ? { versLocal: (lat, lng) => { const q = rep.sceneDe(lat, lng); return { e: q.x, n: -q.z }; }, versLatLng: (e, n) => rep.latLngDe(e, -n) } : metres(origine);
      const dy = bat.sol_m != null ? bat.sol_m - zSol : 0;
      const V = (p) => new THREE.Vector3(o.x + p.e, p.z + dy, o.z - p.n);
      const uvDe = (v) => [v.x / rep.largeurM, 1 - v.z / rep.hauteurM];
      S.batiment = bat; S.origineScene = o; S.M = M; S.dy = dy;

      S.faces = bat.faces.map(f => ({ ...f, plan: planDe(f.polygone) }));
      for (const f of S.faces) {
        const P = f.polygone; const pl = f.plan;
        const hn = Math.hypot(pl.n.e, pl.n.n);
        const u2 = hn < 1e-6 ? { e: 1, n: 0 } : { e: -pl.n.n / hn, n: pl.n.e / hn };
        const P2 = P.map(p => ({ u: p.e * u2.e + p.n * u2.n, v: hn < 1e-6 ? p.n : (-(p.e * u2.n - p.n * u2.e) * pl.n.z + p.z * hn) }));
        const tri = triangulerOreilles(P2);
        const g = new THREE.BufferGeometry(); const pos = [], uv = [], uv1 = []; // uv : photo (toute la tuile) ; uv1 : bardeaux (repère de la face, rangées parallèles à l'égout, 1 u = 1 m)
        for (const p of P) { const v = V(p); pos.push(v.x, v.y, v.z); uv.push(...uvDe(v)); }
        for (const q of P2) uv1.push(q.u / 0.9, q.v / 0.9);
        g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3)); g.setAttribute("uv", new THREE.Float32BufferAttribute(uv, 2)); g.setAttribute("uv1", new THREE.Float32BufferAttribute(uv1, 2)); g.setIndex(tri); g.computeVertexNormals();
        const ombre = 1 - 0.28 * Math.sin(pl.pente * Math.PI / 180);
        const mat = new THREE.MeshStandardMaterial({ map: tex.photo, color: new THREE.Color(ombre, ombre, ombre), roughness: 0.9, metalness: 0, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1, side: THREE.DoubleSide });
        S.matFaces.push(mat);
        const mesh = new THREE.Mesh(g, mat); mesh.castShadow = true; mesh.receiveShadow = true; mesh.userData.face = f; groupes.batiment.add(mesh);
      }
      const couleurs = { faite: 0xffffff, arete: 0xf4f7fa, noue: 0xd6e4f0, rive: 0xeef2f6, egout: 0xe2e8ee };
      const parType = {};
      for (const a of bat.aretes) (parType[a.type] = parType[a.type] || []).push(a);
      for (const [type, liste] of Object.entries(parType)) {
        const pts = []; for (const a of liste) { const A = V(a.a), B = V(a.b); pts.push(A.x, A.y + 0.03, A.z, B.x, B.y + 0.03, B.z); }
        const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.Float32BufferAttribute(pts, 3));
        groupes.batiment.add(new THREE.LineSegments(g, new THREE.LineBasicMaterial({ color: couleurs[type] || 0xffffff, transparent: true, opacity: type === "faite" ? 0.95 : 0.8 })));
      }
      const mats = materiaux(S); const matMur = mats.mur, matCorniche = mats.corniche;
      const geoCorniche = S.geos.corniche;
      for (const m of bat.murs) {
        const P = m.polygone.map(p => p.z <= 0.01 ? { e: p.e, n: p.n, z: -1 } : p); if (P.length < 3) continue;
        const a = P[0], bq = P[1]; const L = Math.hypot(bq.e - a.e, bq.n - a.n) || 1; const ux = (bq.e - a.e) / L, un = (bq.n - a.n) / L;
        const P2 = P.map(p => ({ u: (p.e - a.e) * ux + (p.n - a.n) * un, v: p.z }));
        const tri = triangulerOreilles(P2);
        const g = new THREE.BufferGeometry(); const pos = [];
        for (const p of P) { const v = V(p); pos.push(v.x, v.y, v.z); }
        g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3)); g.setIndex(tri); g.computeVertexNormals();
        const mesh = new THREE.Mesh(g, matMur); mesh.castShadow = true; mesh.receiveShadow = true; groupes.batiment.add(mesh);
        const hauts = P.filter(p => p.z > 0.5).slice(0, 2);
        if (hauts.length === 2) {
          const A = V(hauts[0]), B = V(hauts[1]); const len = A.distanceTo(B); if (len < 0.5) continue;
          const box = new THREE.Mesh(geoCorniche, matCorniche); box.userData.geoPartagee = true; box.scale.x = len;
          box.position.copy(A.clone().add(B).multiplyScalar(0.5)); box.position.y = Math.min(A.y, B.y) - 0.1;
          const dirx = B.x - A.x, dirz = B.z - A.z; box.rotation.y = Math.atan2(dirx, dirz) - Math.PI / 2;
          const nx = dirz / len, nz = -dirx / len;
          const versExt = ((box.position.x - S.pc.x) * nx + (box.position.z - S.pc.z) * nz) >= 0 ? 1 : -1;
          box.position.x += nx * 0.12 * versExt; box.position.z += nz * 0.12 * versExt;
          box.castShadow = true; groupes.batiment.add(box);
        }
      }
      // cheminées et obstacles : boîte gris pierre avec couronnement plus sombre
      const matObs = mats.obs, matCap = mats.cap;
      for (const ob of bat.obstacles) {
        const zBase = ob.z != null ? ob.z : (hauteurToit(S, ob.e, ob.n) ?? 0);
        const box = new THREE.Mesh(new THREE.BoxGeometry(ob.largeur, ob.hauteur, ob.profondeur), matObs);
        box.position.copy(V({ e: ob.e, n: ob.n, z: zBase + ob.hauteur / 2 - 0.15 })); box.rotation.y = -(ob.azimut_deg || 0) * Math.PI / 180;
        box.castShadow = true; box.receiveShadow = true; groupes.batiment.add(box);
        const cap = new THREE.Mesh(new THREE.BoxGeometry(ob.largeur + 0.1, 0.08, ob.profondeur + 0.1), matCap); cap.position.copy(box.position); cap.position.y = zBase + ob.hauteur - 0.15 + dy + 0.04; cap.rotation.y = box.rotation.y; groupes.batiment.add(cap);
      }
      // voisins : volumes simples (murs beige clair, toit gris plat / deux pans / quatre pans / monopente, arêtes fines), posés sur le sol lissé
      const matMurV = mats.murV, matToitV = mats.toitV, matAreteV = mats.areteV;
      const volumeDe = (v, base) => {
        if (window.SolaireModele && typeof window.SolaireModele.volumeVoisin === "function") return window.SolaireModele.volumeVoisin(v, { base, enfoncement: 1.2, debord: 0.3 });
        // repli : contour extrudé à l'égout, toit plat
        const P = v.polygone_2d; const murs = [], idx = [], toit = [], tidx = []; const he = base + (v.hauteur_egout_m || 3);
        P.forEach((a, k) => { const b = P[(k + 1) % P.length]; const i0 = murs.length / 3; murs.push(a.e, base - 1, -a.n, b.e, base - 1, -b.n, b.e, he, -b.n, a.e, he, -a.n); idx.push(i0, i0 + 1, i0 + 2, i0, i0 + 2, i0 + 3); toit.push(a.e, he, -a.n); });
        const tri = triangulerOreilles(P.map(p => ({ u: p.e, v: p.n }))); tidx.push(...tri);
        return { murs: { positions: new Float32Array(murs), indices: new Uint16Array(idx), normales: null }, toit: { positions: new Float32Array(toit), indices: new Uint16Array(tidx), normales: null }, aretes: new Float32Array(0) };
      };
      const geoDe = (part) => { const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.BufferAttribute(part.positions, 3)); if (part.normales && part.normales.length) g.setAttribute("normal", new THREE.BufferAttribute(part.normales, 3)); g.setIndex(new THREE.BufferAttribute(part.indices, 1)); if (!part.normales || !part.normales.length) g.computeVertexNormals(); return g; };
      for (const v of (bat.voisins || [])) {
        if (!v.polygone_2d || v.polygone_2d.length < 3) continue;
        const c = v.centre || v.polygone_2d.reduce((s, p) => ({ e: s.e + p.e / v.polygone_2d.length, n: s.n + p.n / v.polygone_2d.length }), { e: 0, n: 0 });
        const base = terrainA(S, c.e, c.n) + dy - 0.05;
        let vol; try { vol = volumeDe(v, base); } catch (e) { continue; }
        const grp = new THREE.Group(); grp.userData.objet = { x: o.x + c.e, z: o.z - c.n, rayon: Math.sqrt((v.surface_m2 || 50) / Math.PI) + 1, type: "voisin" };
        const murs = new THREE.Mesh(geoDe(vol.murs), matMurV); murs.castShadow = true; murs.receiveShadow = true; murs.position.set(o.x, 0, o.z); grp.add(murs);
        const toit = new THREE.Mesh(geoDe(vol.toit), matToitV); toit.castShadow = true; toit.receiveShadow = true; toit.position.set(o.x, 0, o.z); grp.add(toit);
        if (vol.aretes && vol.aretes.length) { const ga = new THREE.BufferGeometry(); ga.setAttribute("position", new THREE.BufferAttribute(vol.aretes, 3)); const li = new THREE.LineSegments(ga, matAreteV); li.position.set(o.x, 0.02, o.z); grp.add(li); }
        groupes.voisins.add(grp);
      }
      // arbres : feuillus = couronne ellipsoïdale légèrement irrégulière (vert feuillage mat), conifères = cône ; tronc ; ombres portées
      const bruit = (x, y, z) => Math.abs(Math.sin(x * 12.9898 + y * 78.233 + z * 37.719) * 43758.5453) % 1;
      const geosF = S.geos.feuillus, geoCone = S.geos.cone, geoTronc = S.geos.tronc;
      const matsF = mats.feuillus, matsC = mats.coniferes, matTronc = mats.tronc;
      bat.arbres.forEach((t, k) => {
        const baseY = terrainA(S, t.e, t.n) + dy; const base = V({ e: t.e, n: t.n, z: baseY });
        const grp = new THREE.Group(); grp.userData.objet = { x: base.x, z: base.z, rayon: t.rayon, type: "arbre" };
        const conifere = t.forme === "conifere"; const hT = Math.max(0.8, Math.min(t.hauteur_tronc, t.hauteur - 1)); const hc = Math.max(1.2, t.hauteur - hT);
        const tronc = new THREE.Mesh(geoTronc, matTronc); tronc.userData.geoPartagee = true; const rT = Math.max(0.1, Math.min(0.45, t.rayon * 0.09)); tronc.scale.set(rT, hT + (conifere ? 0.3 : 0.5), rT); tronc.position.set(base.x, base.y - 0.1, base.z); tronc.castShadow = true; grp.add(tronc);
        const geoC = conifere ? geoCone : geosF[k % 3]; const mat = conifere ? matsC[k % 2] : matsF[k % 4];
        const can = new THREE.Mesh(geoC, mat); can.userData.geoPartagee = true; can.userData.couronne = true;
        if (conifere) { can.scale.set(t.rayon, hc, t.rayon); can.position.set(base.x, base.y + hT, base.z); }
        else { can.scale.set(t.rayon, hc / 2, t.rayon * (0.92 + 0.16 * bruit(k, 1, 2))); can.rotation.y = bruit(k, 3, 4) * Math.PI; can.position.set(base.x, base.y + hT + hc / 2, base.z); }
        can.castShadow = true; can.receiveShadow = true; grp.add(can);
        groupes.arbres.add(grp);
      });
      // Sol aplati sous l'emprise de la maison (jusqu'à 1,2 m, fondu jusqu'à 5 m) ; ailleurs le terrain lissé
      const emprises = (bat.emprises && bat.emprises.length) ? bat.emprises : (bat.emprise.length ? [bat.emprise] : bat.faces.map(f => f.polygone));
      const pos = relief.geometry.attributes.position; const px0 = relief.position.x, pz0 = relief.position.z;
      for (let k = 0; k < S.cols * S.rows; k++) {
        const x = px0 + pos.getX(k), z = pz0 + pos.getZ(k); const e = x - o.x, n = o.z - z;
        let dmin = Infinity; for (const E of emprises) { const d = distPolygone(E, e, n); if (d < dmin) dmin = d; }
        const base = S.terrainBase[k]; const plat = 0.02 + Math.max(0, dy);
        pos.setY(k, dmin <= 1.2 ? Math.min(base, plat) : dmin < 5 ? base + (Math.min(base, plat) - base) * (1 - (dmin - 1.2) / 3.8) : base);
      }
      pos.needsUpdate = true; relief.geometry.computeVertexNormals();
      appliquerCalque(calqueSoleil);
    }
    function faceSous(S, e, n, tol = 1.5) {
      let best = null, bd = Infinity;
      for (const f of S.faces) { const d = distPolygone(f.polygone, e, n); if (d < bd) { bd = d; best = f; } }
      return bd <= tol ? best : null;
    }
    function hauteurToit(S, e, n) { const f = faceSous(S, e, n, 1e9); return f ? f.plan.zA(e, n) : null; }

    /** Texture des cellules d'un panneau (cadre sombre fin, cellules bleu nuit, lignes claires). */
    function textureCellules(THREE, portrait) {
      const cv = document.createElement("canvas"); cv.width = 256; cv.height = 512; const g = cv.getContext("2d");
      g.fillStyle = "#1b2430"; g.fillRect(0, 0, 256, 512);
      g.fillStyle = "#0e2b4a"; g.fillRect(8, 8, 240, 496);
      const nx = portrait ? 6 : 12, ny = portrait ? 12 : 6;
      g.strokeStyle = "#2e5f8f"; g.lineWidth = 2;
      for (let i = 1; i < nx; i++) { g.beginPath(); g.moveTo(8 + i * 240 / nx, 8); g.lineTo(8 + i * 240 / nx, 504); g.stroke(); }
      for (let j = 1; j < ny; j++) { g.beginPath(); g.moveTo(8, 8 + j * 496 / ny); g.lineTo(248, 8 + j * 496 / ny); g.stroke(); }
      return srgb(THREE, new THREE.CanvasTexture(cv));
    }
    /** Coins d'un panneau (vus du ciel) depuis son centre, la face (ou le pan), le modèle et l'orientation. */
    function coinsDe(p, pans, modele, orientation, face) {
      if (p.coins && p.coins.length === 4) return p.coins;
      const seg = (pans || []).find(s => s.index === p.pan) || {};
      const az = face ? face.plan.azimut : (Number(seg.azimut_deg) || 0), pente = face ? face.plan.pente : (Number(seg.pente_deg) || 0);
      const w = orientation === "paysage" ? modele.h : modele.w, hh = (orientation === "paysage" ? modele.w : modele.h) * Math.cos(pente * Math.PI / 180);
      const rad = az * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad);
      const mLat = 1 / 111320, mLng = 1 / (111320 * Math.cos(p.lat * Math.PI / 180));
      return [[-w / 2, -hh / 2], [w / 2, -hh / 2], [w / 2, hh / 2], [-w / 2, hh / 2]].map(([x, y]) => {
        const est = x * cos + y * sin, nord = -x * sin + y * cos;
        return { lat: p.lat + nord * mLat, lng: p.lng + est * mLng };
      });
    }

    /** Panneaux : plaque sur le plan exact de la face (sinon sur le relief), cadre aluminium, cellules, reflet selon l'angle avec le soleil. */
    function poserPanneaux(data) {
      const S = sceneRef.current; if (!S) return;
      const { THREE, rep, dsm, zSol, groupes, flux } = S;
      vider(groupes.panneaux);
      const DEFAUT = { w: 1.134, h: 1.961, watts: 500 };
      const cat = window.SolaireMoteur && window.SolaireMoteur.MODELES;
      const modele = typeof data.modele === "string" ? ((cat && cat[data.modele]) || DEFAUT) : (data.modele && data.modele.w ? data.modele : DEFAUT);
      const watts = Number(modele.watts || 500);
      const orientation = data.orientation || "portrait";
      const liste = Array.isArray(data.panneaux) ? data.panneaux : [];
      if (!liste.length) return;
      const texTop = textureCellules(THREE, orientation !== "paysage");
      const mats = materiaux(S); const matCote = mats.cote, matCadre = mats.cadre;
      if (S.matTop) S.matTop.dispose(); if (S.texPanneaux) S.texPanneaux.dispose();
      const matTop = partage(new THREE.MeshPhysicalMaterial({ map: texTop, roughness: 0.3, metalness: 0.3, clearcoat: 0.7, clearcoatRoughness: 0.2 })); S.matTop = matTop; S.texPanneaux = texTop;
      const EP = 0.04, SUREL = 0.12;
      const M = S.M || metres(S.centre); const o = S.origineScene || rep.sceneDe(S.centre.lat, S.centre.lng); const dy = S.dy || 0;
      const cadres = [];
      for (const p of liste) {
        const loc = M.versLocal(p.lat, p.lng);
        const memePan = S.faces.filter(f => f.pan === p.pan);
        const face = memePan.length === 1 ? memePan[0] : memePan.length > 1 ? memePan.slice().sort((a, b) => distPolygone(a.polygone, loc.e, loc.n) - distPolygone(b.polygone, loc.e, loc.n))[0] : (S.faces.length ? faceSous(S, loc.e, loc.n) : null);
        const coins = coinsDe(p, data.pans, modele, orientation, face);
        if (!coins || coins.length !== 4) continue;
        let haut;
        if (face) {
          const nrm = new THREE.Vector3(face.plan.n.e, face.plan.n.z, -face.plan.n.n).normalize();
          haut = coins.map(c => { const l = M.versLocal(c.lat, c.lng); return new THREE.Vector3(o.x + l.e, face.plan.zA(l.e, l.n) + dy, o.z - l.n).addScaledVector(nrm, SUREL); });
        } else {
          const pts = coins.map(c => { const px = rep.pxDe(c.lat, c.lng); const sc = rep.sceneDe(c.lat, c.lng); const v = valeurA(dsm, px.x, px.y); return new THREE.Vector3(sc.x, Math.max(0.2, (isFinite(v) ? v : zSol) - zSol + SUREL + 0.06), sc.z); });
          const cy = pts.reduce((t, v) => t + v.y, 0) / 4; haut = pts.map(v => v.clone().setY(cy));
        }
        const n = new THREE.Vector3().subVectors(haut[1], haut[0]).cross(new THREE.Vector3().subVectors(haut[3], haut[0])).normalize(); if (n.y < 0) n.negate();
        const bas = haut.map(v => v.clone().addScaledVector(n, -EP));
        const g = new THREE.BufferGeometry(); const Vv = [], UV = [];
        const push = (v, u, w2) => { Vv.push(v.x, v.y, v.z); UV.push(u, w2); };
        push(haut[0], 0, 0); push(haut[1], 1, 0); push(haut[2], 1, 1); push(haut[0], 0, 0); push(haut[2], 1, 1); push(haut[3], 0, 1);
        g.setAttribute("position", new THREE.Float32BufferAttribute(Vv, 3)); g.setAttribute("uv", new THREE.Float32BufferAttribute(UV, 2)); g.computeVertexNormals();
        let fluxMoy = null;
        if (flux) { const ech = [p, ...coins].map(c => { const px = rep.pxDe(c.lat, c.lng); return valeurA(flux, px.x, px.y); }).filter(v => isFinite(v) && v > 0); if (ech.length) fluxMoy = ech.reduce((s, v) => s + v, 0) / ech.length; }
        const production = fluxMoy != null ? Math.round(fluxMoy * (Number(p.watts) || watts) / 1000 * ((window.SolaireMoteur && window.SolaireMoteur.RENDEMENT_AC) || 0.85)) : null; // même rendement AC que le studio
        const acces = fluxMoy != null && S.fmax ? Math.round(fluxMoy / S.fmax * 100) : null;
        const top = new THREE.Mesh(g, matTop); top.castShadow = true; top.receiveShadow = true;
        top.userData.panneau = { pan: p.pan, production, acces, flux: fluxMoy != null ? Math.round(fluxMoy) : null, orientation: face ? face.plan.azimut : null, pente: face ? face.plan.pente : null, watts: Number(p.watts) || watts };
        groupes.panneaux.add(top);
        const gc = new THREE.BufferGeometry(); const VC = [];
        for (let i = 0; i < 4; i++) { const a = haut[i], bq = haut[(i + 1) % 4], c2 = bas[(i + 1) % 4], d2 = bas[i]; VC.push(a.x, a.y, a.z, bq.x, bq.y, bq.z, c2.x, c2.y, c2.z, a.x, a.y, a.z, c2.x, c2.y, c2.z, d2.x, d2.y, d2.z); }
        gc.setAttribute("position", new THREE.Float32BufferAttribute(VC, 3)); gc.computeVertexNormals();
        const cote = new THREE.Mesh(gc, matCote); cote.castShadow = true; groupes.panneaux.add(cote);
        for (let i = 0; i < 4; i++) { const a = haut[i].clone().addScaledVector(n, 0.012), bq = haut[(i + 1) % 4].clone().addScaledVector(n, 0.012); cadres.push(a.x, a.y, a.z, bq.x, bq.y, bq.z); }
      }
      if (cadres.length) { const gl = new THREE.BufferGeometry(); gl.setAttribute("position", new THREE.Float32BufferAttribute(cadres, 3)); const li = new THREE.LineSegments(gl, matCadre); li.userData.cadre = true; groupes.panneaux.add(li); }
    }

    /** Soleil : position NOAA pour le site, lumière directionnelle et ambiance selon la hauteur. */
    function placerSoleil(m, h) {
      const S = sceneRef.current; if (!S) return;
      const { THREE, sol, ciel, scene, pc } = S;
      const s = soleil(site.lat, site.lng, m, h);
      const el = s.elevation * Math.PI / 180, az = s.azimut * Math.PI / 180;
      const d = 150; const dir = new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el));
      sol.position.set(pc.x + dir.x * d, Math.max(2, dir.y * d), pc.z + dir.z * d); sol.target.position.set(pc.x, 0, pc.z); sol.target.updateMatrixWorld();
      const jour = Math.max(0, Math.min(1, (s.elevation + 4) / 20));
      sol.intensity = 0.15 + 2.3 * jour; sol.color.setHSL(0.1, 0.5 * (1 - jour) + 0.1, 0.5 + 0.5 * jour);
      ciel.intensity = 0.35 + 0.75 * jour;
      const fondJour = new THREE.Color(sombre() ? 0x0b1b2b : 0xdbe7f3), fondNuit = new THREE.Color(0x101a2a);
      scene.background = fondNuit.clone().lerp(fondJour, Math.max(0.15, jour)); scene.fog.color.copy(scene.background);
      S.soleilInfo = s;
    }
    /** Calque « Soleil » (dégradé jaune du flux annuel) ou matériau du toit : photo projetée assombrie par la pente, ou bardeaux gris. */
    function appliquerCalque(on) {
      const S = sceneRef.current; if (!S || !S.matFaces) return;
      S.materiau = materiau;
      for (const mesh of S.groupes.batiment.children) {
        if (!mesh.userData.face || !mesh.material) continue;
        const mat = mesh.material;
        if (on && S.tex.soleil) { mat.map = S.tex.soleil; mat.color.setRGB(1, 1, 1); }
        else if (materiau === "modele") { mat.map = S.tex.bardeaux; const o = 1 - 0.12 * Math.sin(mesh.userData.face.plan.pente * Math.PI / 180); mat.color.setRGB(o, o, o); }
        else { mat.map = S.tex.photo; const o = 1 - 0.28 * Math.sin(mesh.userData.face.plan.pente * Math.PI / 180); mat.color.setRGB(o, o, o); }
        mat.needsUpdate = true;
      }
    }
    /** Vue rue : les arbres et les voisins placés entre la caméra (dans la rue) et la maison deviennent translucides. */
    function appliquerRue(on) {
      const S = sceneRef.current; if (!S) return; S.modeRue = on;
      const d = S.rueDir;
      for (const grp of [...S.groupes.arbres.children, ...S.groupes.voisins.children]) {
        const ob = grp.userData.objet; if (!ob) continue;
        const along = (ob.x - S.pc.x) * d.x + (ob.z - S.pc.z) * d.z; const lateral = Math.abs((ob.x - S.pc.x) * (-d.z) + (ob.z - S.pc.z) * d.x);
        const devant = on && along > 1 && along < 30 + ob.rayon && lateral < ob.rayon + 7;
        grp.traverse(m => {
          if (!m.material || m === grp) return;
          if (devant) { if (!m.userData.matOpaque) { m.userData.matOpaque = m.material; const t = m.material.clone(); t.transparent = true; t.opacity = 0.26; t.depthWrite = false; m.userData.matTrans = t; } m.material = m.userData.matTrans; m.castShadow = false; }
          else if (m.userData.matOpaque) { m.material = m.userData.matOpaque; m.castShadow = !(m.type === "LineSegments"); }
        });
      }
    }

    const S = sceneRef.current;
    const sInfo = S && S.soleilInfo;
    const heureTxt = `${Math.floor(heure)} h ${String(Math.round((heure % 1) * 60)).padStart(2, "0")}`;
    const nbP = Array.isArray(donnees.panneaux) ? donnees.panneaux.length : 0;
    const nbV = S && S.batiment && S.batiment.voisins ? S.batiment.voisins.length : 0, nbA = S && S.batiment ? S.batiment.arbres.length : 0;
    void tick;
    const vue = (fn, rue) => () => { setModeRue(!!rue); const S2 = sceneRef.current; if (S2) fn(S2); };
    return (
      <div className="re-3d">
        <div className="re-3d-barre">
          <div><b>Vue 3D</b><span className="re-muted"> maison, voisins, arbres et panneaux ; ombres réelles selon le soleil</span>{etat.pret && etat.date ? <span className="re-muted"> · imagerie {etat.qualite ? String(etat.qualite).toLowerCase() : ""} {etat.date}</span> : null}</div>
          <div className="re-inline re-3d-vues">
            <button className={"re-btn small" + (!modeRue ? " primary" : "")} disabled={!etat.pret} onClick={vue(S2 => S2.ctrl.reset())}>Perspective</button>
            <button className="re-btn small" disabled={!etat.pret} onClick={vue(S2 => S2.ctrl.dessus())}>Dessus</button>
            <button className="re-btn small" disabled={!etat.pret} onClick={vue(S2 => S2.ctrl.sud())}>Sud</button>
            <button className="re-btn small" disabled={!etat.pret} onClick={vue(S2 => S2.ctrl.nord())}>Nord</button>
            <button className={"re-btn small" + (modeRue ? " primary" : "")} disabled={!etat.pret} title="À hauteur d'homme depuis la rue (ce qui cache la maison devient translucide)" onClick={vue(S2 => S2.ctrl.rue(S2.rueDir, S2.rueH), true)}>Vue rue</button>
            <button className="re-btn small" disabled={!etat.pret} onClick={vue(S2 => S2.ctrl.reset())}>Recentrer</button>
            <span className="re-3d-seg" role="group" aria-label="Rendu du toit" style={{ display: "inline-flex", gap: 4 }}>
              <button className={"re-btn small" + (materiau === "photo" ? " primary" : "")} disabled={!etat.pret || calqueSoleil} title="Photo aérienne projetée sur le toit" onClick={() => setMateriau("photo")}>Photo</button>
              <button className={"re-btn small" + (materiau === "modele" ? " primary" : "")} disabled={!etat.pret || calqueSoleil} title="Toit en bardeaux gris uniformes" onClick={() => setMateriau("modele")}>Modèle</button>
            </span>
            <button className={"re-btn small" + (calqueSoleil ? " primary" : "")} disabled={!etat.pret || !(S && S.tex && S.tex.soleil)} onClick={() => setCalqueSoleil(v => !v)} title="Ensoleillement annuel du toit (jaune = plein soleil)">☀ Soleil</button>
          </div>
        </div>
        <div className={"re-3d-scene" + (etat.pret ? " pret" : "")} ref={hostRef}>
          {!etat.pret && !etat.err && <div className="re-3d-msg">{etat.chargement || "Chargement…"}</div>}
          {etat.err && <div className="re-3d-msg erreur">{etat.err}</div>}
          {survol && <div className="re-3d-encart" style={{ left: survol.x + 14, top: survol.y + 14 }}>
            <b>{survol.production != null ? `${fmtInt(survol.production)} kWh/an` : "Production inconnue"}</b>
            <span>{survol.acces != null ? `accès solaire ${survol.acces} %` : ""}{survol.flux != null ? ` · ${fmtInt(survol.flux)} kWh/kW` : ""}{survol.watts ? ` · ${survol.watts} W` : ""}</span>
            {survol.orientation != null && <span>pan {survol.pan != null ? survol.pan + 1 : ""} · azimut {Math.round(survol.orientation)}° · pente {Math.round(survol.pente)}°</span>}
          </div>}
          {calqueSoleil && S && S.tex && S.tex.soleil && <div className="re-3d-legende"><span>ombre</span><i /><span>plein soleil</span></div>}
        </div>
        <div className="re-3d-soleil">
          <label>Mois <select value={mois} onChange={e => setMois(Number(e.target.value))}>{MOIS.map((m, i) => <option key={m} value={i + 1}>{m}</option>)}</select></label>
          <label className="re-3d-heure">Heure <input type="range" min="6" max="20" step="0.25" value={heure} onChange={e => { setLecture(false); setHeure(Number(e.target.value)); }} /><b>{heureTxt}</b></label>
          <button className={"re-btn small" + (lecture ? " primary" : "")} disabled={!etat.pret} onClick={() => setLecture(v => !v)}>{lecture ? "⏸ Pause" : "▶ Lecture de la journée"}</button>
          {sInfo && <span className="re-muted">{sInfo.elevation > 0 ? `soleil à ${Math.round(sInfo.elevation)}° de hauteur, azimut ${Math.round(sInfo.azimut)}°` : "soleil sous l'horizon"} (heure de Mascouche)</span>}
        </div>
        <div className="re-3d-aide">Glisser : tourner · molette : zoom · bouton droit ou Maj + glisser : déplacer · {nbP} panneau{nbP > 1 ? "x" : ""} · survole un panneau pour sa production.{S && S.batiment ? ` Modèle ${S.batiment.nw ? "vectoriel" : "approximatif"} : ${S.batiment.faces.length} faces, ${nbV} voisin${nbV > 1 ? "s" : ""}, ${nbA} arbre${nbA > 1 ? "s" : ""}${S.batiment.duree_ms ? ` (${S.batiment.duree_ms} ms)` : ""}.` : ""} Lecture seule : la pose se fait dans l'éditeur 2D.</div>
      </div>
    );
  }
  Solaire3DRE.modeleDepuisToit = modeleDepuisToit;
  Solaire3DRE.adapterBatiment = adapterBatiment;
  Solaire3DRE.soleil = soleil;
  Solaire3DRE.metres = metres;
  Solaire3DRE.planDe = planDe;
  Solaire3DRE.geom = { dansPolygone, aire2, distPolygone, enveloppeConvexe, triangulerOreilles };
  window.Solaire3DRE = Solaire3DRE;
})();
