// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";
import { useState } from "react";
import Link from "next/link";
import { useLang } from "./LangContext";
import LeadForm from "./LeadForm";
import RadarMap from "./RadarMap";
import {
  BuildingGlyph,
  ConfidenceDial,
  CountUp,
  EraLine,
  locNum,
  LotDiagram,
  ValueSplit,
} from "./MetricViz";
import Proforma from "./Proforma";
import type { EstimateResult } from "@/lib/engine";
import type { UnitEstimate } from "@/lib/estimator";
import type { TKey } from "@/lib/i18n";

const fmt = (v: number | null | undefined, lang: string) =>
  v == null
    ? "—"
    : new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", {
        style: "currency",
        currency: "CAD",
        maximumFractionDigits: 0,
      }).format(v);

const signed = (v: number, lang: string) =>
  `${v >= 0 ? "+" : "−"}${fmt(Math.abs(Math.round(v)), lang)}`;

const pct = (v: number) => `${v >= 0 ? "+" : ""}${v.toFixed(0)} %`;

function doorsLabel(n: number | null | undefined, fr: boolean): string {
  if (!n) return "Plex";
  const map: Record<number, string> = {
    2: "Duplex", 3: "Triplex", 4: "Quadruplex", 5: "Quintuplex", 6: "Sixplex",
  };
  return map[n] ?? (fr ? `Multi ${n} portes` : `${n}-door multi`);
}

function median(xs: number[]): number | null {
  if (!xs.length) return null;
  const s = [...xs].sort((a, b) => a - b);
  return s[Math.floor(s.length / 2)];
}

function Chip({ k, v }: { k: string; v: string | number }) {
  return (
    <div className="kv-cell">
      <p className="k">{k}</p>
      <p className="v break-words">{v}</p>
    </div>
  );
}

/** Frise des portes : une porte dessinée par logement (signature ValoPlex). */
function DoorsRow({ doors, perDoor, lang }: { doors: number; perDoor: number | null; lang: string }) {
  const shown = Math.min(doors, 10);
  const extra = doors - shown;
  return (
    <div className="flex flex-wrap items-end gap-1.5" aria-label={`${doors} portes`}>
      {Array.from({ length: shown }, (_, i) => (
        <svg key={i} width="30" height="44" viewBox="0 0 30 44" className="rise" style={{ animationDelay: `${i * 60}ms` }}>
          <rect x="2" y="4" width="26" height="38" fill="var(--surface)" stroke="var(--ink)" strokeWidth="1.6" />
          <rect x="5.5" y="8" width="19" height="30" fill="var(--lime)" stroke="var(--ink)" strokeWidth="1.3" />
          <rect x="8" y="11" width="14" height="8" fill="var(--surface)" stroke="var(--ink)" strokeWidth="1" />
          <circle cx="20.5" cy="25" r="1.6" fill="var(--ink)" />
          <text x="15" y="41.5" textAnchor="middle" fontSize="6.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">
            {i + 1}
          </text>
        </svg>
      ))}
      {extra > 0 && (
        <span className="vp-mono mb-1 rounded-md border-[1.5px] border-ink bg-ink px-2 py-1 text-[11px] font-bold text-lime">
          +{extra}
        </span>
      )}
      {perDoor != null && (
        <span className="vp-mono mb-1 ml-2 text-[11px] font-bold uppercase tracking-[0.06em] text-green-deep">
          ≈ {fmt(Math.round(perDoor / 100) * 100, lang)} / {lang === "fr" ? "porte" : "door"}
        </span>
      )}
    </div>
  );
}

export default function ResultView({ data }: { data: UnitEstimate }) {
  const { lang, t } = useLang();
  const [activeComp, setActiveComp] = useState<string | null>(null);
  const r: EstimateResult = data.result;
  const u = data.unit;
  const s = u?.specs;
  const fr = lang === "fr";
  const histMax = Math.max(...(u?.history.map((h) => h.value ?? 0) ?? [0]), 1);
  const moneyFmt = (v: number) =>
    new Intl.NumberFormat(fr ? "fr-CA" : "en-CA", {
      style: "currency",
      currency: "CAD",
      maximumFractionDigits: 0,
    }).format(Math.round(v / 100) * 100);

  const doors = u?.nbLogements ?? null;
  const hasComps = r.nCompsUsed > 0;
  const perDoor = doors && doors >= 2 ? r.estimate / doors : null;
  const perM2 = u?.aireEtagesM2 ? r.estimate / u.aireEtagesM2 : null;
  const age = u?.anneeConstruction ? 2026 - u.anneeConstruction : null;

  // benchmark : médianes du marché local à partir des comparables retenus
  const mktPerDoor = median(
    r.comps.filter((c) => c.doors && c.doors >= 2).map((c) => c.amount / c.doors!)
  );
  const mktPerM2 = median(
    r.comps.filter((c) => c.floorArea && c.floorArea > 20).map((c) => c.amount / c.floorArea!)
  );

  return (
    <div className="space-y-10 py-8">
      {/* fil d'ariane */}
      <nav className="vp-mono flex flex-wrap items-center gap-2 text-[11.5px] uppercase tracking-[0.06em] text-ink-3">
        <Link href="/" className="border-b-[1.5px] border-transparent hover:border-green hover:text-green">
          ValoPlex
        </Link>
        <span>/</span>
        <span>{u ? `${u.adresse ?? ""} · ${u.municipalite ?? ""}` : t("manualTitle")}</span>
      </nav>

      {/* ---- Panneau prix ---- */}
      <section className="vp-card rise p-6 sm:p-8">
        <div className="flex flex-wrap items-start justify-between gap-6">
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-3">
              <span className="kicker">{t("estimatedValue")}</span>
              <span className="vp-mono rotate-[-1deg] rounded-md border-[1.5px] border-ink bg-lime px-2.5 py-1 text-[11px] font-bold uppercase tracking-[0.08em] text-ink">
                {doorsLabel(doors, fr)}
              </span>
            </div>
            {u && (
              <h1 className="vp-display mt-2 text-[clamp(20px,3vw,28px)] font-bold uppercase leading-tight tracking-[-0.02em]">
                {u.adresse}
                {u.municipalite ? <span className="text-ink-3"> · {u.municipalite}</span> : null}
              </h1>
            )}
            <p className="vp-display mt-3 text-[clamp(44px,7vw,72px)] font-bold leading-none tracking-[-0.04em]">
              <CountUp value={r.estimate} format={moneyFmt} />
            </p>
            {doors != null && doors >= 2 && (
              <div className="mt-4">
                <DoorsRow doors={doors} perDoor={perDoor} lang={lang} />
              </div>
            )}
            <div className="mt-5 flex flex-wrap items-center gap-x-6 gap-y-3">
              {perM2 != null && (
                <div>
                  <p className="klabel">{fr ? "Prix au m²" : "Price / m²"}</p>
                  <p className="vp-display text-[19px] font-bold">{fmt(Math.round(perM2), lang)}</p>
                </div>
              )}
              <div>
                <p className="klabel">{t("range")}</p>
                <p className="vp-display text-[19px] font-bold">
                  {fmt(r.low, lang)} <span className="text-ink-3">→</span> {fmt(r.high, lang)}
                </p>
              </div>
              {u?.valeurRole != null && u.valeurRole > 0 && (
                <div>
                  <p className="klabel">{fr ? "Écart vs rôle" : "vs assessment"}</p>
                  <p className="vp-display text-[19px] font-bold text-green-deep">
                    {pct((r.estimate / u.valeurRole - 1) * 100)}
                  </p>
                </div>
              )}
            </div>
            {u && (
              <div className="mt-6 flex flex-wrap gap-2.5">
                <a href={`/api/report?id=${encodeURIComponent(u.id)}`} className="btn btn-primary" download>
                  {fr ? "Rapport PDF" : "PDF report"} ↓
                </a>
                <a href={`/api/report/pro?id=${encodeURIComponent(u.id)}`} className="btn btn-ghost" download>
                  {fr ? "Rapport détaillé format professionnel (banque)" : "Detailed professional report (bank)"} ↓
                </a>
              </div>
            )}
          </div>
          <div className="shrink-0">
            <ConfidenceDial
              pct={r.confidencePct}
              level={r.confidenceLevel}
              label={`${t("confidence")} — ${t(`conf${r.confidenceLevel}` as TKey)}`}
            />
          </div>
        </div>
        <p className="vp-mono mt-5 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pt-3 text-[10.5px] uppercase tracking-[0.05em] text-ink-3">
          {t("disclaimer")}
        </p>
      </section>

      {/* ---- L'économie du plex, porte par porte ---- */}
      {u && s && doors != null && doors >= 2 && (
        <section>
          <span className="kicker">{fr ? "Porte par porte" : "Door by door"}</span>
          <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
            {fr ? "L'économie du plex" : "The plex economics"}
          </h2>
          <div className="mt-4 grid grid-cols-2 gap-3.5 lg:grid-cols-4">
            {(
              [
                [fr ? "Valeur estimée / porte" : "Estimated / door", perDoor != null ? fmt(Math.round(perDoor / 100) * 100, lang) : "—", true],
                [fr ? "Rôle / porte" : "Assessed / door", u.valeurRole ? fmt(Math.round(u.valeurRole / doors), lang) : "—", false],
                [fr ? "Aire habitable / porte" : "Living area / door", u.aireEtagesM2 ? locNum(Math.round(u.aireEtagesM2 / doors), lang, { unit: "m²" }) : "—", false],
                [fr ? "Terrain / porte" : "Land / door", u.superficieTerrainM2 ? locNum(Math.round(u.superficieTerrainM2 / doors), lang, { unit: "m²" }) : "—", false],
              ] as [string, string, boolean][]
            ).map(([k, v, hero], i) => (
              <div key={k} className={`vp-card vp-card-hover rise p-4 ${hero ? "!bg-ink" : ""}`} style={{ animationDelay: `${i * 70}ms` }}>
                <p className={`vp-display text-[clamp(17px,2.2vw,24px)] font-bold tracking-[-0.03em] ${hero ? "text-lime" : ""}`}>{v}</p>
                <p className={`vp-mono mt-1.5 text-[9.5px] font-bold uppercase tracking-[0.09em] ${hero ? "text-[rgba(255,159,69,0.7)]" : "text-ink-3"}`}>{k}</p>
              </div>
            ))}
          </div>
          {/* benchmark vs marché local */}
          {(mktPerDoor != null || mktPerM2 != null) && (
            <div className="vp-card mt-3.5 flex flex-wrap items-center gap-x-6 gap-y-2 p-4">
              <p className="klabel">{fr ? "Vs le marché local (médiane des comparables)" : "Vs local market (comps median)"}</p>
              {mktPerDoor != null && perDoor != null && (
                <p className="vp-mono text-[12px]">
                  {fr ? "$/porte marché" : "market $/door"} : <b>{fmt(Math.round(mktPerDoor), lang)}</b>
                  <span className={`ml-2 rounded-[4px] border border-ink px-1.5 py-0.5 text-[10px] font-bold ${perDoor >= mktPerDoor ? "bg-lime text-ink" : "bg-amber-soft text-ink"}`}>
                    {fr ? "votre plex" : "your plex"} {pct((perDoor / mktPerDoor - 1) * 100)}
                  </span>
                </p>
              )}
              {mktPerM2 != null && perM2 != null && (
                <p className="vp-mono text-[12px]">
                  {fr ? "$/m² marché" : "market $/m²"} : <b>{fmt(Math.round(mktPerM2), lang)}</b>
                  <span className={`ml-2 rounded-[4px] border border-ink px-1.5 py-0.5 text-[10px] font-bold ${perM2 >= mktPerM2 ? "bg-lime text-ink" : "bg-amber-soft text-ink"}`}>
                    {fr ? "votre plex" : "your plex"} {pct((perM2 / mktPerM2 - 1) * 100)}
                  </span>
                </p>
              )}
            </div>
          )}
        </section>
      )}

      {/* ---- Pro forma de l'investisseur ---- */}
      {u && doors != null && doors >= 2 && r.estimate > 0 && (
        <Proforma
          valeur={r.estimate}
          doors={doors}
          valeurRole={u.valeurRole}
          municipalite={u.municipalite}
        />
      )}

      {/* ---- Portrait du plex (bento du registre) ---- */}
      {u && s && (
        <section>
          <span className="kicker">{fr ? "Registre officiel — dessiné par les données du plex" : "Official record — drawn by the plex data"}</span>
          <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
            {fr ? "Portrait du plex" : "Plex portrait"}
          </h2>
          {/* adresses officielles de chaque porte (table des adresses du rôle) */}
          {s.portesAdresses.length > 0 && (
            <div className="vp-card rise mt-4 p-5">
              <div className="flex flex-wrap items-baseline justify-between gap-2">
                <p className="klabel">
                  {fr ? "Les portes officielles du plex (rôle foncier)" : "The plex's official doors (assessment roll)"}
                </p>
                <p className="vp-mono text-[10px] uppercase tracking-[0.05em] text-ink-3">
                  {s.nAdresses ?? s.portesAdresses.length} {fr ? "inscription(s) d'adresse" : "address record(s)"}
                </p>
              </div>
              <div className="mt-3 flex flex-wrap gap-2">
                {s.portesAdresses.map((a, i) => (
                  <span key={a} className="stat-chip !py-1.5 rise" style={{ animationDelay: `${i * 50}ms` }}>
                    <b>{i + 1}</b> {a}
                  </span>
                ))}
              </div>
              <p className="vp-mono mt-3 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pt-2 text-[10px] uppercase tracking-[0.05em] text-ink-3">
                {fr
                  ? "Le rôle public ne détaille pas l'intérieur de chaque logement (pièces, loyers) — voici les inscriptions d'adresses officielles de l'unité."
                  : "The public roll does not detail each dwelling's interior (rooms, rents) — these are the unit's official address records."}
              </p>
            </div>
          )}
          <div className="mt-4 grid gap-4 lg:grid-cols-3">
            {/* Bâtiment */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "60ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? `Bâtiment — ${doorsLabel(doors, fr).toLowerCase()}` : `Building — ${doorsLabel(doors, fr).toLowerCase()}`}
              </p>
              <div className="flex justify-center py-2">
                <BuildingGlyph
                  floors={s.nbEtages}
                  dwellings={doors}
                  genre={s.genreConstruction}
                  yearBuilt={u.anneeConstruction}
                  floorAreaM2={u.aireEtagesM2}
                  lang={lang}
                />
              </div>
              <EraLine year={u.anneeConstruction} lang={lang} />
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip k={fr ? "Portes" : "Doors"} v={doors ?? "—"} />
                <Chip k={fr ? "Étages" : "Storeys"} v={s.nbEtages ?? "—"} />
                <Chip k={fr ? "Aire d'étages" : "Floor area"} v={u.aireEtagesM2 ? locNum(u.aireEtagesM2, lang, { unit: "m²" }) : "—"} />
                <Chip k={fr ? "Âge" : "Age"} v={age != null ? `${age} ${fr ? "ans" : "yrs"} (${u.anneeConstruction})` : "—"} />
                <Chip k={fr ? "Genre" : "Style"} v={s.genreConstruction ?? "—"} />
                <Chip k={fr ? "Lien physique" : "Physical link"} v={s.lienPhysique ?? "—"} />
                <Chip
                  k={fr ? "Mixité commerciale" : "Commercial mix"}
                  v={s.nbLocauxNonResid ? `${s.nbLocauxNonResid} ${fr ? "local(aux)" : "unit(s)"}` : fr ? "Aucune" : "None"}
                />
                <Chip k={fr ? "Chambres locatives" : "Rental rooms"} v={s.nbChambresLocatives ?? (fr ? "Aucune" : "None")} />
              </div>
            </div>
            {/* Terrain */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "140ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? "Terrain — à l'échelle" : "Lot — to scale"}
              </p>
              <div className="flex justify-center py-2">
                <LotDiagram
                  areaM2={u.superficieTerrainM2}
                  frontageM={s.frontTerrainM}
                  footprintM2={u.aireEtagesM2 && s.nbEtages ? u.aireEtagesM2 / Math.max(1, s.nbEtages) : u.aireEtagesM2}
                  lang={lang}
                  isCondo={false}
                />
              </div>
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip k={fr ? "Superficie" : "Area"} v={u.superficieTerrainM2 ? locNum(u.superficieTerrainM2, lang, { unit: "m²" }) : "—"} />
                <Chip k={fr ? "Frontage" : "Frontage"} v={s.frontTerrainM ? locNum(s.frontTerrainM, lang, { unit: "m" }) : "—"} />
                <Chip
                  k={fr ? "Emprise au sol ≈" : "Ground coverage ≈"}
                  v={
                    u.superficieTerrainM2 && u.aireEtagesM2 && s.nbEtages
                      ? `${Math.min(100, Math.round((u.aireEtagesM2 / Math.max(1, s.nbEtages) / u.superficieTerrainM2) * 100))} %`
                      : "—"
                  }
                />
                <Chip k={fr ? "Unité de voisinage" : "Neighbourhood"} v={s.uniteVoisinage || "—"} />
              </div>
            </div>
            {/* Valeur au rôle */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "220ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? "Valeur au rôle 2026 — composition" : "2026 assessed value — split"}
              </p>
              <p className="vp-display py-2 text-[26px] font-bold tracking-[-0.02em]">{fmt(u.valeurRole, lang)}</p>
              <ValueSplit
                land={s.valeurTerrain}
                building={s.valeurBatiment}
                previous={s.valeurAnterieure}
                total={u.valeurRole}
                lang={lang}
                labels={{
                  land: fr ? "Terrain" : "Land",
                  building: fr ? "Bâtiment" : "Building",
                  previous: fr ? "Rôle antérieur" : "Previous roll",
                }}
              />
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip
                  k={fr ? "Bâtiment / m²" : "Building / m²"}
                  v={s.valeurBatiment && u.aireEtagesM2 ? fmt(Math.round(s.valeurBatiment / u.aireEtagesM2), lang) : "—"}
                />
                <Chip k={fr ? "Rôle par porte" : "Assessed / door"} v={u.valeurRole && doors ? fmt(Math.round(u.valeurRole / doors), lang) : "—"} />
                <Chip k={fr ? "Cond. marché au" : "Market cond."} v={s.datCondMarche ?? "—"} />
                <Chip k={fr ? "Matricule" : "Roll no."} v={s.matricule ?? "—"} />
              </div>
            </div>
          </div>
          {/* registre brut complet */}
          <details className="vp-card mt-4 p-5">
            <summary className="vp-mono cursor-pointer text-[11px] font-bold uppercase tracking-[0.08em] text-green-deep">
              {fr ? "▸ Toutes les données du registre (brutes)" : "▸ All registry data (raw)"}
            </summary>
            <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
              <Chip k={fr ? "Année construction" : "Year built"} v={u.anneeConstruction ? `${u.anneeConstruction}${s.anneeEstimee === "E" ? (fr ? " (estimée)" : " (est.)") : ""}` : "—"} />
              <Chip k="CUBF" v={s.cubf ? `${s.cubf} — ${s.cubfLibelle ?? ""}` : "—"} />
              <Chip k={fr ? "Locaux non résid." : "Non-res. units"} v={s.nbLocauxNonResid ?? "—"} />
              <Chip k={fr ? "Chambres locatives" : "Rental rooms"} v={s.nbChambresLocatives ?? "—"} />
              <Chip k={fr ? "Arrondissement" : "Borough"} v={s.arrond || "—"} />
              <Chip k={fr ? "Adresses sur l'unité" : "Addresses"} v={s.nAdresses ?? "—"} />
              <Chip k={fr ? "Valeur terrain" : "Land value"} v={fmt(s.valeurTerrain, lang)} />
              <Chip k={fr ? "Valeur bâtiment" : "Building value"} v={fmt(s.valeurBatiment, lang)} />
              <Chip k={fr ? "Rôle antérieur" : "Previous roll"} v={fmt(s.valeurAnterieure, lang)} />
              <Chip k="ID provincial" v={u.id} />
            </div>
          </details>
        </section>
      )}

      {/* ---- Transparence du calcul ---- */}
      <section>
        <span className="kicker">{fr ? "Transparence" : "Transparency"}</span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">{t("whyTitle")}</h2>
        <div className="mt-4 grid gap-4 sm:grid-cols-2">
          <div className="vp-card vp-card-hover rise p-5">
            <p className="klabel">{t("modelPart")}</p>
            <p className="vp-display mt-2 text-[30px] font-bold tracking-[-0.03em]">
              {r.modelEstimate != null ? <CountUp value={r.modelEstimate} format={moneyFmt} /> : "—"}
            </p>
            <p className="vp-mono mt-1 text-[11px] uppercase tracking-[0.06em] text-green-deep">
              {t("weightModel")} : {(r.modelWeight * 100).toFixed(0)} %
            </p>
          </div>
          <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "100ms" }}>
            <p className="klabel">{t("compsPart")}</p>
            {hasComps ? (
              <>
                <p className="vp-display mt-2 text-[30px] font-bold tracking-[-0.03em]">
                  {r.compsEstimate != null ? <CountUp value={r.compsEstimate} format={moneyFmt} /> : "—"}
                </p>
                <p className="vp-mono mt-1 text-[11px] uppercase tracking-[0.06em] text-green-deep">
                  {t("weightComps")} : {((1 - r.modelWeight) * 100).toFixed(0)} % · {r.nCompsUsed} plex
                  {r.compsDispersionPct != null ? ` · ±${r.compsDispersionPct} %` : ""}
                </p>
              </>
            ) : (
              <>
                <p className="vp-display mt-2 text-[20px] font-bold tracking-[-0.02em] text-ink-3">
                  {fr ? "Aucun plex comparable" : "No comparable plex"}
                </p>
                <p className="mt-1 max-w-sm text-[12.5px] text-ink-2">
                  {fr
                    ? "Immeuble hors gabarit pour son secteur : l'estimation repose à 100 % sur le modèle spécialisé, et la fourchette calibrée s'élargit en conséquence."
                    : "Out-of-scale building for its area: the estimate relies 100% on the specialized model, and the calibrated range widens accordingly."}
                </p>
              </>
            )}
          </div>
        </div>
      </section>

      {/* ---- Historique ---- */}
      {u && u.history.some((h) => h.value != null) && (
        <section>
          <span className="kicker">2021 → 2026</span>
          <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">{t("history")}</h2>
          <div className="vp-card rise mt-4 p-5 sm:p-6">
            <div className="flex flex-col gap-2">
              {u.history.map((h, i) => {
                const prev = i > 0 ? u.history[i - 1].value : null;
                const yoy = h.value != null && prev != null && prev > 0 ? (h.value / prev - 1) * 100 : null;
                return (
                  <div key={h.year} className="hbar-row grid grid-cols-[44px_1fr_auto] items-center gap-2 sm:grid-cols-[52px_1fr_auto] sm:gap-3">
                    <span className="vp-mono text-[12px] font-bold">{h.year}</span>
                    <span className="hbar-track">
                      <span
                        className="hbar-fill grow-x"
                        style={{
                          width: `${((h.value ?? 0) / histMax) * 100}%`,
                          animationDelay: `${i * 90}ms`,
                          background: h.year === 2026 ? "var(--ink)" : undefined,
                        }}
                      />
                    </span>
                    <span className="vp-mono flex items-center justify-end gap-2 text-[12px] font-bold">
                      {fmt(h.value, lang)}
                      {doors != null && doors >= 2 && h.value != null && (
                        <span className="hidden text-[10px] font-normal text-ink-3 sm:inline">
                          ({fmt(Math.round(h.value / doors), lang)}/{fr ? "porte" : "door"})
                        </span>
                      )}
                      {yoy != null && (
                        <span className={`rounded-[4px] border border-ink px-1 py-px text-[9px] ${yoy >= 0 ? "bg-lime-soft text-green-deep" : "bg-[var(--danger-soft)] text-[var(--danger)]"}`}>
                          {pct(yoy)}
                        </span>
                      )}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      )}

      {/* ---- Plan des comparables OU état vide honnête ---- */}
      <section>
        <span className="kicker">
          {hasComps ? `${r.nCompsUsed} ${fr ? "ventes de plex" : "plex sales"}` : fr ? "Comparables" : "Comparables"}
        </span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">{t("compsTitle")}</h2>
        {hasComps ? (
          <div className="mt-4 grid items-start gap-4 lg:grid-cols-[1.05fr_1fr]">
            <div className="overflow-hidden rounded-[10px] border-[1.5px] border-ink shadow-[8px_8px_0_rgba(20,24,20,0.08)]">
              <RadarMap
                subject={{
                  lat: u?.lat ?? r.comps[0]?.lat ?? 46.81,
                  lng: u?.lng ?? r.comps[0]?.lng ?? -71.21,
                  label: u?.adresse ?? (fr ? "Plex évalué" : "Subject plex"),
                }}
                comps={r.comps.map((c) => ({
                  id: c.id,
                  lat: c.lat,
                  lng: c.lng,
                  label: `${c.street ?? ""}, ${c.city ?? ""}`,
                  price: fmt(c.amount, lang),
                  adjusted: fmt(Math.round(c.adjustedPrice), lang),
                  date: c.date,
                  distanceM: c.distanceM,
                  weight: c.weight,
                }))}
                highlight={activeComp}
                onHover={setActiveComp}
              />
            </div>
            <div className="src-wrap max-h-[560px] overflow-y-auto">
              <table className="src-table">
                <thead className="sticky top-0 z-10">
                  <tr>
                    <th>#</th>
                    <th>{fr ? "Vente" : "Sale"}</th>
                    <th className="text-right">{t("adjusted")}</th>
                  </tr>
                </thead>
                <tbody>
                  {r.comps.map((c, i) => (
                    <tr
                      key={c.id}
                      onMouseEnter={() => setActiveComp(c.id)}
                      onMouseLeave={() => setActiveComp(null)}
                      className={activeComp === c.id ? "!bg-lime-soft" : ""}
                    >
                      <td>
                        <span
                          className={`vp-mono inline-flex h-6 w-6 items-center justify-center rounded-full border-[1.5px] border-ink text-[11px] font-bold ${
                            activeComp === c.id ? "bg-lime text-ink" : "bg-green text-paper"
                          }`}
                        >
                          {i + 1}
                        </span>
                      </td>
                      <td>
                        <p className="font-semibold leading-tight">
                          {c.street}, {c.city}
                          {c.doors != null && (
                            <span className="vp-mono ml-1.5 rounded-[3px] border border-ink bg-surface-2 px-1 text-[9px] font-bold uppercase">
                              {doorsLabel(c.doors, fr)}
                            </span>
                          )}
                        </p>
                        <p className="vp-mono mt-0.5 text-[10.5px] uppercase tracking-[0.04em] text-ink-3">
                          {c.date} · {c.distanceM < 1000 ? `${Math.round(c.distanceM)} m` : `${(c.distanceM / 1000).toFixed(1)} km`} ·{" "}
                          {t("sold")} {fmt(c.amount, lang)}
                          {c.doors ? ` (${fmt(Math.round(c.amount / c.doors), lang)}/${fr ? "porte" : "door"})` : ""}
                        </p>
                        <p className="vp-mono mt-0.5 text-[10.5px] text-ink-2">
                          {t("adjTime")} {signed(c.adjTime, lang)} · {t("adjArea")} {signed(c.adjArea, lang)} ·{" "}
                          {t("adjAge")} {signed(c.adjAge, lang)} · {t("adjPortes")} {signed(c.adjDoors, lang)}
                        </p>
                      </td>
                      <td className="vp-display text-right font-bold">
                        {fmt(Math.round(c.adjustedPrice), lang)}
                        <p className="vp-mono text-[10px] font-normal text-ink-3">
                          {t("weight")} {(c.weight * 100).toFixed(0)} %
                        </p>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ) : (
          <div className="vp-card mt-4 flex flex-col items-center gap-3 p-10 text-center">
            <p className="vp-display text-[40px]">⌂</p>
            <p className="vp-display text-[18px] font-bold uppercase tracking-[-0.01em]">
              {fr ? "Aucun plex comparable dans le secteur" : "No comparable plex in the area"}
            </p>
            <p className="max-w-lg text-[13.5px] text-ink-2">
              {fr
                ? `Aucune vente récente de plex de gabarit semblable (${doorsLabel(doors, fr).toLowerCase()}) n'a été trouvée à proximité. L'estimation repose entièrement sur le modèle hédonique spécialisé, entraîné sur 91 060 ventes de plex à travers le Québec — la fourchette calibrée reflète cette incertitude supplémentaire.`
                : `No recent sale of a similar-scale plex (${doorsLabel(doors, fr).toLowerCase()}) was found nearby. The estimate relies entirely on the specialized hedonic model, trained on 91,060 plex sales across Québec — the calibrated range reflects this added uncertainty.`}
            </p>
          </div>
        )}
      </section>

      {/* ---- Lead ---- */}
      <section className="rounded-[10px] border-[1.5px] border-ink bg-ink p-6 text-paper shadow-[8px_8px_0_rgba(20,24,20,0.2)] sm:p-8">
        <h2 className="vp-display text-[22px] font-bold uppercase tracking-[-0.02em] text-lime">{t("leadTitle")}</h2>
        <div className="mt-4 max-w-xl">
          <LeadForm unitId={u?.id ?? null} estimate={r.estimate} />
        </div>
      </section>
    </div>
  );
}
