Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/components/avendre/EvalWorkbench.tsx9 * Module : components10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Vrai-Prix — atelier « mon évaluation » d'une propriété à vendre.43/**44 * Quatre temps, comme un rapport d'évaluation par comparaison directe :45 * 01 bassin — ventes réelles (et annonces actives) autour du sujet, l'utilisateur46 * coche celles qu'il juge comparables (les 12 du moteur sont signalées) ;47 * 02 grille — ajustements en dollars (marché, superficie, âge, + libres),48 * pré-remplis avec les formules du moteur mais entièrement modifiables ;49 * 03 réconciliation — médiane, moyenne, moyennes pondérées ; valeur conclue ;50 * 04 comparaison — face à la mesure Vrai-Prix déjà calculée (hybride, hédonique,51 * comparables, coût, rôle indexé, ensemble), au prix demandé et au rôle.52 * Tout est conservé sur l'appareil (localStorage) — aucun envoi au serveur.53 */54"use client";55import { useCallback, useEffect, useMemo, useRef, useState } from "react";56import Link from "next/link";57import { useLang } from "@/components/LangContext";58import RadarMap, { type RadarComp } from "@/components/RadarMap";59import { TYPE_MATCH } from "@/lib/engine";60import type { CompCandidate, CompsPayload } from "@/lib/comps";61import type { TypeGroupKey } from "@/lib/immoka";62import { groupLabel } from "./ListingCardView";63import { dateFr, mean, median, money, num, pct, round100, signedMoney, sqftToM2, weightedMean, weightedMedian } from "./fmt";6465/* ---------------------------------- types --------------------------------- */66export interface WorkbenchHead {67 uid: string;68 address: string | null;69 city: string | null;70 propertyType: string | null;71 group: TypeGroupKey;72 price: number;73 image: string | null;74 bedrooms: number | null;75 bathrooms: number | null;76 areaSqft: number | null;77 lotSqft: number | null;78 yearBuilt: number | null;79 geolocated: boolean;80 eval: {81 est: number | null;82 low: number | null;83 high: number | null;84 confidence: string | null;85 modelEst: number | null;86 compsEst: number | null;87 costEst: number | null;88 roleEst: number | null;89 ensEst: number | null;90 valeurRole: number | null;91 nComps: number | null;92 unitId: string | null;93 evaluatedAt: string | null;94 } | null;95}9697interface Extra {98 id: string;99 label: string;100 amount: number;101}102interface CompState {103 adjTime: number;104 adjArea: number;105 adjAge: number;106 extras: Extra[];107 weight: number; // 1..5108 rev?: number; // incrémenté à chaque « ↺ moteur » → remonte les champs (key)109}110type Method = "median" | "mean" | "wmean" | "wmedian";111interface Params {112 months: number;113 radiusKm: number;114 includeListings: boolean;115 sameType: boolean;116}117interface Saved {118 v: 1;119 params: Params;120 selected: string[];121 states: Record<string, CompState>;122 snap: Record<string, CompCandidate>;123 method: Method;124 rangePct: number;125 finalValue: number | null;126}127128const DEFAULT_PARAMS: Params = { months: 24, radiusKm: 3, includeListings: true, sameType: true };129const key = (uid: string) => `vrai-prix-avendre:${uid}`;130131const adjustedOf = (c: CompCandidate, s: CompState) =>132 c.amount + s.adjTime + s.adjArea + s.adjAge + s.extras.reduce((a, e) => a + (Number.isFinite(e.amount) ? e.amount : 0), 0);133const grossAdjPct = (c: CompCandidate, s: CompState) =>134 ((Math.abs(s.adjTime) + Math.abs(s.adjArea) + Math.abs(s.adjAge) + s.extras.reduce((a, e) => a + Math.abs(e.amount || 0), 0)) / c.amount) * 100;135136const fmtDist = (m: number) => (m < 1000 ? `${m} m` : `${(m / 1000).toFixed(1).replace(".", ",")} km`);137138/* ------------------------------- sous-blocs -------------------------------- */139function Sect({ num: n, kicker, title, right }: { num: string; kicker: string; title: string; right?: React.ReactNode }) {140 return (141 <header className="sec">142 <div className="flex flex-wrap items-baseline justify-between gap-2">143 <span className="sec-num">144 {n} — {kicker}145 </span>146 {right}147 </div>148 <h2 className="vp-display mt-2 text-[clamp(20px,3vw,28px)] font-bold uppercase leading-[1.05] tracking-[-0.025em]">{title}</h2>149 </header>150 );151}152153/** Champ monétaire : texte libre pendant la saisie ; remonté par `key` quand le parent réinitialise. */154function MoneyInput({ value, onChange, hint, label }: { value: number; onChange: (v: number) => void; hint?: string; label: string }) {155 const [txt, setTxt] = useState(() => String(Math.round(value)));156 return (157 <label className="block">158 <span className="klabel">{label}</span>159 <input160 value={txt}161 inputMode="numeric"162 onChange={(e) => {163 const t = e.target.value.replace(/[^\d-]/g, "");164 setTxt(t);165 const n = Number(t);166 if (Number.isFinite(n) && t !== "" && t !== "-") onChange(n);167 if (t === "") onChange(0);168 }}169 className="vp-input vp-mono mt-0.5 text-[13px]"170 />171 {hint && <span className="vp-mono mt-0.5 block text-[9.5px] uppercase tracking-[0.05em] text-ink-3">{hint}</span>}172 </label>173 );174}175176/** Graphique à points : chaque repère sur sa ligne, échelle commune, ma valeur en trait vertical. */177function DotPlot({178 rows,179 me,180 lang,181}: {182 rows: { key: string; label: string; value: number | null; band?: [number, number] | null; tone: "me" | "main" | "method" | "ask" | "role" }[];183 me: number | null;184 lang: string;185}) {186 const vals = rows.flatMap((r) => [r.value, r.band?.[0], r.band?.[1]]).filter((v): v is number => v != null && Number.isFinite(v));187 if (!vals.length) return null;188 const lo = Math.min(...vals) * 0.96;189 const hi = Math.max(...vals) * 1.04;190 const W = 760;191 const L = 250;192 const R = 24;193 const RH = 30;194 const H = rows.length * RH + 28;195 const x = (v: number) => L + ((v - lo) / (hi - lo)) * (W - L - R);196 const ticks = 4;197 return (198 <svg viewBox={`0 0 ${W} ${H}`} className="w-full" role="img" aria-label="Comparaison des valeurs">199 {Array.from({ length: ticks + 1 }, (_, i) => lo + ((hi - lo) * i) / ticks).map((v, i) => (200 <g key={i}>201 <line x1={x(v)} y1={4} x2={x(v)} y2={H - 22} stroke="var(--line)" strokeWidth="1" />202 <text x={x(v)} y={H - 8} textAnchor="middle" fontSize="9.5" fontFamily="var(--font-jetbrains), monospace" fill="var(--ink-3)">203 {new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", { notation: "compact", maximumFractionDigits: 0 }).format(v)} $204 </text>205 </g>206 ))}207 {me != null && Number.isFinite(me) && <line x1={x(me)} y1={2} x2={x(me)} y2={H - 22} stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="4 4" />}208 {rows.map((r, i) => {209 const y = i * RH + RH / 2 + 4;210 const color = r.tone === "me" ? "var(--accent)" : r.tone === "ask" ? "var(--danger)" : r.tone === "role" ? "var(--ink-3)" : "var(--ink)";211 return (212 <g key={r.key}>213 <text x={0} y={y + 4} fontSize={r.tone === "me" || r.tone === "main" ? 11.5 : 10.5} fontWeight={r.tone === "me" || r.tone === "main" ? 700 : 500} fontFamily="var(--font-space-grotesk), sans-serif" fill={color}>214 {r.label.length > 40 ? r.label.slice(0, 39) + "…" : r.label}215 </text>216 <line x1={L} y1={y} x2={W - R} y2={y} stroke="var(--line-soft)" strokeWidth="1" />217 {r.band && r.band[1] > r.band[0] && <rect x={x(r.band[0])} y={y - 6} width={Math.max(2, x(r.band[1]) - x(r.band[0]))} height={12} fill={color} opacity={0.14} />}218 {r.value != null && Number.isFinite(r.value) && (219 <>220 {r.tone === "me" ? (221 <rect x={x(r.value) - 7} y={y - 7} width={14} height={14} transform={`rotate(45 ${x(r.value)} ${y})`} fill={color} stroke="var(--paper)" strokeWidth="1.5" />222 ) : (223 <circle cx={x(r.value)} cy={y} r={r.tone === "main" ? 6.5 : 5} fill={r.tone === "ask" ? "var(--paper)" : color} stroke={color} strokeWidth={2} />224 )}225 <text x={x(r.value) + (x(r.value) > W - 120 ? -12 : 12)} y={y + 4} textAnchor={x(r.value) > W - 120 ? "end" : "start"} fontSize="10.5" fontWeight="700" fontFamily="var(--font-jetbrains), monospace" fill={color}>226 {money(r.value, lang)}227 </text>228 </>229 )}230 </g>231 );232 })}233 </svg>234 );235}236237/* --------------------------------- atelier --------------------------------- */238export default function EvalWorkbench({ head }: { head: WorkbenchHead }) {239 const { lang } = useLang();240 const fr = lang === "fr";241 const [params, setParams] = useState<Params>(DEFAULT_PARAMS);242 const [data, setData] = useState<CompsPayload | null>(null);243 // la réponse (ou l'erreur) porte la clé de la requête qui l'a produite :244 // « en chargement » = la requête courante n'est pas encore servie245 const reqKey = `${head.uid}|${params.months}|${params.radiusKm}|${params.includeListings ? 1 : 0}`;246 const [dataKey, setDataKey] = useState<string | null>(null);247 const [errState, setErrState] = useState<{ key: string; msg: string } | null>(null);248 const error = errState?.key === reqKey ? errState.msg : null;249 const [selected, setSelected] = useState<string[]>([]);250 const [states, setStates] = useState<Record<string, CompState>>({});251 const [snap, setSnap] = useState<Record<string, CompCandidate>>({});252 const [method, setMethod] = useState<Method>("wmedian");253 const [rangePct, setRangePct] = useState(8);254 const [finalValue, setFinalValue] = useState<number | null>(null);255 const [finalTxt, setFinalTxt] = useState("");256 const [hover, setHover] = useState<string | null>(null);257 const [sortBy, setSortBy] = useState<"weight" | "distance" | "date" | "price">("weight");258 const [showAll, setShowAll] = useState(false);259 const [ready, setReady] = useState(false);260 const abortRef = useRef<AbortController | null>(null);261262 /* --- restauration locale --- */263 useEffect(() => {264 const id = setTimeout(() => {265 try {266 const raw = window.localStorage.getItem(key(head.uid));267 if (raw) {268 const s = JSON.parse(raw) as Saved;269 if (s.v === 1) {270 setParams({ ...DEFAULT_PARAMS, ...s.params });271 setSelected(s.selected ?? []);272 setStates(s.states ?? {});273 setSnap(s.snap ?? {});274 setMethod(s.method ?? "wmedian");275 setRangePct(s.rangePct ?? 8);276 setFinalValue(s.finalValue ?? null);277 if (s.finalValue != null) setFinalTxt(String(Math.round(s.finalValue)));278 }279 }280 } catch {}281 setReady(true);282 }, 0);283 return () => clearTimeout(id);284 }, [head.uid]);285286 /* --- sauvegarde locale (débouncée) --- */287 useEffect(() => {288 if (!ready) return;289 const id = setTimeout(() => {290 try {291 const s: Saved = { v: 1, params, selected, states, snap, method, rangePct, finalValue };292 window.localStorage.setItem(key(head.uid), JSON.stringify(s));293 } catch {}294 }, 300);295 return () => clearTimeout(id);296 }, [ready, params, selected, states, snap, method, rangePct, finalValue, head.uid]);297298 /* --- bassin de comparables --- */299 useEffect(() => {300 if (!ready || !head.geolocated) return;301 abortRef.current?.abort();302 const ctl = new AbortController();303 abortRef.current = ctl;304 const key = `${head.uid}|${params.months}|${params.radiusKm}|${params.includeListings ? 1 : 0}`;305 const qs = new URLSearchParams({306 uid: head.uid,307 months: String(params.months),308 radius: String(params.radiusKm),309 listings: params.includeListings ? "1" : "0",310 limit: "80",311 });312 fetch(`/api/avendre/comps?${qs}`, { signal: ctl.signal })313 .then(async (r) => {314 if (!r.ok) throw new Error((await r.json()).error ?? r.statusText);315 return r.json() as Promise<CompsPayload>;316 })317 .then((d) => {318 if (ctl.signal.aborted) return;319 setData(d);320 setDataKey(key);321 })322 .catch((e) => {323 if (ctl.signal.aborted) return;324 setErrState({ key, msg: String(e.message ?? e) });325 });326 return () => ctl.abort();327 }, [ready, head.uid, head.geolocated, params.months, params.radiusKm, params.includeListings]);328329 const loading = head.geolocated && ready && dataKey !== reqKey && error == null;330 const subject = data?.subject ?? null;331 const subjArea = subject?.floorArea ?? sqftToM2(head.areaSqft);332333 const pool = useMemo(() => {334 if (!data) return [] as CompCandidate[];335 let list = data.comps;336 if (params.sameType && subject) {337 const types = TYPE_MATCH[subject.typeProp] ?? TYPE_MATCH.autre;338 list = list.filter((c) => c.kind === "listing" || (c.propertyType != null && types.includes(c.propertyType)));339 }340 const sorted = [...list];341 sorted.sort((a, b) => {342 if (sortBy === "distance") return a.distanceM - b.distanceM;343 if (sortBy === "date") return b.date.localeCompare(a.date);344 if (sortBy === "price") return a.amount - b.amount;345 return Number(b.engineUsed) - Number(a.engineUsed) || b.weight - a.weight;346 });347 return sorted;348 }, [data, params.sameType, sortBy, subject]);349350 const visible = showAll ? pool : pool.slice(0, 30);351 const maxW = useMemo(() => Math.max(1e-6, ...pool.map((c) => c.weight)), [pool]);352353 const compOf = useCallback((id: string): CompCandidate | undefined => data?.comps.find((c) => c.id === id) ?? snap[id], [data, snap]);354355 const toggle = (c: CompCandidate) => {356 setSelected((prev) => (prev.includes(c.id) ? prev.filter((x) => x !== c.id) : [...prev, c.id]));357 setSnap((prev) => (prev[c.id] ? prev : { ...prev, [c.id]: c }));358 setStates((prev) =>359 prev[c.id] ? prev : { ...prev, [c.id]: { adjTime: c.adjTime, adjArea: c.adjArea, adjAge: c.adjAge, extras: [], weight: c.engineUsed ? 4 : 3 } }360 );361 };362 const takeEngine = () => {363 if (!data) return;364 const eng = data.comps.filter((c) => c.engineUsed);365 setSelected(eng.map((c) => c.id));366 setSnap((prev) => ({ ...prev, ...Object.fromEntries(eng.map((c) => [c.id, c])) }));367 setStates((prev) => ({368 ...prev,369 ...Object.fromEntries(eng.map((c) => [c.id, prev[c.id] ?? { adjTime: c.adjTime, adjArea: c.adjArea, adjAge: c.adjAge, extras: [], weight: 4 }])),370 }));371 };372 const clearAll = () => setSelected([]);373 const resetAll = () => {374 setSelected([]);375 setStates({});376 setSnap({});377 setMethod("wmedian");378 setRangePct(8);379 setFinalValue(null);380 setFinalTxt("");381 setParams(DEFAULT_PARAMS);382 try {383 window.localStorage.removeItem(key(head.uid));384 } catch {}385 };386 const patchState = (id: string, patch: Partial<CompState>) => setStates((prev) => ({ ...prev, [id]: { ...prev[id], ...patch } }));387388 /* --- réconciliation --- */389 const chosen = selected.map((id) => ({ c: compOf(id), s: states[id] })).filter((x): x is { c: CompCandidate; s: CompState } => !!x.c && !!x.s);390 const adjusted = chosen.map(({ c, s }) => adjustedOf(c, s));391 const weights = chosen.map(({ s }) => s.weight);392 const indications: Record<Method, number | null> = {393 median: median(adjusted),394 mean: mean(adjusted),395 wmean: weightedMean(adjusted, weights),396 wmedian: weightedMedian(adjusted, weights),397 };398 const indication = indications[method];399 const myValue = finalValue ?? (indication != null ? round100(indication) : null);400 const dispersion = (() => {401 if (adjusted.length < 2 || indication == null || indication <= 0) return null;402 const dev = adjusted.map((v) => Math.abs(v - indication) / indication).sort((a, b) => a - b);403 return dev[Math.floor(dev.length / 2)] * 100;404 })();405 const avgGross = chosen.length ? chosen.reduce((a, { c, s }) => a + grossAdjPct(c, s), 0) / chosen.length : null;406 const engineOverlap = chosen.filter(({ c }) => c.engineUsed).length;407408 /* --- repères de comparaison --- */409 const ev = head.eval;410 const vpMain = ev?.est ?? data?.engine.estimate ?? null;411 const vpLow = ev?.low ?? data?.engine.low ?? null;412 const vpHigh = ev?.high ?? data?.engine.high ?? null;413 const rows = [414 { key: "me", label: fr ? "Ma valeur conclue" : "My concluded value", value: myValue, band: myValue != null ? ([myValue * (1 - rangePct / 100), myValue * (1 + rangePct / 100)] as [number, number]) : null, tone: "me" as const },415 { key: "vp", label: fr ? "Vrai-Prix — hybride (mesure principale)" : "Vrai-Prix — hybrid (main measure)", value: vpMain, band: vpLow != null && vpHigh != null ? ([vpLow, vpHigh] as [number, number]) : null, tone: "main" as const },416 { key: "model", label: fr ? "Modèle hédonique" : "Hedonic model", value: ev?.modelEst ?? data?.engine.modelEstimate ?? null, tone: "method" as const },417 { key: "comps", label: fr ? "Comparables du moteur" : "Engine comparables", value: ev?.compsEst ?? data?.engine.compsEstimate ?? null, tone: "method" as const },418 { key: "cost", label: fr ? "Méthode du coût" : "Cost approach", value: ev?.costEst ?? null, tone: "method" as const },419 { key: "role_idx", label: fr ? "Rôle indexé (IAAO)" : "Indexed roll (IAAO)", value: ev?.roleEst ?? null, tone: "method" as const },420 { key: "ens", label: fr ? "Ensemble des méthodes" : "Ensemble of methods", value: ev?.ensEst ?? null, tone: "method" as const },421 { key: "ask", label: fr ? "Prix demandé" : "Asking price", value: head.price, tone: "ask" as const },422 { key: "role", label: fr ? "Valeur au rôle" : "Assessed value", value: ev?.valeurRole ?? null, tone: "role" as const },423 ].filter((r) => r.value != null || r.key === "me");424425 const diffPct = (v: number | null) => (v != null && myValue != null && v > 0 ? ((myValue - v) / v) * 100 : null);426 const inBand = myValue != null && vpLow != null && vpHigh != null ? myValue >= vpLow && myValue <= vpHigh : null;427428 const radarComps: RadarComp[] = visible.map((c) => ({429 id: c.id,430 lat: c.lat,431 lng: c.lng,432 label: `${c.street ?? "—"}${c.city ? `, ${c.city}` : ""}${c.kind === "listing" ? (fr ? " (en vente)" : " (for sale)") : ""}`,433 price: money(c.amount, lang),434 adjusted: money(states[c.id] ? adjustedOf(c, states[c.id]) : c.adjustedPrice, lang),435 date: dateFr(c.date, lang),436 distanceM: c.distanceM,437 weight: selected.includes(c.id) ? 1 : (c.weight / maxW) * 0.5,438 }));439440 const step = (n: number, done: boolean, label: string) => (441 <span className={`vp-mono flex items-center gap-1.5 text-[10px] uppercase tracking-[0.08em] ${done ? "text-ink" : "text-ink-3"}`}>442 <span className={`inline-flex h-5 w-5 items-center justify-center border text-[10px] font-bold ${done ? "border-ink bg-ink text-paper" : "border-[var(--line-strong)]"}`}>{n}</span>443 {label}444 </span>445 );446447 return (448 <div className="space-y-12 py-8">449 {/* ================= masthead ================= */}450 <section className="rise">451 <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 border-b-2 border-ink pb-2.5">452 <nav className="vp-mono flex min-w-0 flex-wrap items-center gap-2 text-[10.5px] uppercase tracking-[0.08em] text-ink-3">453 <Link href="/" className="text-ink-2 hover:text-accent-deep">454 Vrai Prix455 </Link>456 <span aria-hidden="true">/</span>457 <Link href="/a-vendre" className="text-ink-2 hover:text-accent-deep">458 {fr ? "À vendre" : "For sale"}459 </Link>460 <span aria-hidden="true">/</span>461 <Link href={`/a-vendre/${encodeURIComponent(head.uid)}`} className="truncate text-ink-2 hover:text-accent-deep">462 {fr ? "Fiche" : "Listing"}463 </Link>464 <span aria-hidden="true">/</span>465 <span>{fr ? "Mon évaluation" : "My valuation"}</span>466 </nav>467 <div className="flex flex-wrap gap-4 print:hidden">468 {step(1, selected.length > 0, fr ? `Comparables (${selected.length})` : `Comparables (${selected.length})`)}469 {step(2, selected.length > 0, fr ? "Ajustements" : "Adjustments")}470 {step(3, myValue != null, fr ? "Réconciliation" : "Reconciliation")}471 {step(4, myValue != null, fr ? "Comparaison" : "Comparison")}472 </div>473 </div>474 <div className="mt-6 grid gap-x-10 gap-y-6 lg:grid-cols-[1fr_260px]">475 <div className="min-w-0">476 <span className="kicker">{fr ? "Atelier — mode exercice" : "Workshop — exercise mode"}</span>477 <h1 className="vp-display mt-2 text-[clamp(22px,3.2vw,34px)] font-bold uppercase leading-tight tracking-[-0.025em]">478 {fr ? "Mon évaluation" : "My valuation"} <span className="text-ink-3">·</span> {head.address || head.propertyType || "—"}479 {head.city ? <span className="text-ink-3"> · {head.city}</span> : null}480 </h1>481 <p className="vp-mono mt-3 text-[11px] uppercase tracking-[0.06em] text-ink-2">482 {[483 groupLabel(head.group, fr),484 `${fr ? "prix demandé" : "asking"} ${money(head.price, lang)}`,485 subjArea ? `${num(subjArea, lang)} m²` : null,486 (subject?.yearBuilt ?? head.yearBuilt) ? `${fr ? "constr." : "built"} ${subject?.yearBuilt ?? head.yearBuilt}` : null,487 subject?.landArea ? `${fr ? "terrain" : "lot"} ${num(subject.landArea, lang)} m²` : null,488 head.bedrooms != null ? `${head.bedrooms} ${fr ? "ch." : "bd"}` : null,489 ]490 .filter(Boolean)491 .join(" · ")}492 </p>493 {subject && (494 <p className="mt-2 text-[12.5px] text-ink-3">495 {subject.fromUnit496 ? fr497 ? `Caractéristiques du sujet lues au rôle d'évaluation (unité ${subject.unitId}) : type ${subject.typeProp}, aire d'étages, terrain, année.`498 : `Subject characteristics read from the assessment roll (unit ${subject.unitId}): type ${subject.typeProp}, floor area, lot, year.`499 : fr500 ? "Aucune unité du rôle jumelée : les caractéristiques du sujet viennent de l'annonce (superficie et année déclarées par le vendeur)."501 : "No roll unit matched: subject characteristics come from the listing (area and year declared by the seller)."}502 </p>503 )}504 <div className="mt-5 flex flex-wrap gap-2.5 print:hidden">505 <Link href={`/a-vendre/${encodeURIComponent(head.uid)}`} className="btn btn-ghost">506 ← {fr ? "Fiche de la propriété" : "Property listing"}507 </Link>508 <button type="button" className="btn btn-ghost" onClick={() => window.print()}>509 {fr ? "Imprimer / PDF" : "Print / PDF"}510 </button>511 <button type="button" className="btn btn-ghost" onClick={resetAll}>512 ↺ {fr ? "Réinitialiser l'atelier" : "Reset workshop"}513 </button>514 </div>515 </div>516 {head.image && (517 // eslint-disable-next-line @next/next/no-img-element518 <img src={head.image} alt="" referrerPolicy="no-referrer" className="aspect-[4/3] w-full border border-[var(--line)] object-cover" />519 )}520 </div>521 </section>522523 {!head.geolocated && (524 <p className="border-l-2 border-[var(--danger)] pl-4 text-[14px] text-ink-2">525 {fr ? "Cette annonce n'est pas géolocalisée : impossible de chercher des comparables autour d'elle." : "This listing is not geolocated: comparables cannot be searched around it."}526 </p>527 )}528529 {/* ================= 01 — bassin ================= */}530 <section>531 <Sect532 num="01"533 kicker={fr ? "Sélection" : "Selection"}534 title={fr ? "Choisir mes comparables" : "Choose my comparables"}535 right={536 <span className="vp-mono text-[10px] uppercase tracking-[0.08em] text-ink-3">537 {data ? `${pool.length} ${fr ? "candidats" : "candidates"} · ${data.comps.filter((c) => c.engineUsed).length} ${fr ? "retenus par le moteur" : "kept by the engine"}` : ""}538 </span>539 }540 />541 <p className="mt-3 max-w-3xl text-[13.5px] leading-relaxed text-ink-2">542 {fr543 ? "Ventes réelles publiées autour du sujet (et, si vous le souhaitez, annonces actives voisines — des prix demandés, pas des ventes). Cochez les propriétés que VOUS jugez comparables : même marché, même type, superficie et âge voisins, vente récente. Le moteur signale ses 12 choix, mais c'est votre jugement qui compte ici."544 : "Published real sales around the subject (and, optionally, nearby active listings — asking prices, not sales). Tick the properties YOU judge comparable: same market, same type, similar size and age, recent sale. The engine flags its 12 picks, but your judgment is what matters here."}545 </p>546547 <div className="mt-5 grid gap-4 print:hidden sm:grid-cols-2 lg:grid-cols-[1fr_1fr_1fr_1fr_auto]">548 <label className="block">549 <span className="klabel">{fr ? "Rayon de recherche" : "Search radius"}</span>550 <select value={params.radiusKm} onChange={(e) => setParams({ ...params, radiusKm: Number(e.target.value) })} className="vp-input mt-1 cursor-pointer">551 {[1, 2, 3, 5, 10, 20].map((k) => (552 <option key={k} value={k}>553 {k} km554 </option>555 ))}556 </select>557 </label>558 <label className="block">559 <span className="klabel">{fr ? "Ventes depuis" : "Sales since"}</span>560 <select value={params.months} onChange={(e) => setParams({ ...params, months: Number(e.target.value) })} className="vp-input mt-1 cursor-pointer">561 {[12, 24, 36, 60].map((m) => (562 <option key={m} value={m}>563 {m} {fr ? "mois" : "months"}564 </option>565 ))}566 </select>567 </label>568 <label className="block">569 <span className="klabel">{fr ? "Trier par" : "Sort by"}</span>570 <select value={sortBy} onChange={(e) => setSortBy(e.target.value as typeof sortBy)} className="vp-input mt-1 cursor-pointer">571 <option value="weight">{fr ? "Pertinence (poids moteur)" : "Relevance (engine weight)"}</option>572 <option value="distance">{fr ? "Distance" : "Distance"}</option>573 <option value="date">{fr ? "Date (récentes d'abord)" : "Date (newest first)"}</option>574 <option value="price">{fr ? "Prix" : "Price"}</option>575 </select>576 </label>577 <div className="flex flex-col justify-end gap-1.5 text-[13px]">578 <label className="flex items-center gap-2">579 <input type="checkbox" checked={params.sameType} onChange={(e) => setParams({ ...params, sameType: e.target.checked })} className="h-4 w-4 accent-[var(--accent)]" />580 {fr ? "Même famille de type" : "Same type family"}581 </label>582 <label className="flex items-center gap-2">583 <input type="checkbox" checked={params.includeListings} onChange={(e) => setParams({ ...params, includeListings: e.target.checked })} className="h-4 w-4 accent-[var(--accent)]" />584 {fr ? "Inclure les annonces actives" : "Include active listings"}585 </label>586 </div>587 <div className="flex flex-col justify-end gap-2">588 <button type="button" className="btn btn-primary whitespace-nowrap" onClick={takeEngine} disabled={!data}>589 {fr ? "Reprendre les 12 du moteur" : "Take the engine's 12"}590 </button>591 <button type="button" className="btn btn-ghost whitespace-nowrap" onClick={clearAll} disabled={!selected.length}>592 {fr ? "Tout retirer" : "Clear all"}593 </button>594 </div>595 </div>596597 {error && <p className="mt-4 text-[13px] text-[var(--danger)]">{error}</p>}598599 <div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,420px)_1fr]">600 {subject && (601 <div className="border border-[var(--line)]">602 <RadarMap subject={{ lat: subject.lat, lng: subject.lng, label: head.address ?? head.uid }} comps={radarComps} highlight={hover} onHover={setHover} />603 <p className="vp-mono border-t border-[var(--line)] px-3 py-2 text-[9.5px] uppercase tracking-[0.06em] text-ink-3">604 {fr ? "Gros cercles = comparables cochés. Survolez une ligne du tableau pour la repérer." : "Large circles = ticked comparables. Hover a table row to locate it."}605 </p>606 </div>607 )}608 <div className={`src-wrap ${loading ? "opacity-60" : ""}`}>609 <table className="src-table">610 <thead>611 <tr>612 <th></th>613 <th>#</th>614 <th>{fr ? "Propriété" : "Property"}</th>615 <th>{fr ? "Date" : "Date"}</th>616 <th className="text-right">{fr ? "Prix" : "Price"}</th>617 <th className="text-right">{fr ? "Dist." : "Dist."}</th>618 <th className="text-right">m²</th>619 <th className="text-right">{fr ? "Année" : "Year"}</th>620 <th>{fr ? "Type" : "Type"}</th>621 </tr>622 </thead>623 <tbody>624 {visible.map((c, i) => {625 const on = selected.includes(c.id);626 return (627 <tr628 key={c.id}629 onMouseEnter={() => setHover(c.id)}630 onMouseLeave={() => setHover(null)}631 onClick={() => toggle(c)}632 className={`cursor-pointer ${on ? "bg-[var(--accent-soft)]" : ""} ${hover === c.id ? "outline outline-1 outline-[var(--accent)]" : ""}`}633 >634 <td>635 <input type="checkbox" checked={on} onChange={() => toggle(c)} onClick={(e) => e.stopPropagation()} className="h-4 w-4 accent-[var(--accent)]" aria-label={fr ? "Retenir ce comparable" : "Keep this comparable"} />636 </td>637 <td className="vp-mono text-[11px] text-ink-3">{i + 1}</td>638 <td>639 <p className="font-semibold leading-snug">{c.street ?? "—"}</p>640 <p className="vp-mono text-[10px] uppercase tracking-[0.05em] text-ink-3">641 {c.city ?? ""}642 {c.engineUsed ? <span className="ml-2 border border-ink px-1 text-ink">{fr ? "moteur" : "engine"}</span> : null}643 {c.kind === "listing" ? <span className="ml-2 border border-[var(--danger)] px-1 text-[var(--danger)]">{fr ? "en vente" : "for sale"}</span> : null}644 </p>645 </td>646 <td className="vp-mono whitespace-nowrap text-[12px]">{c.kind === "listing" ? (fr ? "actuel" : "current") : dateFr(c.date, lang)}</td>647 <td className="vp-mono whitespace-nowrap text-right font-bold">{money(c.amount, lang)}</td>648 <td className="vp-mono whitespace-nowrap text-right text-[12px]">{fmtDist(c.distanceM)}</td>649 <td className="vp-mono text-right text-[12px]">{c.floorArea ? num(c.floorArea, lang) : "—"}</td>650 <td className="vp-mono text-right text-[12px]">{c.yearBuilt ?? "—"}</td>651 <td className="text-[12px] text-ink-2">{c.propertyType ?? "—"}</td>652 </tr>653 );654 })}655 {!loading && data && visible.length === 0 && (656 <tr>657 <td colSpan={9} className="text-center text-ink-3">658 {fr ? "Aucun candidat avec ces critères — élargissez le rayon ou la fenêtre." : "No candidate with these criteria — widen the radius or window."}659 </td>660 </tr>661 )}662 </tbody>663 </table>664 {pool.length > visible.length && (665 <button type="button" className="btn btn-ghost mt-3 w-full print:hidden" onClick={() => setShowAll(true)}>666 {fr ? `Voir les ${pool.length - visible.length} autres candidats` : `Show the ${pool.length - visible.length} other candidates`}667 </button>668 )}669 </div>670 </div>671 </section>672673 {/* ================= 02 — ajustements ================= */}674 <section>675 <Sect num="02" kicker={fr ? "Grille" : "Grid"} title={fr ? "Ajuster chaque comparable au sujet" : "Adjust each comparable to the subject"} />676 <p className="mt-3 max-w-3xl text-[13.5px] leading-relaxed text-ink-2">677 {fr678 ? "On ajuste le comparable vers le sujet : si le comparable est plus petit, on ajoute ; s'il est meilleur, on retire. Les trois ajustements du moteur sont pré-remplis (marché = indice mensuel du type ; superficie = 50 % du $/m² marginal, borné à ±25 % ; âge = 0,5 %/an, borné à ±10 %). Modifiez-les, ajoutez les vôtres (garage, terrain, état, vue…) et pondérez de 1 à 5."679 : "Comparables are adjusted toward the subject: smaller comparable → add; better comparable → subtract. The engine's three adjustments are prefilled (market = monthly type index; area = 50% of marginal $/m², capped ±25%; age = 0.5%/yr, capped ±10%). Edit them, add your own (garage, lot, condition, view…) and weight 1 to 5."}680 </p>681 {chosen.length === 0 ? (682 <p className="mt-6 border border-dashed border-[var(--line-strong)] p-6 text-center text-[13.5px] text-ink-3">683 {fr ? "Cochez au moins un comparable ci-dessus pour ouvrir la grille." : "Tick at least one comparable above to open the grid."}684 </p>685 ) : (686 <div className="mt-6 space-y-5">687 {chosen.map(({ c, s }, i) => {688 const adj = adjustedOf(c, s);689 const gross = grossAdjPct(c, s);690 return (691 <article key={c.id} className="border border-[var(--line)] bg-surface p-4 sm:p-5">692 <header className="flex flex-wrap items-baseline justify-between gap-2 border-b border-[var(--line)] pb-3">693 <div className="min-w-0">694 <p className="vp-display text-[15px] font-bold uppercase tracking-[-0.01em]">695 <span className="vp-mono mr-2 text-[11px] text-accent">C{i + 1}</span>696 {c.street ?? "—"}697 {c.city ? <span className="text-ink-3"> · {c.city}</span> : null}698 </p>699 <p className="vp-mono mt-0.5 text-[10px] uppercase tracking-[0.05em] text-ink-3">700 {c.kind === "listing" ? (fr ? "annonce active — prix demandé" : "active listing — asking price") : `${fr ? "vendu le" : "sold"} ${dateFr(c.date, lang)}`} · {fmtDist(c.distanceM)}701 {c.floorArea ? ` · ${num(c.floorArea, lang)} m²` : ""}702 {c.yearBuilt ? ` · ${c.yearBuilt}` : ""}703 {c.propertyType ? ` · ${c.propertyType}` : ""}704 {c.engineUsed ? ` · ${fr ? "retenu par le moteur" : "kept by the engine"}` : ""}705 {c.idProvinc ? (706 <>707 {" · "}708 <Link href={`/estimation/${encodeURIComponent(c.idProvinc)}`} className="text-accent underline-offset-2 hover:underline">709 {fr ? "fiche" : "record"}710 </Link>711 </>712 ) : null}713 {c.uid ? (714 <>715 {" · "}716 <Link href={`/a-vendre/${encodeURIComponent(c.uid)}`} className="text-accent underline-offset-2 hover:underline">717 {fr ? "annonce" : "listing"}718 </Link>719 </>720 ) : null}721 </p>722 </div>723 <div className="flex items-center gap-2 print:hidden">724 <button type="button" className="vp-mono text-[10.5px] uppercase tracking-[0.08em] text-ink-2 hover:text-accent-deep" onClick={() => patchState(c.id, { adjTime: c.adjTime, adjArea: c.adjArea, adjAge: c.adjAge, extras: [], rev: (s.rev ?? 0) + 1 })}>725 ↺ {fr ? "moteur" : "engine"}726 </button>727 <button type="button" className="vp-mono text-[10.5px] uppercase tracking-[0.08em] text-[var(--danger)]" onClick={() => setSelected((p) => p.filter((x) => x !== c.id))}>728 ✕ {fr ? "retirer" : "remove"}729 </button>730 </div>731 </header>732 <div className="mt-4 grid gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-[1fr_1fr_1fr_1fr_1.2fr]">733 <div>734 <p className="klabel">{c.kind === "listing" ? (fr ? "Prix demandé" : "Asking price") : fr ? "Prix de vente" : "Sale price"}</p>735 <p className="vp-display mt-1 text-[20px] font-bold tracking-[-0.02em]">{money(c.amount, lang)}</p>736 {c.valeurRole ? <p className="vp-mono text-[9.5px] uppercase tracking-[0.05em] text-ink-3">{fr ? "rôle" : "roll"} {money(c.valeurRole, lang)}</p> : null}737 </div>738 <MoneyInput739 key={`t${s.rev ?? 0}`}740 label={fr ? "Ajust. marché ($)" : "Market adj. ($)"}741 value={s.adjTime}742 onChange={(v) => patchState(c.id, { adjTime: v })}743 hint={`${fr ? "moteur" : "engine"} ${signedMoney(c.adjTime, lang)} · ${c.kind === "listing" ? (fr ? "actuel" : "current") : `${num(c.monthsAgo, lang)} ${fr ? "mois" : "mo"}`}`}744 />745 <MoneyInput746 key={`a${s.rev ?? 0}`}747 label={fr ? "Ajust. superficie ($)" : "Area adj. ($)"}748 value={s.adjArea}749 onChange={(v) => patchState(c.id, { adjArea: v })}750 hint={`${fr ? "moteur" : "engine"} ${signedMoney(c.adjArea, lang)}${subjArea && c.floorArea ? ` · Δ ${subjArea - c.floorArea >= 0 ? "+" : "−"}${num(Math.abs(subjArea - c.floorArea), lang)} m²` : ""}`}751 />752 <MoneyInput753 key={`g${s.rev ?? 0}`}754 label={fr ? "Ajust. âge ($)" : "Age adj. ($)"}755 value={s.adjAge}756 onChange={(v) => patchState(c.id, { adjAge: v })}757 hint={`${fr ? "moteur" : "engine"} ${signedMoney(c.adjAge, lang)}${(subject?.yearBuilt ?? head.yearBuilt) && c.yearBuilt ? ` · Δ ${(subject?.yearBuilt ?? head.yearBuilt)! - c.yearBuilt} ${fr ? "ans" : "yrs"}` : ""}`}758 />759 <div className="border-l-2 border-accent pl-4">760 <p className="klabel">{fr ? "Prix ajusté" : "Adjusted price"}</p>761 <p className="vp-display mt-1 text-[24px] font-bold tracking-[-0.02em]">{money(adj, lang)}</p>762 <p className={`vp-mono text-[9.5px] uppercase tracking-[0.05em] ${gross > 25 ? "text-[var(--danger)]" : "text-ink-3"}`}>763 {fr ? "ajust. brut" : "gross adj."} {pct(gross, lang, 1, false)}764 {gross > 25 ? (fr ? " — comparable faible" : " — weak comparable") : ""}765 </p>766 </div>767 </div>768 {/* ajustements libres */}769 <div className="mt-4 grid gap-x-6 gap-y-3 sm:grid-cols-[1fr_auto]">770 <div className="space-y-2">771 {s.extras.map((x) => (772 <div key={x.id} className="grid grid-cols-[1fr_140px_auto] items-end gap-3">773 <label className="block">774 <span className="klabel">{fr ? "Ajustement libre" : "Custom adjustment"}</span>775 <input value={x.label} onChange={(e) => patchState(c.id, { extras: s.extras.map((y) => (y.id === x.id ? { ...y, label: e.target.value } : y)) })} placeholder={fr ? "ex. garage, piscine, état, vue…" : "e.g. garage, pool, condition, view…"} className="vp-input mt-0.5 text-[13px]" />776 </label>777 <MoneyInput label="$" value={x.amount} onChange={(v) => patchState(c.id, { extras: s.extras.map((y) => (y.id === x.id ? { ...y, amount: v } : y)) })} />778 <button type="button" className="vp-mono pb-2 text-[11px] text-[var(--danger)] print:hidden" onClick={() => patchState(c.id, { extras: s.extras.filter((y) => y.id !== x.id) })} aria-label={fr ? "Supprimer" : "Delete"}>779 ✕780 </button>781 </div>782 ))}783 <button type="button" className="vp-mono text-[10.5px] font-bold uppercase tracking-[0.08em] text-accent print:hidden" onClick={() => patchState(c.id, { extras: [...s.extras, { id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, label: "", amount: 0 }] })}>784 + {fr ? "ajouter un ajustement" : "add an adjustment"}785 </button>786 </div>787 <div>788 <p className="klabel">{fr ? "Poids (1-5)" : "Weight (1-5)"}</p>789 <div className="mt-1 flex gap-1">790 {[1, 2, 3, 4, 5].map((w) => (791 <button key={w} type="button" onClick={() => patchState(c.id, { weight: w })} className={`vp-mono h-8 w-8 border text-[12px] font-bold ${s.weight === w ? "border-ink bg-ink text-paper" : "border-[var(--line-strong)] text-ink-2"}`} aria-pressed={s.weight === w}>792 {w}793 </button>794 ))}795 </div>796 </div>797 </div>798 </article>799 );800 })}801 <p className="vp-mono overflow-x-auto whitespace-nowrap border-l-2 border-accent bg-surface px-3 py-2 text-[11.5px] text-ink">802 {fr ? "prix ajusté = prix + ajust. marché + ajust. superficie + ajust. âge + Σ ajustements libres" : "adjusted price = price + market adj. + area adj. + age adj. + Σ custom adjustments"}803 </p>804 </div>805 )}806 </section>807808 {/* ================= 03 — réconciliation ================= */}809 <section>810 <Sect num="03" kicker={fr ? "Conclusion" : "Conclusion"} title={fr ? "Réconcilier ma valeur" : "Reconcile my value"} />811 {chosen.length === 0 ? (812 <p className="mt-6 text-[13.5px] text-ink-3">{fr ? "La réconciliation s'ouvre dès qu'un comparable est retenu." : "Reconciliation opens as soon as one comparable is kept."}</p>813 ) : (814 <div className="mt-6 grid gap-x-12 gap-y-8 lg:grid-cols-[1.3fr_1fr]">815 <div>816 <p className="klabel">{fr ? "Indications de valeur selon la règle de réconciliation" : "Value indications by reconciliation rule"}</p>817 <div className="mt-2 grid grid-cols-2 gap-3 sm:grid-cols-4">818 {(819 [820 ["median", fr ? "Médiane" : "Median"],821 ["mean", fr ? "Moyenne" : "Mean"],822 ["wmean", fr ? "Moyenne pondérée" : "Weighted mean"],823 ["wmedian", fr ? "Médiane pondérée" : "Weighted median"],824 ] as [Method, string][]825 ).map(([k, label]) => (826 <button key={k} type="button" onClick={() => setMethod(k)} aria-pressed={method === k} className={`border p-3 text-left ${method === k ? "border-ink bg-ink text-paper" : "border-[var(--line)] bg-surface hover:border-[var(--line-strong)]"}`}>827 <p className={`vp-mono text-[9.5px] uppercase tracking-[0.08em] ${method === k ? "text-paper/70" : "text-ink-3"}`}>{label}</p>828 <p className="vp-display mt-1 text-[17px] font-bold tracking-[-0.02em]">{indications[k] != null ? money(round100(indications[k]!), lang) : "—"}</p>829 </button>830 ))}831 </div>832 <div className="mt-6 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4">833 <div className="kv-cell">834 <p className="k">{fr ? "Comparables" : "Comparables"}</p>835 <p className="v">836 {chosen.length} <span className="text-ink-3">({engineOverlap} {fr ? "du moteur" : "engine"})</span>837 </p>838 </div>839 <div className="kv-cell">840 <p className="k">{fr ? "Étendue ajustée" : "Adjusted range"}</p>841 <p className="v text-[12.5px]">842 {money(Math.min(...adjusted), lang)} – {money(Math.max(...adjusted), lang)}843 </p>844 </div>845 <div className="kv-cell">846 <p className="k">{fr ? "Dispersion médiane" : "Median dispersion"}</p>847 <p className="v">{dispersion != null ? `±${pct(dispersion, lang, 1, false)}` : "—"}</p>848 </div>849 <div className="kv-cell">850 <p className="k">{fr ? "Ajust. brut moyen" : "Avg gross adj."}</p>851 <p className={`v ${avgGross != null && avgGross > 25 ? "text-[var(--danger)]" : ""}`}>{avgGross != null ? pct(avgGross, lang, 1, false) : "—"}</p>852 </div>853 </div>854 <p className="mt-4 max-w-2xl text-[13px] leading-relaxed text-ink-2">855 {fr856 ? "La médiane résiste aux valeurs extrêmes ; la moyenne pondérée laisse parler votre confiance dans chaque comparable. Le rapport final ne retient qu'UNE valeur conclue, arrondie, avec une fourchette qui reflète la dispersion observée."857 : "The median resists outliers; the weighted mean lets your confidence in each comparable speak. The final report keeps ONE concluded value, rounded, with a range reflecting the observed dispersion."}858 </p>859 </div>860 <div className="lg:border-l lg:border-[var(--line)] lg:pl-10">861 <label className="block">862 <span className="klabel">{fr ? "Ma valeur conclue ($)" : "My concluded value ($)"}</span>863 <input864 value={finalTxt !== "" ? finalTxt : myValue != null ? String(Math.round(myValue)) : ""}865 inputMode="numeric"866 onChange={(e) => {867 const t = e.target.value.replace(/\D/g, "");868 setFinalTxt(t);869 setFinalValue(t ? Number(t) : null);870 }}871 className="vp-input vp-display mt-1 text-[32px] font-bold tracking-[-0.03em]"872 />873 </label>874 <button875 type="button"876 className="vp-mono mt-2 text-[10.5px] font-bold uppercase tracking-[0.08em] text-accent print:hidden"877 onClick={() => {878 setFinalValue(null);879 setFinalTxt("");880 }}881 >882 ↺ {fr ? "reprendre l'indication" : "take the indication"} ({indication != null ? money(round100(indication), lang) : "—"})883 </button>884 <label className="mt-6 block">885 <span className="klabel">886 {fr ? "Fourchette" : "Range"} ±{rangePct} %887 </span>888 <input type="range" min={1} max={30} value={rangePct} onChange={(e) => setRangePct(Number(e.target.value))} className="mt-2 w-full accent-[var(--accent)]" />889 </label>890 {myValue != null && (891 <p className="vp-mono mt-2 text-[11px] uppercase tracking-[0.05em] text-ink-2">892 {money(round100(myValue * (1 - rangePct / 100)), lang)} – {money(round100(myValue * (1 + rangePct / 100)), lang)}893 {subjArea ? ` · ${num(Math.round(myValue / subjArea), lang)} $/m²` : ""}894 </p>895 )}896 {dispersion != null && (897 <button type="button" className="vp-mono mt-2 text-[10px] uppercase tracking-[0.08em] text-ink-3 print:hidden" onClick={() => setRangePct(Math.max(1, Math.min(30, Math.round(dispersion))))}>898 {fr ? "→ aligner sur la dispersion" : "→ align on dispersion"} (±{Math.round(dispersion)} %)899 </button>900 )}901 </div>902 </div>903 )}904 </section>905906 {/* ================= 04 — comparaison ================= */}907 <section>908 <Sect num="04" kicker={fr ? "Confrontation" : "Confrontation"} title={fr ? "Ma valeur face à la mesure Vrai-Prix" : "My value vs. the Vrai-Prix measure"} />909 {myValue == null ? (910 <p className="mt-6 text-[13.5px] text-ink-3">{fr ? "Concluez une valeur pour la comparer." : "Conclude a value to compare it."}</p>911 ) : (912 <div className="mt-6 space-y-8">913 <div className="border border-[var(--line)] bg-surface p-3 sm:p-5">914 <DotPlot rows={rows} me={myValue} lang={lang} />915 <p className="vp-mono mt-1 text-[9.5px] uppercase tracking-[0.06em] text-ink-3">916 {fr ? "Bandes : ma fourchette (bleu) et l'intervalle P10-P90 de Vrai-Prix (encre). Trait pointillé : ma valeur." : "Bands: my range (blue) and the Vrai-Prix P10-P90 interval (ink). Dashed line: my value."}917 </p>918 </div>919 <div className="grid gap-x-12 gap-y-8 lg:grid-cols-[1.2fr_1fr]">920 <div className="src-wrap">921 <table className="src-table">922 <thead>923 <tr>924 <th>{fr ? "Repère" : "Benchmark"}</th>925 <th className="text-right">{fr ? "Valeur" : "Value"}</th>926 <th className="text-right">{fr ? "Ma valeur − repère" : "My value − benchmark"}</th>927 <th className="text-right">%</th>928 </tr>929 </thead>930 <tbody>931 {rows932 .filter((r) => r.key !== "me")933 .map((r) => {934 const d = r.value != null ? myValue - r.value : null;935 const p = diffPct(r.value);936 return (937 <tr key={r.key} className={r.tone === "main" ? "font-bold" : ""}>938 <td>{r.label}</td>939 <td className="vp-mono text-right">{money(r.value, lang)}</td>940 <td className={`vp-mono text-right ${d != null && d < 0 ? "text-[var(--danger)]" : ""}`}>{d != null ? signedMoney(d, lang) : "—"}</td>941 <td className={`vp-mono text-right ${p != null && p < 0 ? "text-[var(--danger)]" : ""}`}>{pct(p, lang, 1)}</td>942 </tr>943 );944 })}945 </tbody>946 </table>947 </div>948 <div className="space-y-4 text-[14px] leading-relaxed text-ink-2 lg:border-l lg:border-[var(--line)] lg:pl-10">949 <p className="klabel">{fr ? "Lecture" : "Reading"}</p>950 {vpMain != null && (951 <p>952 {fr ? (953 <>954 Votre valeur conclue (<b className="text-ink">{money(myValue, lang)}</b>) est{" "}955 <b className="text-ink">{pct(diffPct(vpMain), lang, 1)}</b> par rapport à la mesure principale Vrai-Prix ({money(vpMain, lang)}956 {ev?.confidence ? `, confiance ${ev.confidence}` : ""}).{" "}957 {inBand === true ? "Elle se situe DANS l'intervalle P10-P90 de Vrai-Prix : les deux lectures sont compatibles." : inBand === false ? "Elle se situe HORS de l'intervalle P10-P90 de Vrai-Prix : l'écart mérite d'être expliqué (comparables différents, ajustements, superficie retenue)." : ""}958 </>959 ) : (960 <>961 Your concluded value (<b className="text-ink">{money(myValue, lang)}</b>) is <b className="text-ink">{pct(diffPct(vpMain), lang, 1)}</b> relative to the main Vrai-Prix measure ({money(vpMain, lang)}962 {ev?.confidence ? `, confidence ${ev.confidence}` : ""}).{" "}963 {inBand === true ? "It lies WITHIN the Vrai-Prix P10-P90 interval: both readings are compatible." : inBand === false ? "It lies OUTSIDE the Vrai-Prix P10-P90 interval: the gap deserves an explanation (different comparables, adjustments, retained area)." : ""}964 </>965 )}966 </p>967 )}968 <p>969 {fr ? (970 <>971 Face au prix demandé ({money(head.price, lang)}), votre évaluation suggère un affichage{" "}972 <b className="text-ink">{myValue < head.price ? `au-dessus de la valeur de ${pct(((head.price - myValue) / myValue) * 100, lang, 1, false)}` : `en dessous de la valeur de ${pct(((myValue - head.price) / myValue) * 100, lang, 1, false)}`}</b>. Rappel : un prix demandé n'est pas une valeur — le marché tranche à la vente.973 </>974 ) : (975 <>976 Against the asking price ({money(head.price, lang)}), your valuation suggests a listing{" "}977 <b className="text-ink">{myValue < head.price ? `priced ${pct(((head.price - myValue) / myValue) * 100, lang, 1, false)} above value` : `priced ${pct(((myValue - head.price) / myValue) * 100, lang, 1, false)} below value`}</b>. Reminder: an asking price is not a value — the market decides at the sale.978 </>979 )}980 </p>981 <p>982 {fr983 ? `${engineOverlap} de vos ${chosen.length} comparables font partie des ${ev?.nComps ?? data?.engine.nComps ?? 12} retenus par le moteur${chosen.some(({ c }) => c.kind === "listing") ? " ; vous avez aussi retenu des annonces actives (prix demandés, non des ventes — à pondérer avec prudence)" : ""}.`984 : `${engineOverlap} of your ${chosen.length} comparables are among the ${ev?.nComps ?? data?.engine.nComps ?? 12} kept by the engine${chosen.some(({ c }) => c.kind === "listing") ? "; you also kept active listings (asking prices, not sales — weight with caution)" : ""}.`}985 </p>986 {ev?.evaluatedAt && (987 <p className="vp-mono text-[10px] uppercase tracking-[0.05em] text-ink-3">988 {fr ? "Mesure Vrai-Prix calculée le" : "Vrai-Prix measure computed on"} {ev.evaluatedAt}989 {ev.unitId ? ` · ${fr ? "unité" : "unit"} ${ev.unitId}` : ""}990 </p>991 )}992 {!ev && (993 <p className="vp-mono text-[10px] uppercase tracking-[0.05em] text-ink-3">994 {fr ? "Aucune mesure stockée pour cette annonce : repère Vrai-Prix calculé à la volée (comparables du moteur seulement)." : "No stored measure for this listing: Vrai-Prix benchmark computed on the fly (engine comparables only)."}995 </p>996 )}997 </div>998 </div>999 </div>1000 )}1001 </section>10021003 <p className="vp-mono border-t border-[var(--line)] pt-3 text-[10px] uppercase tracking-[0.05em] text-ink-3">1004 {fr1005 ? "Atelier d'évaluation — vos choix restent sur cet appareil. Ni la mesure Vrai-Prix ni votre évaluation ne constituent une évaluation professionnelle certifiée (OEAQ)."1006 : "Valuation workshop — your choices stay on this device. Neither the Vrai-Prix measure nor your valuation is a certified professional appraisal (OEAQ)."}1007 </p>1008 </div>1009 );1010}10111012// utilitaires exposés pour les tests1013export { adjustedOf, grossAdjPct };1014