// Public fiche technique — desktop
// Hero with KPIs, sticky sidenav, theme-grouped sections with auto-hide of empty fields

const { useState: ficheUseState, useEffect: ficheUseEffect, useRef: ficheUseRef, useMemo: ficheUseMemo } = React;

function KpiCard({ label, value, suffix, big, accent }) {
  if (value == null || value === 0 || value === "") return null;
  return (
    <div className={`fc-kpi ${big ? "fc-kpi--big" : ""} ${accent ? "fc-kpi--accent" : ""}`}>
      <span className="fc-kpi-label">{label}</span>
      <span className="fc-kpi-value">
        {window.fmt.num(value)}
        {suffix && <span className="fc-kpi-suffix">{suffix}</span>}
      </span>
    </div>
  );
}

function SpecRow({ label, value, suffix, mono }) {
  if (value == null || value === "" || (typeof value === "number" && value === 0)) return null;
  return (
    <div className="fc-spec">
      <span className="fc-spec-label">{label}</span>
      <span className={`fc-spec-value ${mono ? "fc-spec-value--mono" : ""}`}>
        {value}{suffix && <span className="fc-spec-suffix">{suffix}</span>}
      </span>
    </div>
  );
}

function SpecSection({ id, title, eyebrow, children, visualEl, wideVisual }) {
  // Filter null children (auto-hide if all SpecRows are null)
  const kids = React.Children.toArray(children).filter(c => c != null && c !== false);
  if (kids.length === 0 && !visualEl) return null;
  return (
    <section id={id} className="fc-section">
      <header className="fc-section-head">
        <div>
          <p className="eyebrow fc-section-eyebrow">{eyebrow}</p>
          <h2 className="display-sm fc-section-title">{title}</h2>
        </div>
      </header>
      <div className={`fc-section-body ${visualEl ? "fc-section-body--has-visual" : ""} ${wideVisual ? "fc-section-body--wide" : ""}`}>
        {visualEl && <div className="fc-section-visual">{visualEl}</div>}
        <div className="fc-spec-list">{kids}</div>
      </div>
    </section>
  );
}

// Visual: car dimensions — proper proportioned silhouette with measurement callouts
function DimensionsVisual({ v }) {
  const L = v.length_mm, W = v.width_mm, H = v.height_mm, WB = v.wheelbase_mm, GC = v.ground_clearance_mm;
  if (!L) return null;

  // Scale to fit nicely. Side view is wide, front view is narrower.
  // Use real-world proportions: render side at L×H, front at W×H.
  // Compute relative coordinate space: side view canvas is 100 wide × (H/L*100) tall.
  const sideAspect = L / H;       // ~3.6 for sports cars
  const frontAspect = W / H;      // ~1.5 for sports cars

  // Wheelbase positioned within the side view; wheel positions
  const overhangFront = (L - WB) * 0.45; // front overhang is typically smaller
  const overhangRear  = (L - WB) * 0.55;
  const wheelFx = overhangFront / L;
  const wheelRx = (overhangFront + WB) / L;

  // SVG side silhouette path — generic sleek 2-door coupe / sedan profile
  // Drawn in a 400×100 viewBox; we scale via aspectRatio
  const isLowProfile = H < 1400;
  const silhouette = isLowProfile
    ? "M 8 78 L 18 70 L 50 60 L 100 35 L 180 22 L 240 20 L 290 28 L 340 50 L 372 62 L 392 72 L 392 80 L 8 80 Z"
    : "M 6 75 L 14 60 L 40 38 L 90 18 L 140 12 L 270 12 L 320 24 L 360 42 L 388 60 L 394 72 L 394 80 L 6 80 Z";

  return (
    <div className="fc-dim-visual">
      <div className="fc-dim-duo">
      {/* SIDE VIEW with length, height, wheelbase, ground clearance */}
      <div className="fc-dim-block fc-dim-side" style={{aspectRatio: `${sideAspect + 0.05} / 1`}}>
        {/* Length label — top */}
        <div className="fc-dim-axis fc-dim-axis--length">
          <span className="fc-dim-tick fc-dim-tick--start" />
          <span className="fc-dim-line" />
          <span className="fc-dim-readout">
            <em>Longueur</em>
            <b>{window.fmt.num(L)}<small>mm</small></b>
          </span>
          <span className="fc-dim-line" />
          <span className="fc-dim-tick fc-dim-tick--end" />
        </div>

        {/* Silhouette — mock-up IA (vue de côté) à l'échelle, cotes superposées */}
        <div className="fc-dim-canvas">
          <img className="fc-dim-img" src={v.dimSide} alt={`${v.brand} ${v.model} — profil`}
               style={{width: "100%", height: "100%", objectFit: "contain", display: "block"}} />
          {/* ground line */}
          <div className="fc-dim-ground" />

          {/* Wheelbase callout */}
          {WB && (
            <div className="fc-dim-wb-callout" style={{left: `${wheelFx*100}%`, width: `${(wheelRx-wheelFx)*100}%`}}>
              <em>Empattement</em>
              <b>{window.fmt.num(WB)}<small>mm</small></b>
            </div>
          )}
        </div>

        {/* Height label — right side */}
        <div className="fc-dim-axis fc-dim-axis--height">
          <span className="fc-dim-tick fc-dim-tick--start" />
          <span className="fc-dim-line" />
          <span className="fc-dim-readout fc-dim-readout--v">
            <em>Hauteur</em>
            <b>{window.fmt.num(H)}<small>mm</small></b>
          </span>
          <span className="fc-dim-line" />
          <span className="fc-dim-tick fc-dim-tick--end" />
        </div>
      </div>

      {/* FRONT VIEW — côte à côte avec la vue de profil */}
        <div className="fc-dim-front-block" style={{aspectRatio: `${frontAspect + 0.1} / 1`}}>
          <img className="fc-dim-img" src={v.dimFront} alt={`${v.brand} ${v.model} — face`}
               style={{width: "100%", height: "100%", objectFit: "contain", display: "block"}} />
          <div className="fc-dim-ground" />
          <div className="fc-dim-width-callout">
            <div className="fc-dim-readout fc-dim-readout--inline">
              <em>Largeur</em>
              <b>{window.fmt.num(W)}<small>mm</small></b>
            </div>
            {v.width_mirrors_mm && (
              <div className="fc-dim-readout fc-dim-readout--inline fc-dim-readout--muted">
                <em>Avec rétros</em>
                <b>{window.fmt.num(v.width_mirrors_mm)}<small>mm</small></b>
              </div>
            )}
          </div>
        </div>
      </div>{/* /fc-dim-duo */}

      <div className="fc-dim-stats">
          <div className="fc-dim-stat">
            <span className="fc-dim-stat-lbl">Voie avant</span>
            <span className="fc-dim-stat-val">{window.fmt.num(v.front_track_mm)} <small>mm</small></span>
          </div>
          <div className="fc-dim-stat">
            <span className="fc-dim-stat-lbl">Voie arrière</span>
            <span className="fc-dim-stat-val">{window.fmt.num(v.rear_track_mm)} <small>mm</small></span>
          </div>
          <div className="fc-dim-stat">
            <span className="fc-dim-stat-lbl">Garde au sol</span>
            <span className="fc-dim-stat-val">{GC || "—"} <small>mm</small></span>
          </div>
          <div className="fc-dim-stat">
            <span className="fc-dim-stat-lbl">Cx</span>
            <span className="fc-dim-stat-val">{v.drag_coefficient_cd?.toString().replace(".",",") || "—"}</span>
          </div>
        </div>
    </div>
  );
}

function PowerCurve({ v }) {
  // Decorative power/torque curve graphic
  const maxPower = v.power_hp;
  if (!maxPower) return null;
  return (
    <div className="fc-curve">
      <svg viewBox="0 0 320 160" width="100%">
        <defs>
          <linearGradient id="curveGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--color-yellow)" stopOpacity="0.8"/>
            <stop offset="100%" stopColor="var(--color-yellow)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {/* grid */}
        {[0,1,2,3,4].map(i => <line key={i} x1="30" y1={20+i*30} x2="310" y2={20+i*30} stroke="var(--color-medium-grey)" strokeWidth="0.5"/>)}
        {/* torque (flat-ish) */}
        <path d="M 30 80 Q 80 50, 130 45 T 240 50 L 280 70 L 310 110" fill="none" stroke="var(--color-dark-green)" strokeWidth="2"/>
        {/* power (rising) */}
        <path d="M 30 130 Q 100 110, 160 80 T 280 35 L 310 30" fill="url(#curveGrad)" stroke="var(--color-yellow)" strokeWidth="2"/>
        <path d="M 30 130 Q 100 110, 160 80 T 280 35 L 310 30 L 310 140 L 30 140 Z" fill="url(#curveGrad)" opacity="0.5"/>
        {/* labels */}
        <text x="280" y="22" fontSize="9" fontFamily="Roboto" fill="var(--color-dark-green)" fontWeight="700">{v.power_hp} ch</text>
        <text x="240" y="62" fontSize="9" fontFamily="Roboto" fill="var(--color-dark-green)" opacity="0.6">{v.torque_nm} Nm</text>
        {/* x axis */}
        <text x="30" y="155" fontSize="8" fontFamily="Roboto" fill="var(--color-dark-green-30)">1000</text>
        <text x="160" y="155" fontSize="8" fontFamily="Roboto" fill="var(--color-dark-green-30)">4500</text>
        <text x="290" y="155" fontSize="8" fontFamily="Roboto" fill="var(--color-dark-green-30)">8000 tr/min</text>
      </svg>
      <div className="fc-curve-legend">
        <span><i style={{background:"var(--color-yellow)"}}/>Puissance ({v.power_hp} ch @ {window.fmt.num(v.power_rpm)} tr/min)</span>
        <span><i style={{background:"var(--color-dark-green)"}}/>Couple ({v.torque_nm} Nm @ {window.fmt.num(v.torque_rpm_low)}-{window.fmt.num(v.torque_rpm_high)})</span>
      </div>
    </div>
  );
}

function AccelChart({ v }) {
  const points = [
    { label: "0-100", val: v.acceleration_0_100_s },
    { label: "0-200", val: v.acceleration_0_200_s },
    { label: "80-120", val: v.acceleration_80_120_s },
    { label: "100-200", val: v.acceleration_100_200_s },
    { label: "1000m DA", val: v.da_1000m_s },
  ].filter(p => p.val != null && p.val > 0);
  if (!points.length) return null;
  const max = Math.max(...points.map(p => p.val));
  return (
    <div className="fc-accel">
      <div className="fc-accel-rows">
        {points.map(p => (
          <div key={p.label} className="fc-accel-row">
            <span className="fc-accel-label">{p.label} km/h</span>
            <div className="fc-accel-bar"><div style={{width: `${(p.val/max)*100}%`}}/></div>
            <span className="fc-accel-val">{p.val.toFixed(2).replace(".",",")}<small>s</small></span>
          </div>
        ))}
      </div>
    </div>
  );
}

function BatteryViz({ v }) {
  if (!v.battery_kwh_total) return null;
  const usable = v.battery_kwh_usable / v.battery_kwh_total;
  return (
    <div className="fc-battery">
      <div className="fc-batt-icon">
        <svg viewBox="0 0 100 50" width="100%">
          <rect x="2" y="6" width="92" height="38" rx="3" fill="none" stroke="var(--color-dark-green)" strokeWidth="2"/>
          <rect x="94" y="18" width="6" height="14" rx="1" fill="var(--color-dark-green)"/>
          <rect x="6" y="10" width={`${usable*84}`} height="30" rx="1.5" fill="var(--color-yellow)"/>
          <text x="50" y="30" fontSize="14" fontFamily="Bebas Neue" fill="var(--color-dark-green)" textAnchor="middle" fontWeight="700">{v.battery_kwh_total} kWh</text>
        </svg>
      </div>
      <div className="fc-batt-stats">
        <div><b>{v.battery_kwh_usable}</b><span>kWh utiles</span></div>
        <div><b>{v.range_wltp_km}</b><span>km WLTP</span></div>
        <div><b>{v.dc_charging_kw}</b><span>kW max DC</span></div>
        <div><b>{v.charge_time_dc_10_80_min}</b><span>min 10→80%</span></div>
      </div>
    </div>
  );
}

function FicheDesktop({ vehicle, fromMarketplace, notInMarketplace, density, heroVariant, statsStyle }) {
  const v = vehicle;
  // Powertrain: thermal | hybrid | electric. Hybrid = battery AND combustion engine.
  const powertrain = v.powertrain || (v.battery_kwh_total ? (v.cylinders ? "hybrid" : "electric") : "thermal");
  const isEV = powertrain === "electric";
  const isHybrid = powertrain === "hybrid";
  const hasBattery = isEV || isHybrid;
  // Real gallery photos (marketplace listing) when available, else the mock-up.
  const photos = (v.photos && v.photos.length) ? v.photos
    : (fromMarketplace ? window.MARKETPLACE_PHOTOS["mkt-r8-987"] : [v.photoMain]);

  const [activeAnchor, setActiveAnchor] = ficheUseState("hero");
  const [activePhoto, setActivePhoto] = ficheUseState(0);
  const [lightbox, setLightbox] = ficheUseState(false);

  const sections = ficheUseMemo(() => {
    return [
      { id: "perf", label: "Performance" },
      { id: "engine", label: isEV ? "Motorisation électrique" : "Moteur" },
      ...(hasBattery ? [{ id: "battery", label: isHybrid ? "Batterie & mode électrique" : "Batterie & recharge" }] : []),
      ...(!isEV ? [{ id: "fuel", label: "Consommation" }] : []),
      { id: "dim", label: "Dimensions & poids" },
      { id: "chassis", label: "Châssis & freinage" },
      { id: "transmission", label: "Transmission" },
      { id: "warranty", label: "Garantie & production" },
      { id: "similar", label: "Modèles similaires" },
    ];
  }, [isEV, isHybrid, hasBattery]);

  // Scroll-spy : surligne la section courante + révèle la barre sticky après le hero.
  const [showSticky, setShowSticky] = ficheUseState(false);
  ficheUseEffect(() => {
    const ids = sections.map(s => s.id);
    const onScroll = () => {
      const hero = document.getElementById("hero");
      setShowSticky(hero ? hero.getBoundingClientRect().bottom < 8 : false);
      let cur = "hero";
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= 130) cur = id;
      }
      setActiveAnchor(cur);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [sections]);

  return (
    <div className={`fc-root fc-density-${density || "default"} fc-hero-${heroVariant || "full"} fc-stats-${statsStyle || "xxl"}`}>
      {/* TOP NAV — marketplace nav */}
      <nav className="fc-nav">
        <div className="fc-nav-lockup">
          <svg viewBox="0 0 37.468 35.933" fill="currentColor" width="26" height="26"><path d="M 37.468 30.774 L 37.021 30.011 C 36.708 29.428 36.216 28.441 35.501 27.993 L 30.404 25.121 L 28.213 25.75 L 25.575 16.553 C 25.038 15.252 24.1 14.131 22.848 13.413 L 0 0 L 1.833 5.069 C 2.057 5.832 2.549 6.415 3.13 6.908 L 16.99 16.553 L 4.471 11.26 C 4.471 11.305 5.5 14.938 5.5 14.938 C 5.589 15.297 5.768 15.656 5.991 15.925 C 6.081 16.06 6.215 16.194 6.349 16.329 L 17.438 24.045 L 8.45 20.277 L 9.658 24.718 C 9.881 25.57 10.597 26.288 11.044 26.736 L 20.12 35.933 C 21.104 34.273 23.429 32.703 27.006 31.267 C 28.571 30.639 30.046 30.236 31.477 30.011 C 33.847 29.652 35.903 29.832 37.468 30.011 Z"/></svg>
          <span>JOINSTEER</span>
        </div>
        <div className="fc-nav-links">
          <a>Marketplace</a>
          <a>Fiches techniques</a>
          <a>Financement</a>
          <a>À propos</a>
        </div>
        <div className="fc-nav-right">
          <button className="fc-nav-search">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="6" cy="6" r="4" stroke="currentColor" strokeWidth="1.5"/><path d="M11 11l-2-2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            Rechercher un véhicule…
          </button>
          <button className="fc-nav-avatar">JD</button>
        </div>
      </nav>

      {/* STICKY BAR — apparaît après le hero : identité véhicule + nav sections + CTA */}
      <div className={`fc-stickybar ${showSticky ? "is-visible" : ""}`}>
        <div className="fc-sb-id">
          {photos[0] && <img className="fc-sb-photo" src={photos[0]} alt="" />}
          <div className="fc-sb-name">
            <span className="fc-sb-brand">{v.brand}</span>
            <span className="fc-sb-model">{v.model}{v.modele_sp ? ` ${v.modele_sp}` : ""}</span>
            <span className="fc-sb-version">{[v.version, v.year].filter(Boolean).join(" · ")}</span>
          </div>
        </div>
        <div className="fc-sb-right">
          <div className="fc-sb-kpis">
            <span><b>{v.power_hp}</b> ch</span>
            {v.acceleration_0_100_s && <span><b>{String(v.acceleration_0_100_s).replace(".", ",")}</b> s</span>}
          </div>
          <button className="fc-cta-primary fc-sb-cta"><span>{notInMarketplace ? "Recevoir une alerte" : "Faisons connaissance"}</span></button>
        </div>
      </div>

      {/* CRUMBS */}
      <div className="fc-crumbs">
        <a>Fiches techniques</a> <span>›</span>
        <a>{v.brand}</a> <span>›</span>
        <a>{v.model}</a> <span>›</span>
        <span className="fc-crumbs-current">{v.year} · {v.trim}</span>
      </div>

      {/* HERO */}
      <header id="hero" className="fc-hero">
        <div className="fc-hero-left">
          <div className="fc-hero-tags">
            <span className="fc-tag fc-tag--year">{v.year}</span>
            <span className="fc-tag">{v.segment}</span>
            {fromMarketplace && <span className="fc-tag fc-tag--marketplace">● Annonce active</span>}
            {notInMarketplace && <span className="fc-tag fc-tag--offmarket">Hors marketplace</span>}
          </div>

          {/* Hierarchy crumbs — Marque › Modèle › Version › Modèle SP */}
          <div className="fc-hierarchy">
            <div className="fc-hier-crumb">
              <span className="fc-hier-label">Marque</span>
              <span className="fc-hier-val">{v.brand}</span>
            </div>
            <span className="fc-hier-sep">›</span>
            <div className="fc-hier-crumb fc-hier-crumb--model">
              <span className="fc-hier-label">Modèle</span>
              <span className="fc-hier-val">{v.model}</span>
            </div>
            <span className="fc-hier-sep">›</span>
            <div className="fc-hier-crumb">
              <span className="fc-hier-label">Version</span>
              <span className="fc-hier-val">{v.version || "—"}</span>
            </div>
            <span className="fc-hier-sep">›</span>
            <div className="fc-hier-crumb fc-hier-crumb--sp">
              <span className="fc-hier-label">Modèle SP</span>
              <span className="fc-hier-val">{v.modele_sp || "—"}</span>
            </div>
          </div>

          {/* Display title */}
          <h1 className="fc-hero-title">{v.model}</h1>
          <p className="fc-hero-subtitle">
            <span>{v.version}</span>
            <span className="fc-hero-sub-sep">·</span>
            <span className="fc-hero-sp">{v.modele_sp}</span>
            <span className="fc-hero-sub-sep">·</span>
            <span className="fc-hero-year">{v.year}</span>
          </p>

          <p className="fc-hero-lede">
            {(() => {
              const bits = [`${window.fmt.num(v.power_hp)} ch`];
              if (!isEV && v.cylinders) {
                bits.push(`${v.cylinders} cylindres${v.engine_layout && v.engine_layout.toLowerCase().includes("central") ? " en position centrale" : ""}`);
              }
              if (isEV && v.range_wltp_km) bits.push(`${v.range_wltp_km} km WLTP`);
              else if (isHybrid && v.range_wltp_km) bits.push(`${v.range_wltp_km} km en mode électrique`);
              if (v.acceleration_0_100_s) bits.push(`0-100 km/h en ${String(v.acceleration_0_100_s).replace(".", ",")} s`);
              const body = (v.body && v.body.toLowerCase()) || "voiture";
              const kind = isEV ? `Une ${body} 100% électrique` : `Une ${body}${isHybrid ? " hybride" : ""} d'exception`;
              return `${bits.join(" · ")}. ${kind} signée ${v.brand}${v.production_plant ? `, fabriquée à ${v.production_plant}` : ""}.`;
            })()}
          </p>

          {/* Signature KPIs */}
          <div className="fc-hero-kpis">
            <div className="fc-hero-kpi">
              <span className="fc-hero-kpi-val">{v.power_hp}</span>
              <span className="fc-hero-kpi-unit">ch</span>
              <span className="fc-hero-kpi-label">Puissance</span>
            </div>
            <div className="fc-hero-kpi fc-hero-kpi--accent">
              <span className="fc-hero-kpi-val">{v.acceleration_0_100_s?.toString().replace(".",",")}</span>
              <span className="fc-hero-kpi-unit">s</span>
              <span className="fc-hero-kpi-label">0-100 km/h</span>
            </div>
            <div className="fc-hero-kpi">
              <span className="fc-hero-kpi-val">{v.top_speed_kmh}</span>
              <span className="fc-hero-kpi-unit">km/h</span>
              <span className="fc-hero-kpi-label">V. max</span>
            </div>
            <div className="fc-hero-kpi">
              <span className="fc-hero-kpi-val">{isEV ? v.range_wltp_km : v.torque_nm}</span>
              <span className="fc-hero-kpi-unit">{isEV ? "km" : "Nm"}</span>
              <span className="fc-hero-kpi-label">{isEV ? "Autonomie" : "Couple"}</span>
            </div>
          </div>

          {/* From marketplace banner */}
          {fromMarketplace && (
            <div className="fc-from-banner">
              <div className="fc-from-icon">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="3" fill="currentColor"/><circle cx="10" cy="10" r="7" stroke="currentColor" strokeWidth="1.5"/></svg>
              </div>
              <div className="fc-from-text">
                <b>Vous consultez la fiche de l'annonce #mkt-r8-987</b>
                <p>Photos et options issues de l'exemplaire actuellement en vente. <a>Voir l'annonce</a></p>
              </div>
            </div>
          )}

          {/* Off-market notice banner */}
          {notInMarketplace && (
            <div className="fc-from-banner fc-from-banner--off">
              <div className="fc-from-icon fc-from-icon--off">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 2v8l5 3" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/><circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="1.5"/></svg>
              </div>
              <div className="fc-from-text">
                <b>Pas encore d'exemplaire disponible sur Joinsteer</b>
                <p>Fiche technique consultable, mais aucune annonce active actuellement. Activez une alerte pour être prévenu·e dès qu'un exemplaire est disponible.</p>
              </div>
            </div>
          )}

          <div className="fc-hero-ctas">
            {notInMarketplace ? (
              <>
                <button className="fc-cta-primary">
                  <span>Recevoir une alerte</span>
                </button>
                <button className="fc-cta-secondary">Faire une demande sur mesure</button>
              </>
            ) : (
              <>
                <button className="fc-cta-primary">
                  <span>Faisons connaissance</span>
                </button>
                <button className="fc-cta-secondary">Voir 12 annonces actives</button>
              </>
            )}
          </div>

          {/* Quality strip */}
          <div className="fc-quality-strip">
            <div>
              <span className="fc-q-label">Complétude</span>
              <span className="fc-q-val">{Math.round(v.completeness*100)}%</span>
            </div>
            <div>
              <span className="fc-q-label">Sources croisées</span>
              <span className="fc-q-val">{v.sources.length}</span>
            </div>
            <div>
              <span className="fc-q-label">Fiabilité</span>
              <span className="fc-q-val">{Math.round(v.reliability*100)}%</span>
            </div>
            <div>
              <span className="fc-q-label">Dernière vérif.</span>
              <span className="fc-q-val">21/05/2026</span>
            </div>
          </div>
        </div>

        <div className="fc-hero-right">
          <div className="fc-gallery">
            <div className="fc-gallery-main" onClick={()=>setLightbox(true)}>
              <img src={photos[activePhoto]} alt="" />
              <span className="fc-gallery-counter">{activePhoto+1} / {photos.length}</span>
              <button className="fc-gallery-zoom" aria-label="Zoom">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 6V2h4M14 6V2h-4M2 10v4h4M14 10v4h-4" stroke="currentColor" strokeWidth="1.5"/></svg>
              </button>
            </div>
            <div className="fc-gallery-thumbs">
              {photos.map((p, i) => (
                <button key={i} className={`fc-thumb ${i === activePhoto ? "is-on" : ""}`} onClick={()=>setActivePhoto(i)}>
                  <img src={p} alt="" />
                </button>
              ))}
            </div>
          </div>
        </div>
      </header>

      {/* MARKETPLACE BAND — vrais exemplaires disponibles sur Joinsteer */}
      {v.marketplaceListings && v.marketplaceListings.length > 0 && (
        <section className="fc-mkt-band">
          <div className="fc-mkt-head">
            <div>
              <p className="eyebrow" style={{color: "var(--color-dark-green-30)", marginBottom: 6}}>Disponible maintenant</p>
              <h2 className="h3">{window.fmt.num(v.marketplaceCount || v.marketplaceListings.length)} {v.brand} {v.model} sur le marketplace Joinsteer</h2>
            </div>
            <a className="fc-link" href={v.marketplaceUrl || "#"} target="_blank" rel="noopener">Voir les annonces →</a>
          </div>
          <div className="fc-mkt-cards">
            {v.marketplaceListings.map((l, i) => (
              <a key={i} className="fc-mkt-card" href={l.url || "#"} target="_blank" rel="noopener">
                <div className="fc-mkt-photo">
                  {l.photo && <img src={l.photo} alt="" loading="lazy" />}
                  {l.color && <span className="fc-mkt-color">{l.color}</span>}
                </div>
                <div className="fc-mkt-meta">
                  <div className="fc-mkt-row1">
                    <span className="fc-mkt-year">{l.year}</span>
                    {l.mileage != null && <span className="fc-mkt-km">{window.fmt.num(l.mileage)} km</span>}
                  </div>
                  <div className="fc-mkt-price">
                    <b>{window.fmt.num(l.price)} €</b>
                    {l.monthly ? <span>ou {window.fmt.num(l.monthly)} €/mois</span> : null}
                  </div>
                </div>
              </a>
            ))}
          </div>
        </section>
      )}

      {/* MAIN GRID — sticky nav + content */}
      <div className="fc-main-grid">
        <aside className="fc-sidenav">
          <p className="eyebrow" style={{marginBottom:16, color:"var(--color-dark-green-30)"}}>Navigation</p>
          <ul>
            {sections.map(s => (
              <li key={s.id}>
                <a href={`#${s.id}`} className={activeAnchor === s.id ? "is-active" : ""}>{s.label}</a>
              </li>
            ))}
          </ul>
          <div className="fc-sidenav-share">
            <button title="Partager"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="4" cy="8" r="2" stroke="currentColor" strokeWidth="1.4"/><circle cx="12" cy="3" r="2" stroke="currentColor" strokeWidth="1.4"/><circle cx="12" cy="13" r="2" stroke="currentColor" strokeWidth="1.4"/><path d="M6 7l4-3M6 9l4 3" stroke="currentColor" strokeWidth="1.4"/></svg> Partager</button>
            <button title="PDF"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 2h6l3 3v9H4V2z" stroke="currentColor" strokeWidth="1.4"/><path d="M10 2v3h3" stroke="currentColor" strokeWidth="1.4"/></svg> PDF</button>
            <button title="Comparer"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 4h10M3 8h10M3 12h6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg> Comparer</button>
          </div>
        </aside>

        <main className="fc-content">

          {/* PERFORMANCE */}
          <SpecSection id="perf" eyebrow="01 · Comportement" title="PERFORMANCE" visualEl={<AccelChart v={v}/>}>
            <SpecRow label="0 à 100 km/h" value={v.acceleration_0_100_s?.toString().replace(".",",")} suffix=" s" />
            <SpecRow label="0 à 200 km/h" value={v.acceleration_0_200_s?.toString().replace(".",",")} suffix=" s" />
            <SpecRow label="80 à 120 km/h" value={v.acceleration_80_120_s?.toString().replace(".",",")} suffix=" s" />
            <SpecRow label="100 à 200 km/h" value={v.acceleration_100_200_s?.toString().replace(".",",")} suffix=" s" />
            <SpecRow label="DA 1000 m" value={v.da_1000m_s?.toString().replace(".",",")} suffix=" s" />
            <SpecRow label="Vitesse maximale" value={window.fmt.num(v.top_speed_kmh)} suffix=" km/h" />
            <SpecRow label="Freinage 100-0" value={v.braking_100_0_m?.toString().replace(".",",")} suffix=" m" />
            <SpecRow label="Accélération latérale" value={v.lateral_g?.toString().replace(".",",")} suffix=" g" />
          </SpecSection>

          {/* ENGINE / MOTOR */}
          <SpecSection id="engine" eyebrow="02 · Cœur mécanique" title={isEV ? "MOTORISATION ÉLECTRIQUE" : "MOTEUR"} visualEl={!isEV ? <PowerCurve v={v}/> : null}>
            {!isEV && <SpecRow label="Code moteur" value={v.engine_code} mono />}
            <SpecRow label="Architecture" value={v.engine_layout} />
            {!isEV && <SpecRow label="Cylindres" value={v.cylinders} />}
            {!isEV && <SpecRow label="Cylindrée" value={window.fmt.num(v.displacement_cc)} suffix=" cm³" />}
            {!isEV && <SpecRow label="Soupapes / cylindre" value={v.valves_per_cylinder} />}
            {!isEV && <SpecRow label="Alésage × course" value={v.bore_mm && v.stroke_mm ? `${v.bore_mm} × ${v.stroke_mm}` : null} suffix=" mm" />}
            {!isEV && <SpecRow label="Rapport volumétrique" value={v.compression_ratio?.toString().replace(".",",")} />}
            {!isEV && <SpecRow label="Alimentation" value={v.fuel_system} />}
            {!isEV && <SpecRow label="Suralimentation" value={v.aspiration} />}
            {!isEV && v.intercooler != null && <SpecRow label="Intercooler" value={v.intercooler ? "Oui" : "Non"} />}
            {!isEV && <SpecRow label="Distribution" value={v.valvetrain} />}
            <SpecRow label="Puissance" value={v.power_hp && v.power_kw ? `${v.power_hp} ch (${v.power_kw} kW)` : null} />
            {!isEV && <SpecRow label="Régime de puissance max" value={window.fmt.num(v.power_rpm)} suffix=" tr/min" />}
            <SpecRow label="Couple maxi" value={v.torque_nm} suffix=" Nm" />
            {!isEV && v.torque_rpm_low && <SpecRow label="Plage de couple" value={`${window.fmt.num(v.torque_rpm_low)} – ${window.fmt.num(v.torque_rpm_high)}`} suffix=" tr/min" />}
            {hasBattery && <SpecRow label="Nombre de moteurs élec." value={v.motor_count} />}
            {hasBattery && <SpecRow label="Implantation moteur élec." value={v.motor_layout} />}
            {isHybrid && <SpecRow label="Puissance thermique seule" value={v.power_hp_ice ? `${v.power_hp_ice} ch` : null} />}
          </SpecSection>

          {/* BATTERY (EV + hybride) */}
          {hasBattery && (
            <SpecSection id="battery" eyebrow="03 · Énergie" title={isHybrid ? "BATTERIE & MODE ÉLECTRIQUE" : "BATTERIE & RECHARGE"} visualEl={<BatteryViz v={v}/>}>
              <SpecRow label="Capacité totale" value={v.battery_kwh_total?.toString().replace(".",",")} suffix=" kWh" />
              <SpecRow label="Capacité utile" value={v.battery_kwh_usable?.toString().replace(".",",")} suffix=" kWh" />
              <SpecRow label="Chimie" value={v.battery_chemistry} />
              <SpecRow label="Autonomie WLTP" value={window.fmt.num(v.range_wltp_km)} suffix=" km" />
              <SpecRow label="Autonomie ville" value={window.fmt.num(v.range_city_km)} suffix=" km" />
              <SpecRow label="Autonomie test réel" value={window.fmt.num(v.range_real_test_km)} suffix=" km" />
              <SpecRow label="Consommation" value={v.consumption_kwh_100km?.toString().replace(".",",")} suffix=" kWh/100km" />
              <SpecRow label="Recharge AC max" value={v.ac_charging_kw} suffix=" kW" />
              <SpecRow label="Recharge DC max" value={v.dc_charging_kw} suffix=" kW" />
              <SpecRow label="10 → 80% en DC" value={v.charge_time_dc_10_80_min} suffix=" min" />
              <SpecRow label="Coût recharge domicile" value={v.charge_cost_full_home_eur?.toString().replace(".",",")} suffix=" €" />
              <SpecRow label="Coût recharge DC" value={v.charge_cost_full_dc_eur?.toString().replace(".",",")} suffix=" €" />
            </SpecSection>
          )}

          {/* FUEL & EMISSIONS (thermal) */}
          {!isEV && (
            <SpecSection id="fuel" eyebrow="03 · Consommation" title="CONSOMMATION & ÉMISSIONS">
              <SpecRow label="Mixte" value={v.consumption_combined_l_100km?.toString().replace(".",",")} suffix=" L/100km" />
              <SpecRow label="Urbaine" value={v.consumption_city_l_100km?.toString().replace(".",",")} suffix=" L/100km" />
              <SpecRow label="Extra-urbaine" value={v.consumption_extra_l_100km?.toString().replace(".",",")} suffix=" L/100km" />
              <SpecRow label="CO₂ WLTP" value={v.co2_wltp_g_km} suffix=" g/km" />
              <SpecRow label="CO₂ NEDC" value={v.co2_nedc_g_km} suffix=" g/km" />
              <SpecRow label="Capacité réservoir" value={v.fuel_tank_l?.toString().replace(".",",")} suffix=" L" />
              <SpecRow label="Norme" value={v.emission_norm} />
              <SpecRow label="Coût aux 100 km" value={v.cost_per_100km_eur?.toString().replace(".",",")} suffix=" €" />
            </SpecSection>
          )}

          {/* DIMENSIONS */}
          <SpecSection id="dim" eyebrow="04 · Géométrie" title="DIMENSIONS & POIDS" visualEl={<DimensionsVisual v={v}/>} wideVisual>
            <SpecRow label="Longueur" value={window.fmt.num(v.length_mm)} suffix=" mm" />
            <SpecRow label="Largeur" value={window.fmt.num(v.width_mm)} suffix=" mm" />
            <SpecRow label="Largeur avec rétros" value={window.fmt.num(v.width_mirrors_mm)} suffix=" mm" />
            <SpecRow label="Hauteur" value={window.fmt.num(v.height_mm)} suffix=" mm" />
            <SpecRow label="Empattement" value={window.fmt.num(v.wheelbase_mm)} suffix=" mm" />
            <SpecRow label="Voie avant" value={window.fmt.num(v.front_track_mm)} suffix=" mm" />
            <SpecRow label="Voie arrière" value={window.fmt.num(v.rear_track_mm)} suffix=" mm" />
            <SpecRow label="Garde au sol" value={v.ground_clearance_mm} suffix=" mm" />
            <SpecRow label="Cx (coef. aéro)" value={v.drag_coefficient_cd?.toString().replace(".",",")} />
            <SpecRow label="Surface frontale" value={v.frontal_area_m2?.toString().replace(".",",")} suffix=" m²" />
            <SpecRow label="Poids à vide" value={window.fmt.num(v.curb_weight_kg)} suffix=" kg" />
            <SpecRow label="PTAC" value={window.fmt.num(v.gvwr_kg)} suffix=" kg" />
            <SpecRow label="Charge utile" value={window.fmt.num(v.payload_kg)} suffix=" kg" />
            <SpecRow label="Remorquage freiné" value={window.fmt.num(v.towing_braked_kg)} suffix=" kg" />
            <SpecRow label="Remorquage non freiné" value={window.fmt.num(v.towing_unbraked_kg)} suffix=" kg" />
            <SpecRow label="Répartition AV" value={v.weight_distribution_front_pct?.toString().replace(".",",")} suffix=" %" />
            <SpecRow label="Coffre" value={window.fmt.num(v.trunk_l)} suffix=" L" />
            <SpecRow label="Coffre sièges rabattus" value={window.fmt.num(v.trunk_seats_down_l)} suffix=" L" />
            <SpecRow label="Places" value={v.seats} />
            <SpecRow label="Portes" value={v.doors} />
          </SpecSection>

          {/* CHASSIS & BRAKES */}
          <SpecSection id="chassis" eyebrow="05 · Tenue de route" title="CHÂSSIS, FREINS, PNEUS">
            <SpecRow label="Suspension avant" value={v.front_suspension} />
            <SpecRow label="Suspension arrière" value={v.rear_suspension} />
            <SpecRow label="Type de direction" value={v.steering_type} />
            <SpecRow label="Diamètre de braquage" value={v.turning_circle_m?.toString().replace(".",",")} suffix=" m" />
            <SpecRow label="Matériau du châssis" value={v.chassis_material} />
            <SpecRow label="Freins AV" value={v.brake_front_mm ? `${v.brake_front_mm} mm — ${v.brake_front_type}` : null} />
            <SpecRow label="Freins AR" value={v.brake_rear_mm ? `${v.brake_rear_mm} mm — ${v.brake_rear_type}` : null} />
            <SpecRow label="Pneus AV" value={v.tire_front} mono />
            <SpecRow label="Pneus AR" value={v.tire_rear} mono />
            <SpecRow label="Jantes AV" value={v.wheel_front_inch ? `${v.wheel_front_inch}″` : null} />
            <SpecRow label="Jantes AR" value={v.wheel_rear_inch ? `${v.wheel_rear_inch}″` : null} />
          </SpecSection>

          {/* TRANSMISSION */}
          <SpecSection id="transmission" eyebrow="06 · Pilotage" title="TRANSMISSION">
            <SpecRow label="Type" value={v.transmission_type} />
            <SpecRow label="Rapports" value={v.transmission_speeds} />
            <SpecRow label="Embrayages" value={v.clutch_count} />
          </SpecSection>

          {/* WARRANTY & PRODUCTION */}
          <SpecSection id="warranty" eyebrow="07 · Fabrication" title="GARANTIE & PRODUCTION">
            <SpecRow label="Garantie constructeur" value={v.warranty_years ? `${v.warranty_years} ans${v.warranty_km ? ` / ${window.fmt.num(v.warranty_km)} km` : ""}` : null} />
            <SpecRow label="Peinture" value={v.paint_warranty_years} suffix=" ans" />
            <SpecRow label="Anti-corrosion" value={v.perforation_warranty_years} suffix=" ans" />
            <SpecRow label="Prix de lancement" value={window.fmt.price(v.launch_price_eur)} />
            <SpecRow label="Production totale" value={window.fmt.num(v.production_total)} suffix=" exemplaires" />
            <SpecRow label="Site de production" value={v.production_plant} />
          </SpecSection>

          {/* CTA banner before similar models */}
          {notInMarketplace ? (
            <div className="fc-cta-banner fc-cta-banner--alert">
              <div>
                <p className="eyebrow" style={{color:"var(--color-yellow)", marginBottom:8}}>Alerte personnalisée</p>
                <h3 className="display-sm" style={{color:"#fff"}}>SOYEZ LE/LA PREMIER·E PRÉVENU·E.</h3>
                <p style={{color:"rgba(255,255,255,0.8)", marginTop:12, maxWidth:520}}>
                  Activez une alerte sur la {v.brand} {v.model} et nous vous contactons dès qu'un exemplaire entre dans notre flotte.
                  En moyenne, nous trouvons l'exemplaire dans <b style={{color:"var(--color-yellow)"}}>18 jours</b>.
                </p>
              </div>
              <div className="fc-alert-form">
                <div className="fc-alert-input">
                  <svg width="18" height="18" viewBox="0 0 20 20" fill="none"><path d="M3 5l7 5 7-5M3 5h14v10H3V5z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
                  <span>votre@email.com</span>
                </div>
                <button className="fc-cta-primary fc-cta-primary--big">Activer l'alerte</button>
              </div>
            </div>
          ) : (
            <div className="fc-cta-banner">
              <div>
                <p className="eyebrow" style={{color:"var(--color-yellow)", marginBottom:8}}>Disponible en LOA</p>
                <h3 className="display-sm" style={{color:"#fff"}}>UNE {v.model.toUpperCase()}<br/>POUR VOUS, DÈS DEMAIN.</h3>
                <p style={{color:"rgba(255,255,255,0.8)", marginTop:12, maxWidth:480}}>
                  12 exemplaires actuellement disponibles à la location longue durée. Financement en 48h.
                </p>
              </div>
              <button className="fc-cta-primary fc-cta-primary--big">Faisons connaissance</button>
            </div>
          )}

          {/* SIMILAR MODELS */}
          <section id="similar" className="fc-section fc-similar">
            <header className="fc-section-head">
              <div>
                <p className="eyebrow fc-section-eyebrow">08 · À découvrir aussi</p>
                <h2 className="display-sm fc-section-title">MODÈLES SIMILAIRES</h2>
              </div>
              <button className="fc-link">Voir le comparateur →</button>
            </header>
            <div className="fc-similar-grid">
              {[
                { brand: "Lamborghini", model: "Huracán EVO", year: 2022, hp: 640, accel: 3.1, price: 230000, photo: "assets/porsche-side.png", match: "Performance similaire" },
                { brand: "McLaren", model: "Artura", year: 2023, hp: 680, accel: 3.0, price: 245000, photo: "assets/porsche-front.png", match: "Même segment" },
                { brand: "Ferrari", model: "Roma", year: 2023, hp: 620, accel: 3.4, price: 220000, photo: "assets/porsche-rear.png", match: "Tranche de prix" },
              ].map((s,i)=>(
                <a key={i} className="fc-sim-card">
                  <div className="fc-sim-photo">
                    <img src={s.photo} alt="" />
                    <span className="fc-sim-match">{s.match}</span>
                  </div>
                  <div className="fc-sim-meta">
                    <span className="fc-sim-brand">{s.brand}</span>
                    <div className="fc-sim-row1">
                      <span className="fc-sim-model">{s.model}</span>
                      <span className="fc-sim-year">{s.year}</span>
                    </div>
                    <div className="fc-sim-stats">
                      <span><b>{s.hp}</b>ch</span>
                      <span><b>{s.accel.toString().replace(".",",")}</b>s</span>
                      <span><b>{(s.price/1000)}k€</b></span>
                    </div>
                  </div>
                </a>
              ))}
            </div>
          </section>

          {/* Footer sources */}
          <footer className="fc-sources-footer">
            <div>
              <p className="eyebrow" style={{marginBottom:8}}>Sources de cette fiche</p>
              <div className="fc-source-list">
                {v.sources.map((s,i)=>(<span key={i} className="fc-source-pill">{s}</span>))}
              </div>
            </div>
            <p className="fc-disclaimer">
              Données vérifiées le 21 mai 2026. Indice de fiabilité : {Math.round(v.reliability*100)}%.
              Les caractéristiques peuvent varier selon les options et la version commercialisée.
            </p>
          </footer>
        </main>
      </div>

      {/* LIGHTBOX */}
      {lightbox && (
        <div className="fc-lightbox" onClick={()=>setLightbox(false)}>
          <button className="fc-lightbox-close" onClick={()=>setLightbox(false)}>✕</button>
          <img src={photos[activePhoto]} alt="" onClick={(e)=>e.stopPropagation()} />
          <div className="fc-lightbox-strip" onClick={(e)=>e.stopPropagation()}>
            {photos.map((p,i)=>(
              <button key={i} className={`fc-lb-thumb ${i===activePhoto?"is-on":""}`} onClick={()=>setActivePhoto(i)}>
                <img src={p} alt="" />
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.FicheDesktop = FicheDesktop;
