Repository Public
1// Carte et proximité : le logement, les commerces, le transport, l'essence.23import { useMemo, useRef, useState } from "react";4import { useQuery } from "@tanstack/react-query";5import type { Map as MbMap } from "mapbox-gl";6import {7 Baby, BookOpen, Bus, Coffee, Cross, Dumbbell, Fuel, GraduationCap, Hospital, MapPin, Minus, Pill as PillIcon, Plus, ShoppingBasket, Store, TrainFront, Trees,8} from "lucide-react";9import { fetchCommerces, fetchGaz, type CommerceItem, type Listing } from "@/lib/api";10import { cn } from "@/lib/cn";11import { fmtDist } from "@/lib/format";12import { useInView } from "@/lib/hooks";13import { useTheme } from "@/lib/store";14import { FicheMap, type FichePoint } from "@/map/FicheMap";15import { Sheet } from "@/ui/Sheet";16import { dec1, MoreLink, Panel, Section, SourceLine, Tile } from "./kit";1718type Lucide = typeof MapPin;1920const POI: Record<string, { icon: Lucide; label: string; color: string }> = {21 metro: { icon: TrainFront, label: "Métro", color: "#454d48" },22 bus: { icon: Bus, label: "Arrêt de bus", color: "#454d48" },23 epicerie: { icon: ShoppingBasket, label: "Épicerie", color: "#245b48" },24 depanneur: { icon: Store, label: "Dépanneur", color: "#245b48" },25 pharmacie: { icon: PillIcon, label: "Pharmacie", color: "#245b48" },26 ecole: { icon: GraduationCap, label: "École", color: "#245b48" },27 garderie: { icon: Baby, label: "Garderie", color: "#245b48" },28 bibliotheque: { icon: BookOpen, label: "Bibliothèque", color: "#245b48" },29 clinique: { icon: Cross, label: "Clinique", color: "#245b48" },30 hopital: { icon: Hospital, label: "Hôpital", color: "#245b48" },31 cafe: { icon: Coffee, label: "Café", color: "#245b48" },32 parc: { icon: Trees, label: "Parc", color: "#245b48" },33 gym: { icon: Dumbbell, label: "Gym", color: "#245b48" },34};3536const GROUPS: { key: string; title: string; cats: string[] }[] = [37 { key: "transport", title: "Transport", cats: ["metro", "bus"] },38 { key: "courses", title: "Courses", cats: ["epicerie", "depanneur", "pharmacie"] },39 { key: "famille", title: "Études et famille", cats: ["ecole", "garderie", "bibliotheque"] },40 { key: "sante", title: "Santé", cats: ["clinique", "hopital"] },41 { key: "quartier", title: "Vie de quartier", cats: ["cafe", "parc", "gym"] },42];4344const TRANSIT_IDS = new Set(["metro_station", "rem_station", "arret_bus", "gare_train"]);45const BANNER_CAT: Record<string, string> = {46 metro_station: "Station de métro", rem_station: "Station du REM", arret_bus: "Arrêt de bus", gare_train: "Gare de train",47 costco: "Entrepôt", walmart: "Grande surface", metro: "Épicerie", iga: "Épicerie", maxi: "Épicerie", superc: "Épicerie", provigo: "Épicerie",48 canadiantire: "Quincaillerie", dollarama: "Magasin à 1 $", saq: "SAQ", pharmaprix: "Pharmacie", jeancoutu: "Pharmacie", homedepot: "Rénovation", rona: "Rénovation",49};5051interface Row {52 key: string;53 icon: Lucide;54 cat: string;55 name: string;56 dist: number;57 color: string;58 lat?: number;59 lng?: number;60}6162const walkMin = (m: number) => Math.max(1, Math.round((m * 1.3) / 80));6364function RowItem({ r, active, onHover }: { r: Row; active: boolean; onHover: (k: string | null) => void }) {65 const Icon = r.icon;66 return (67 <li68 onMouseEnter={() => onHover(r.key)}69 onMouseLeave={() => onHover(null)}70 className={cn("flex items-center gap-3 rounded-[8px] px-2 py-2 transition-colors duration-150", active && "bg-surface-2")}71 >72 <span className="grid size-9 shrink-0 place-items-center rounded-[8px] bg-surface-2 text-ink-2">73 <Icon className="size-4.5" />74 </span>75 <span className="min-w-0 flex-1">76 <span className="block truncate text-[0.93rem] font-medium text-ink">{r.name}</span>77 <span className="block truncate text-xs text-ink-3">{r.cat}</span>78 </span>79 <span className="num shrink-0 text-right">80 <span className="block text-[0.9rem] font-semibold text-ink">{fmtDist(r.dist)}</span>81 {r.dist <= 1600 && <span className="block text-[0.72rem] text-ink-3">{walkMin(r.dist)} min à pied</span>}82 </span>83 </li>84 );85}8687function Gas({ lat, lng, enabled }: { lat: number; lng: number; enabled: boolean }) {88 const [sheet, setSheet] = useState(false);89 const q = useQuery({ queryKey: ["gaz", lat, lng], queryFn: () => fetchGaz(lat, lng, 60), enabled, staleTime: 6e5, retry: 0 });90 const d = q.data;91 if (!d || !d.stations?.length) return null;92 const cents = (v: number | null | undefined) => (v == null ? "—" : `${dec1(v)} ¢`);93 return (94 <Panel icon={<Fuel className="size-5" />} title="Essence à proximité" className="mt-5">95 <div className="grid grid-cols-3 gap-2.5">96 <Tile tone="good" value={cents(d.min_regulier)} label="Meilleur prix" />97 <Tile value={cents(d.mediane_regulier)} label="Médiane du secteur" />98 <Tile value={d.n} label={`Stations à moins de ${fmtDist(d.rayon_m)}`} />99 </div>100 <ul className="mt-3 divide-y divide-line">101 {d.stations.slice(0, 3).map((s, i) => (102 <li key={i} className="flex items-center justify-between gap-3 py-2.5 text-[0.92rem]">103 <span className="min-w-0">104 <span className="block truncate font-medium text-ink">105 {s.nom}106 {s.moins_chere && <span className="ml-2 rounded-[6px] bg-good-soft px-1.5 py-0.5 text-[0.68rem] font-medium text-good">la moins chère</span>}107 </span>108 <span className="text-xs text-ink-3">{fmtDist(s.dist_m)}</span>109 </span>110 <span className="num shrink-0 font-semibold text-ink">111 {cents(s.regulier)}112 <span className="ml-0.5 text-xs font-normal text-ink-3">/ L</span>113 </span>114 </li>115 ))}116 </ul>117 {d.stations.length > 3 && <MoreLink onClick={() => setSheet(true)}>Voir les {d.stations.length} stations</MoreLink>}118 <SourceLine>Prix du régulier, gazquebec.ca{d.maj ? ` · mis à jour ${d.maj}` : ""}</SourceLine>119 <Sheet open={sheet} onClose={() => setSheet(false)} title="Stations-service" size="lg">120 <ul className="divide-y divide-line">121 {d.stations.map((s, i) => (122 <li key={i} className="flex items-center justify-between gap-3 py-3 text-[0.92rem]">123 <span className="min-w-0">124 <span className="block truncate font-medium text-ink">{s.nom}</span>125 <span className="block truncate text-xs text-ink-3">126 {fmtDist(s.dist_m)}127 {s.adresse ? ` · ${s.adresse}` : ""} · super {cents(s.super)} · diesel {cents(s.diesel)}128 </span>129 </span>130 <span className="num shrink-0 font-semibold text-ink">{cents(s.regulier)}</span>131 </li>132 ))}133 </ul>134 </Sheet>135 </Panel>136 );137}138139export function Nearby({ l }: { l: Listing }) {140 const theme = useTheme();141 const [ref, inView] = useInView<HTMLDivElement>("500px");142 const [active, setActive] = useState<string | null>(null);143 const [tab, setTab] = useState("tout");144 const mapRef = useRef<MbMap | null>(null);145 const geo = l.lat != null && l.lng != null;146 const lat = l.lat ?? 0;147 const lng = l.lng ?? 0;148149 const commerces = useQuery({ queryKey: ["commerces", lat, lng], queryFn: () => fetchCommerces(lat, lng), enabled: inView && geo, staleTime: 6e5, retry: 0 });150151 const { rows, byGroup } = useMemo(() => {152 const pois: Row[] = (l.poi ?? [])153 .filter((p) => POI[p.cat])154 .map((p) => ({ key: `p-${p.cat}`, icon: POI[p.cat]!.icon, cat: POI[p.cat]!.label, name: p.name || POI[p.cat]!.label, dist: p.dist_m, color: POI[p.cat]!.color, lat: p.lat, lng: p.lng }));155 const toRow = (c: CommerceItem, transit: boolean): Row => ({156 key: `${transit ? "t" : "b"}-${c.id}`,157 icon: transit ? (c.id === "arret_bus" ? Bus : TrainFront) : Store,158 cat: BANNER_CAT[c.id] ?? c.commerce,159 name: c.nom,160 dist: c.dist_m,161 color: transit ? "#454d48" : "#245b48",162 lat: c.lat,163 lng: c.lng,164 });165 const transit = (commerces.data?.transit ?? []).filter((c) => TRANSIT_IDS.has(c.id)).map((c) => toRow(c, true));166 const banners = (commerces.data?.commerces ?? []).map((c) => toRow(c, false));167 const catOf = new Map<string, string>();168 (l.poi ?? []).forEach((p) => catOf.set(`p-${p.cat}`, p.cat));169 const byGroup: Record<string, Row[]> = {};170 for (const g of GROUPS) {171 byGroup[g.key] = [172 ...pois.filter((r) => g.cats.includes(catOf.get(r.key) ?? "")),173 ...(g.key === "transport" ? transit : []),174 ...(g.key === "courses" ? banners : []),175 ].sort((a, b) => a.dist - b.dist);176 }177 // sans doublon évident (même nom à moins de 60 m)178 const all = [...pois, ...transit, ...banners].sort((a, b) => a.dist - b.dist);179 const rows = all.filter((r, i) => !all.slice(0, i).some((o) => o.name === r.name && Math.abs(o.dist - r.dist) < 60));180 return { rows, byGroup };181 }, [l.poi, commerces.data]);182183 const shown = tab === "tout" ? rows.slice(0, 10) : (byGroup[tab] ?? []).slice(0, 12);184 const points = useMemo<FichePoint[]>(185 () => rows.filter((r) => r.lat != null && r.lng != null).slice(0, 28).map((r) => ({ key: r.key, lng: r.lng!, lat: r.lat!, label: `${r.name} · ${fmtDist(r.dist)}`, color: r.color })),186 [rows],187 );188 const tabs = [{ key: "tout", title: "Le plus proche" }, ...GROUPS.filter((g) => (byGroup[g.key]?.length ?? 0) > 0)];189190 if (!geo && !rows.length) return null;191192 return (193 <Section194 id="carte"195 eyebrow="Autour du logement"196 title="Carte et proximité"197 text={l.address ? `${l.address}${l.city && !l.address.includes(l.city) ? `, ${l.city.replace(/[()]/g, "").trim()}` : ""}` : undefined}198 >199 <div ref={ref} className="space-y-5">200 {geo && (201 <div className="relative h-[300px] overflow-hidden rounded-xl border border-line sm:h-[400px]">202 {inView ? (203 <FicheMap lng={lng} lat={lat} points={points} activeKey={active} theme={theme} onReady={(m) => (mapRef.current = m)} className="absolute inset-0" />204 ) : (205 <div className="skeleton absolute inset-0 rounded-none" />206 )}207 <div className="absolute right-3 top-3 flex flex-col overflow-hidden rounded-[10px] border border-line bg-surface">208 <button type="button" aria-label="Zoom avant" onClick={() => mapRef.current?.zoomIn()} className="grid size-10 place-items-center text-ink hover:bg-surface-2">209 <Plus className="size-4.5" />210 </button>211 <span className="h-px bg-line-2" />212 <button type="button" aria-label="Zoom arrière" onClick={() => mapRef.current?.zoomOut()} className="grid size-10 place-items-center text-ink hover:bg-surface-2">213 <Minus className="size-4.5" />214 </button>215 </div>216 <a217 href={`https://www.google.com/maps/search/?api=1&query=${lat},${lng}`}218 target="_blank"219 rel="noopener noreferrer"220 className="absolute bottom-3 right-3 inline-flex h-9 items-center gap-1.5 rounded-[8px] border border-line bg-surface px-3 text-[0.8rem] font-medium text-ink transition-colors duration-150 hover:border-ink-3"221 >222 <MapPin className="size-3.5" /> Itinéraire223 </a>224 </div>225 )}226 {rows.length > 0 && (227 <div className="card flex flex-col p-4 sm:p-5">228 <div className="no-scrollbar -mx-1 mb-2 flex gap-1.5 overflow-x-auto px-1 pb-1" role="tablist" aria-label="Catégories à proximité">229 {tabs.map((t) => (230 <button231 key={t.key}232 type="button"233 role="tab"234 aria-selected={tab === t.key}235 onClick={() => setTab(t.key)}236 className={cn(237 "h-9 shrink-0 rounded-[8px] px-3 text-[0.82rem] transition-colors duration-150",238 tab === t.key ? "bg-ink font-medium text-bg" : "bg-surface-2 text-ink-2 hover:text-ink",239 )}240 >241 {t.title}242 </button>243 ))}244 </div>245 <ul className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">246 {shown.map((r) => (247 <RowItem key={r.key} r={r} active={active === r.key} onHover={setActive} />248 ))}249 </ul>250 <SourceLine>Distances à vol d'oiseau, temps de marche estimés. OpenStreetMap et Mapbox.</SourceLine>251 </div>252 )}253 </div>254 {geo && <Gas lat={lat} lng={lng} enabled={inView} />}255 </Section>256 );257}258