SPB Git

Repository Public

ListingSections.swift 38.8 KB 760 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Listing/ListingSections.swift10// Description      : blocs de la fiche propriété — description,11//                    caractéristiques, bâtiment et terrain, vrai prix,12//                    historique du prix, financement, emplacement, quartier,13//                    risques, courtier et agence, comparables. Chaque bloc14//                    porte son espacement et disparaît quand il n'a rien à15//                    montrer.16// Module           : ImmoKa17// Repository       : https://git.spboucher.ai/immo-ka-ios-v318// Project Website  : https://www.immo-ka.com19// Created          : 2026-11-2520// Last Modified    : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Charts95import MapKit96import SwiftUI9798/// Charge une donnée à l'apparition ; rien n'est affiché si elle est absente ou en erreur.99struct LazyLoad<T: Sendable, Content: View>: View {100    let id: String101    let load: @Sendable () async throws -> T?102    @ViewBuilder let content: (T) -> Content103    @State private var value: T?104105    var body: some View {106        Group {107            if let value {108                content(value).padding(.bottom, 30).transition(.opacity)109            } else {110                Color.clear.frame(height: 1)111            }112        }113        .task(id: id) {114            guard value == nil else { return }115            let v = (try? await load()) ?? nil116            withAnimation(.easeOut(duration: 0.3)) { value = v }117        }118    }119}120121/// Liste de lignes « libellé … valeur » séparées par des filets.122struct RowList: View {123    let rows: [(String, String)]124    var body: some View {125        VStack(spacing: 0) {126            ForEach(Array(rows.enumerated()), id: \.offset) { i, r in127                KeyValueRow(label: r.0, value: r.1)128                if i < rows.count - 1 { Divider().overlay(Theme.line) }129            }130        }131    }132}133134// MARK: - 3. Description135136struct DescriptionSection: View {137    let listing: Listing138    @State private var expanded = false139140    var body: some View {141        let text = listing.description142        if !text.isEmpty {143            VStack(alignment: .leading, spacing: 12) {144                SectionHeader(title: "Description")145                Text(text).font(.subheadline).foregroundStyle(Theme.ink2).lineSpacing(3)146                    .lineLimit(expanded ? nil : 7)147                    .fixedSize(horizontal: false, vertical: true)148                if text.count > 380 {149                    Button(expanded ? "Réduire" : "Lire la suite") { withAnimation(.snappy) { expanded.toggle() } }150                        .font(.subheadline.weight(.semibold))151                }152            }153            .padding(.bottom, 30)154        }155    }156}157158// MARK: - 4. Caractéristiques159160/// Caractéristiques publiées par la source : « Libellé : valeur » en lignes, mentions simples en étiquettes.161struct FeaturesSection: View {162    let listing: Listing163    @State private var expanded = false164165    var body: some View {166        // les lignes déjà présentes dans les détails (bâtiment et terrain) ne sont pas répétées167        let known = Set(listing.details.rows.map { $0.label.lowercased() })168        let pairs: [(String, String)] = listing.features.compactMap { f in169            guard let r = f.range(of: " : ") else { return nil }170            let k = String(f[..<r.lowerBound]), v = String(f[r.upperBound...])171            return known.contains(k.lowercased()) || v.isEmpty ? nil : (k, v)172        }173        let tags = listing.features.filter { !$0.contains(" : ") && $0.count <= 48 }174        if !(pairs.isEmpty && tags.isEmpty) {175            VStack(alignment: .leading, spacing: 14) {176                SectionHeader(title: "Caractéristiques")177                if !tags.isEmpty {178                    FlowLayout(spacing: 8) {179                        ForEach(Array(Set(tags)).sorted().prefix(expanded ? 60 : 14), id: \.self) { t in180                            Text(t).font(.footnote.weight(.medium)).foregroundStyle(Theme.ink)181                                .padding(.horizontal, 11).padding(.vertical, 7)182                                .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))183                        }184                    }185                }186                if !pairs.isEmpty {187                    RowList(rows: Array(pairs.prefix(expanded ? 80 : 8)))188                }189                if pairs.count > 8 || tags.count > 14 {190                    Button(expanded ? "Réduire" : "Toutes les caractéristiques (\(pairs.count + Set(tags).count))") {191                        withAnimation(.snappy) { expanded.toggle() }192                    }193                    .font(.subheadline.weight(.semibold))194                }195            }196            .padding(.bottom, 30)197        }198    }199}200201// MARK: - 5. Bâtiment et terrain202203struct BuildingSection: View {204    let listing: Listing205    @State private var open: Set<DetailGroup> = [.batiment]206    @State private var showRooms = false207208    var body: some View {209        let groups = listing.details.grouped210        let rooms = listing.details.rooms211        if !(groups.isEmpty && rooms.isEmpty) {212            VStack(alignment: .leading, spacing: 4) {213                SectionHeader(title: "Bâtiment et terrain").padding(.bottom, 8)214                ForEach(groups, id: \.group) { g in215                    disclosure(g.group.title, count: g.rows.count, isOpen: open.contains(g.group)) {216                        withAnimation(.snappy(duration: 0.28)) { if open.contains(g.group) { open.remove(g.group) } else { open.insert(g.group) } }217                    } content: {218                        RowList(rows: g.rows.map { ($0.label, $0.value) })219                    }220                }221                if !rooms.isEmpty {222                    disclosure("Pièces", count: rooms.count, isOpen: showRooms) {223                        withAnimation(.snappy(duration: 0.28)) { showRooms.toggle() }224                    } content: {225                        VStack(spacing: 0) {226                            ForEach(Array(rooms.enumerated()), id: \.element.id) { i, r in227                                HStack(alignment: .firstTextBaseline) {228                                    VStack(alignment: .leading, spacing: 2) {229                                        Text(r.nom).font(.subheadline).foregroundStyle(Theme.ink)230                                        Text([r.niveau, r.revetement].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.ink3)231                                    }232                                    Spacer(minLength: 12)233                                    Text(r.dimensions ?? "").font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink2)234                                }235                                .padding(.vertical, 8)236                                .accessibilityElement(children: .combine)237                                if i < rooms.count - 1 { Divider().overlay(Theme.line) }238                            }239                        }240                    }241                }242            }243            .padding(.bottom, 30)244        }245    }246247    /// Repli à hauteur animée : un titre à filet, le contenu se déploie dessous.248    private func disclosure<C: View>(_ title: String, count: Int, isOpen: Bool, toggle: @escaping () -> Void, @ViewBuilder content: () -> C) -> some View {249        VStack(alignment: .leading, spacing: 0) {250            Button(action: toggle) {251                HStack {252                    Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)253                    Text("\(count)").font(.caption).num().foregroundStyle(Theme.ink3)254                    Spacer()255                    Image(systemName: "chevron.down").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)256                        .rotationEffect(.degrees(isOpen ? 180 : 0))257                }258                .padding(.vertical, 12)259                .contentShape(Rectangle())260            }261            .buttonStyle(.plain)262            .accessibilityHint(isOpen ? "Replie la section" : "Déploie la section")263            if isOpen {264                content().padding(.bottom, 8).transition(.opacity.combined(with: .move(edge: .top)))265            }266            Divider().overlay(Theme.line)267        }268        .clipped()269    }270}271272// MARK: - 6a. Vrai prix273274struct VraiPrixSection: View {275    let listing: Listing276    @Binding var external: ExternalLink?277278    var body: some View {279        if let vp = listing.vraiprix, let price = listing.plausiblePrice {280            let info = listing.verdictInfo281            VStack(alignment: .leading, spacing: 14) {282                SectionHeader(title: "Vrai prix", subtitle: "Le prix demandé, comparé à la valeur estimée de la propriété.") {283                    NavigationLink(value: Route.vraiPrixGuide) { Image(systemName: "info.circle").foregroundStyle(Theme.ink3) }284                        .accessibilityLabel("Comment la valeur est estimée")285                }286                HStack(alignment: .firstTextBaseline) {287                    VStack(alignment: .leading, spacing: 2) {288                        Text("Valeur estimée").font(.caption).foregroundStyle(Theme.ink3)289                        Text(Fmt.money(vp.value)).font(.display(28, weight: .semibold)).num().foregroundStyle(Theme.ink)290                    }291                    Spacer()292                    VerdictPill(verdict: info?.verdict, deviation: info?.deviation, large: true)293                }294                // la fourchette n'encadre pas toujours la valeur (API.md, piège 4) : pas de jauge dans ce cas295                if let low = vp.low, let high = vp.high, high > low, low <= vp.value, vp.value <= high {296                    FairValueGauge(price: price, fv: vp.value, low: low, high: high, verdict: info?.verdict)297                }298                Text(sentence(price: price, vp: vp, info: info))299                    .font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)300                let rows = roleRows(vp)301                if !rows.isEmpty {302                    VStack(alignment: .leading, spacing: 4) {303                        Text("Rôle d'évaluation foncière").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)304                        RowList(rows: rows)305                    }306                }307                if let link = ExternalLink(vp.url) {308                    Button { external = link } label: {309                        HStack(spacing: 6) {310                            Text("Voir l'estimation détaillée").font(.subheadline.weight(.semibold))311                            Image(systemName: "arrow.up.right").font(.caption.weight(.bold))312                        }313                    }314                }315                Text("Estimation statistique, à titre indicatif : elle ne remplace pas l'avis d'un évaluateur agréé ni une inspection.")316                    .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)317            }318            .padding(.bottom, 30)319        }320    }321322    private func sentence(price: Double, vp: VraiPrix, info: (verdict: Verdict, deviation: Double)?) -> String {323        // écart aberrant : l'estimation reste visible, sans jugement324        guard let info else {325            return "L'écart entre le prix demandé et cette estimation est trop grand pour en tirer un verdict : l'appariement avec le rôle d'évaluation est probablement imparfait (terrain, immeuble entier, adresse voisine)."326        }327        let gap = Fmt.money(abs(price - vp.value))328        let range = (vp.low != nil && vp.high != nil && (vp.low ?? 0) <= vp.value && vp.value <= (vp.high ?? 0)) ? " La fourchette va de \(Fmt.money(vp.low)) à \(Fmt.money(vp.high))." : ""329        switch info.verdict {330        case .sous: return "Le prix demandé est \(gap) sous la valeur estimée (\(Fmt.pct(info.deviation)))." + range331        case .sur: return "Le prix demandé dépasse la valeur estimée de \(gap) (\(Fmt.pct(info.deviation)))." + range332        case .marche: return "Le prix demandé est conforme à la valeur estimée (\(Fmt.pct(info.deviation)))." + range333        }334    }335336    private func roleRows(_ vp: VraiPrix) -> [(String, String)] {337        var rows: [(String, String)] = []338        if let v = vp.valeurRole { rows.append(("Valeur au rôle", Fmt.money(v))) }339        if let v = vp.valeurTerrain { rows.append(("Terrain", Fmt.money(v))) }340        if let v = vp.valeurBatiment { rows.append(("Bâtiment", Fmt.money(v))) }341        if let v = vp.terrainM2 { rows.append(("Superficie du terrain", "\(Fmt.decimal(v)) m²")) }342        if let v = vp.etagesM2 { rows.append(("Aire d'étages", "\(Fmt.decimal(v)) m²")) }343        return rows344    }345}346347// MARK: - 6b. Historique du prix348349struct PriceHistorySection: View {350    let listing: Listing351    @State private var draw: Double = 0352353    var body: some View {354        let pts = listing.priceHistory.filter { Listing.priceIsPlausible($0.price) && $0.ts > 0 }.sorted { $0.ts < $1.ts }355        if pts.count >= 2, let first = pts.first?.price, let last = pts.last?.price {356            let change = last - first357            VStack(alignment: .leading, spacing: 14) {358                SectionHeader(title: "Historique du prix",359                              subtitle: change == 0 ? "Prix inchangé depuis la première observation."360                              : "\(change < 0 ? "Baisse" : "Hausse") de \(Fmt.money(abs(change))) depuis le \(Fmt.date(pts.first?.ts)).")361                Chart {362                    ForEach(pts) { p in363                        LineMark(x: .value("Date", Date(timeIntervalSince1970: p.ts)), y: .value("Prix", first + ((p.price ?? first) - first) * draw))364                            .interpolationMethod(.stepEnd)365                            .foregroundStyle(Theme.brand)366                            .lineStyle(StrokeStyle(lineWidth: 2))367                        PointMark(x: .value("Date", Date(timeIntervalSince1970: p.ts)), y: .value("Prix", first + ((p.price ?? first) - first) * draw))368                            .foregroundStyle(Theme.brand).symbolSize(34)369                    }370                }371                .chartYScale(domain: .automatic(includesZero: false))372                .chartYAxis {373                    AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { v in374                        AxisGridLine().foregroundStyle(Theme.line)375                        AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.compactMoney(d)).font(.caption2).monospacedDigit() } }376                    }377                }378                .chartXAxis {379                    AxisMarks(values: .automatic(desiredCount: 3)) { _ in380                        AxisGridLine().foregroundStyle(Theme.line)381                        AxisValueLabel(format: .dateTime.day().month(.abbreviated).locale(Fmt.locale))382                    }383                }384                .frame(height: 150)385                .drawOnAppear($draw, duration: 0.8)386                .accessibilityLabel("Prix demandé de \(Fmt.money(first)) à \(Fmt.money(last))")387            }388            .padding(.bottom, 30)389        }390    }391}392393// MARK: - 6c. Financement394395struct FinancingSection: View {396    let listing: Listing397    @State private var model: FinanceModel?398399    var body: some View {400        if let price = listing.plausiblePrice, !listing.isLand {401            VStack(alignment: .leading, spacing: 16) {402                SectionHeader(title: listing.isV3 ? "Simuler un financement" : "Financement",403                              subtitle: listing.isV3 ? "Changez le prix, la mise de fonds, le taux et l'amortissement : tout est calculé sur l'appareil."404                              : "Ce que cette propriété coûterait chaque mois, et la somme à réunir pour l'acheter.") {405                    NavigationLink(value: Route.rates) { Text("Taux").font(.subheadline.weight(.semibold)) }406                }407                if let model {408                    FinanceCalculator(model: model)409                }410            }411            .padding(.bottom, 30)412            .onAppear { if model == nil { model = FinanceModel(price: price, city: listing.cleanCity) } }413        }414    }415}416417// MARK: - 7. Emplacement418419struct LocationSection: View {420    let listing: Listing421    @State private var scene: MKLookAroundScene?422    @State private var showLookAround = false423    @State private var commerces: [Commerces.Item] = []424425    static let poiLabels: [String: (String, String)] = [426        "epicerie": ("Épicerie", "cart"), "pharmacie": ("Pharmacie", "cross.case"), "ecole": ("École", "graduationcap"),427        "parc": ("Parc", "tree"), "bus": ("Arrêt de bus", "bus"), "metro": ("Métro", "tram"), "cafe": ("Café", "cup.and.saucer"),428        "restaurant": ("Restaurant", "fork.knife"), "banque": ("Banque", "building.columns"), "garderie": ("Garderie", "figure.and.child.holdinghands"),429        "hopital": ("Hôpital", "cross"), "bibliotheque": ("Bibliothèque", "books.vertical"), "gym": ("Gym", "dumbbell"),430    ]431432    var body: some View {433        if let c = listing.coordinate {434            VStack(alignment: .leading, spacing: 14) {435                SectionHeader(title: "Emplacement", subtitle: [listing.address, listing.cleanCity].filter { !$0.isEmpty }.joined(separator: ", "))436                Map(initialPosition: .camera(MapCamera(centerCoordinate: c, distance: 1600)), interactionModes: [.pan, .zoom]) {437                    Annotation(listing.displayTitle, coordinate: c, anchor: .bottom) {438                        // la maison du symbole, posée sur l'adresse439                        BrandMark(angle: BrandGeometry.ajarAngle).frame(width: 44, height: 44)440                            .shadow(color: .black.opacity(0.25), radius: 3, y: 2)441                    }442                    .annotationTitles(.hidden)443                    ForEach(commerces.filter { $0.lat != nil && $0.lng != nil }.prefix(10)) { p in444                        Marker(p.commerce, systemImage: "cart", coordinate: .init(latitude: p.lat ?? 0, longitude: p.lng ?? 0))445                            .tint(Theme.slate)446                    }447                }448                .mapStyle(.standard(emphasis: .muted, pointsOfInterest: .excludingAll))449                .frame(height: 240)450                .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))451                .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))452                .accessibilityLabel("Carte de l'emplacement de la propriété")453                HStack(spacing: 10) {454                    Button {455                        let item = MKMapItem(placemark: MKPlacemark(coordinate: c))456                        item.name = listing.displayTitle457                        item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])458                    } label: { Label("Itinéraire", systemImage: "arrow.triangle.turn.up.right.diamond") }459                    .buttonStyle(SoftButtonStyle())460                    Button {461                        let item = MKMapItem(placemark: MKPlacemark(coordinate: c))462                        item.name = listing.displayTitle463                        item.openInMaps(launchOptions: [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: c)])464                    } label: { Label("Plans", systemImage: "map") }465                    .buttonStyle(SoftButtonStyle())466                    if scene != nil {467                        Button { showLookAround = true } label: { Label("Vue de la rue", systemImage: "binoculars") }468                            .buttonStyle(SoftButtonStyle())469                    }470                }471                let near = nearby472                if !near.isEmpty {473                    VStack(spacing: 0) {474                        ForEach(Array(near.enumerated()), id: \.offset) { i, p in475                            HStack(spacing: 12) {476                                Image(systemName: p.icon).font(.system(size: 14)).foregroundStyle(Theme.ink2).frame(width: 24)477                                VStack(alignment: .leading, spacing: 1) {478                                    Text(p.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)479                                    if !p.subtitle.isEmpty { Text(p.subtitle).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1) }480                                }481                                Spacer()482                                Text(Fmt.distance(p.dist)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink2)483                            }484                            .padding(.vertical, 8)485                            .accessibilityElement(children: .combine)486                            if i < near.count - 1 { Divider().overlay(Theme.line) }487                        }488                    }489                }490            }491            .padding(.bottom, 30)492            .task(id: listing.uid) {493                scene = try? await MKLookAroundSceneRequest(coordinate: c).scene494                if let r = try? await APIClient.shared.commerces(lat: c.latitude, lng: c.longitude) {495                    withAnimation(.easeOut(duration: 0.3)) { commerces = r.commerces }496                }497            }498            .lookAroundViewer(isPresented: $showLookAround, initialScene: scene)499        }500    }501502    private struct Near { let icon: String; let title: String; let subtitle: String; let dist: Double }503504    /// À proximité : commodités de la fiche (la plus proche de chaque catégorie), puis les commerces.505    private var nearby: [Near] {506        var best: [String: Poi] = [:]507        for p in listing.poi where p.distM > 0 { if best[p.cat].map({ p.distM < $0.distM }) ?? true { best[p.cat] = p } }508        var out = best.values.map { Near(icon: Self.poiLabels[$0.cat]?.1 ?? "mappin", title: Self.poiLabels[$0.cat]?.0 ?? $0.cat.capitalized, subtitle: $0.name, dist: $0.distM) }509        var seen = Set<String>()510        for c in commerces where seen.insert(c.commerce).inserted {511            out.append(Near(icon: "cart", title: c.commerce, subtitle: c.nom == c.commerce ? "" : c.nom, dist: c.distM))512        }513        return Array(out.sorted { $0.dist < $1.dist }.prefix(8))514    }515}516517// MARK: - 8. Quartier518519struct NeighbourhoodSection: View {520    let listing: Listing521    @State private var draw: Double = 0522523    var body: some View {524        if let q = listing.quartier {525            VStack(alignment: .leading, spacing: 16) {526                SectionHeader(title: "Quartier", subtitle: "Portrait du voisinage immédiat, d'après le recensement et les données publiques.")527                if q.hasDemographics {528                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 140), spacing: 16, alignment: .topLeading)], alignment: .leading, spacing: 16) {529                        if let v = q.revenuMedian { StatTile(value: Fmt.compactMoney(v), label: "Revenu médian des ménages") }530                        if let v = q.ageMedian { StatTile(value: "\(Fmt.decimal(v)) ans", label: "Âge médian") }531                        if let v = q.pctLocataires { StatTile(value: "\(Fmt.int(100 - v)) %", label: "Ménages propriétaires") }532                        if let v = q.population { StatTile(value: Fmt.int(v), label: "Habitants du secteur") }533                        if let v = q.pctUniv { StatTile(value: "\(Fmt.int(v)) %", label: "Diplôme universitaire") }534                        if let v = q.pctFrancais { StatTile(value: "\(Fmt.int(v)) %", label: "Français à la maison") }535                    }536                }537                if !q.proximite.isEmpty {538                    VStack(alignment: .leading, spacing: 10) {539                        Text("Proximité des services").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)540                        ForEach(q.proximite) { p in541                            HStack(spacing: 12) {542                                Text(p.label).font(.footnote).foregroundStyle(Theme.ink2).frame(width: 132, alignment: .leading)543                                GeometryReader { geo in544                                    ZStack(alignment: .leading) {545                                        Capsule().fill(Theme.surface3)546                                        Capsule().fill(Theme.brand).frame(width: max(3, geo.size.width * p.value * draw))547                                    }548                                }549                                .frame(height: 6)550                                Text(Fmt.int(p.value * 100)).font(.footnote.weight(.semibold)).num().foregroundStyle(Theme.ink).frame(width: 28, alignment: .trailing)551                            }552                            .accessibilityElement(children: .ignore)553                            .accessibilityLabel("\(p.label) : \(Int(p.value * 100)) sur 100")554                        }555                        Text("Indice de proximité de Statistique Canada, de 0 (éloigné) à 100 (très proche).")556                            .font(.caption).foregroundStyle(Theme.ink3)557                    }558                    .drawOnAppear($draw, duration: 0.8)559                }560                let rows = contextRows(q)561                if !rows.isEmpty { RowList(rows: rows) }562            }563            .padding(.bottom, 30)564        }565    }566567    private func contextRows(_ q: Quartier) -> [(String, String)] {568        var rows: [(String, String)] = []569        let quintile: (Int) -> String = { ["", "Très favorisé", "Favorisé", "Moyen", "Défavorisé", "Très défavorisé"][min(5, max(0, $0))] }570        if let m = q.quintileMateriel, (1...5).contains(m) { rows.append(("Défavorisation matérielle", quintile(m))) }571        if let s = q.quintileSocial, (1...5).contains(s) { rows.append(("Défavorisation sociale", quintile(s))) }572        if let c = q.chaleurClasse {573            let label = c >= 8 ? "Îlot de chaleur" : c >= 6 ? "Plus chaud que la moyenne" : c >= 4 ? "Dans la moyenne" : "Îlot de fraîcheur"574            rows.append(("Chaleur en été", label))575        }576        if let t = q.crimeTexte { rows.append(("Sécurité", t)) }577        return rows578    }579}580581// MARK: - 9. Risques et environnement582583struct RisksSection: View {584    let listing: Listing585586    private struct Env: Sendable {587        var flood: Inondation?588        var air: AirNearby?589        var gaz: GazNearby?590        var isEmpty: Bool { flood == nil && (air?.mesures.isEmpty ?? true) && (gaz?.stations.isEmpty ?? true) }591    }592593    var body: some View {594        if let c = listing.coordinate {595            LazyLoad(id: "env-\(listing.uid)") { () async throws -> Env? in596                async let f = try? APIClient.shared.inondation(lat: c.latitude, lng: c.longitude)597                async let a = try? APIClient.shared.air(lat: c.latitude, lng: c.longitude)598                async let g = try? APIClient.shared.gaz(lat: c.latitude, lng: c.longitude)599                let env = await Env(flood: f, air: a, gaz: g)600                return env.isEmpty ? nil : env601            } content: { env in602                VStack(alignment: .leading, spacing: 14) {603                    SectionHeader(title: "Risques et environnement", subtitle: "Données publiques à l'adresse de la propriété.")604                    VStack(spacing: 0) {605                        if let f = env.flood {606                            riskRow(icon: f.enZone ? "exclamationmark.triangle" : "water.waves", tint: f.enZone ? Theme.bad : Theme.ink2,607                                    title: "Inondation", text: f.texte, source: "Base de données des zones inondables du Québec")608                            Divider().overlay(Theme.line)609                        }610                        if let a = env.air, let pm = a.mesures.first(where: { $0.polluant == "PM2.5" }) ?? a.mesures.first {611                            let over = pm.ref.map { pm.moyenne > $0 } ?? false612                            riskRow(icon: "aqi.medium", tint: Theme.ink2, title: "Qualité de l'air",613                                    text: "\(pm.polluant) : \(Fmt.decimal(pm.moyenne)) \(pm.unite) en moyenne\(pm.annee.map { " (\($0))" } ?? "")\(pm.ref.map { ", \(over ? "au-dessus" : "sous") le repère de \(Fmt.decimal($0)) (\(pm.refNom ?? "référence"))" } ?? "").",614                                    source: a.station.map { "Station \($0)\(a.distanceKm.map { ", à \(Fmt.decimal($0)) km" } ?? "")" })615                            Divider().overlay(Theme.line)616                        }617                        if let g = env.gaz, let s = g.stations.first, let prix = s.regulier ?? g.medianeRegulier {618                            riskRow(icon: "fuelpump", tint: Theme.ink2, title: "Essence à proximité",619                                    text: "\(s.nom), à \(Fmt.distance(s.distM)) : \(Fmt.decimal(prix)) ¢ le litre d'ordinaire.",620                                    source: g.stations.count > 1 ? "\(g.stations.count) stations dans un rayon de 5 km" : nil)621                            Divider().overlay(Theme.line)622                        }623                    }624                }625            }626        }627    }628629    private func riskRow(icon: String, tint: Color, title: String, text: String, source: String?) -> some View {630        HStack(alignment: .top, spacing: 12) {631            Image(systemName: icon).font(.system(size: 15)).foregroundStyle(tint).frame(width: 24).padding(.top, 2)632            VStack(alignment: .leading, spacing: 3) {633                Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)634                Text(text).font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)635                if let source { Text(source).font(.caption).foregroundStyle(Theme.ink3) }636            }637            Spacer(minLength: 0)638        }639        .padding(.vertical, 11)640        .accessibilityElement(children: .combine)641    }642}643644// MARK: - Courtier et agence645646struct BrokerSection: View {647    let listing: Listing648    @Binding var external: ExternalLink?649    @Environment(AppModel.self) private var app650    @Environment(Account.self) private var account651    /// Courtier de cette inscription d'après les comptes d'Immo-Ka, s'il y en a un ; demandé sans bloquer l'affichage.652    @State private var info: ListingBrokerInfo?653654    private var verified: ListingBrokerInfo.Broker? { info?.broker.flatMap { $0.verified ? $0 : nil } }655656    var body: some View {657        let l = listing658        let source = app.sourceName(l.source)659        VStack(alignment: .leading, spacing: 12) {660            SectionHeader(title: "Courtier et agence")661            HStack(alignment: .top, spacing: 14) {662                if let v = verified { BrokerLogo(image: v.logo, name: v.name.isEmpty ? (l.brokerName ?? source) : v.name) }663                VStack(alignment: .leading, spacing: 4) {664                    if let v = verified, !v.name.isEmpty {665                        Text(verbatim: v.name).font(.editorial(20)).foregroundStyle(Theme.ink)666                    } else if let b = l.brokerName, b.caseInsensitiveCompare(source) != .orderedSame {667                        Text(b).font(.editorial(20)).foregroundStyle(Theme.ink)668                    }669                    if verified != nil { VerifiedBadge() }670                    if let a = verified?.agency ?? l.agency { Text(verbatim: a).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink2) }671                    Text("Inscription publiée par \(source)").font(.footnote).foregroundStyle(Theme.ink3)672                }673            }674            if let info { ListingBrokerBlock(listing: l, info: info) }675            FlowLayout(spacing: 10) {676                // page du courtier (fiche publiée, autres propriétés) quand Immo-Ka le connaît dans son annuaire677                if let b = info?.broker, !b.brokerID.isEmpty {678                    NavigationLink(value: Route.broker(id: b.brokerID, name: b.name)) {679                        Label(b.verified ? "Sa fiche" : "Ce courtier", systemImage: "person.text.rectangle")680                    }681                    .buttonStyle(SoftButtonStyle())682                    .accessibilityIdentifier("listing.broker.page")683                }684                // v3 : le téléphone du courtier reste chez la source (contrat de l'API), l'app y renvoie685                if !l.isV3, let tel = l.phoneURL, let phone = l.brokerPhone {686                    Link(destination: tel) { Label(phone, systemImage: "phone") }687                        .buttonStyle(PrimaryButtonStyle())688                        .accessibilityLabel("Appeler le \(phone)")689                }690                if let link = ExternalLink(l.url) {691                    Button { external = link } label: { Label("Inscription originale", systemImage: "safari") }692                        .buttonStyle(SoftButtonStyle())693                }694                NavigationLink(value: Route.agency(app.franchiseName(for: l.source))) {695                    Label("Ses propriétés", systemImage: "person.2")696                }697                .buttonStyle(SoftButtonStyle())698            }699            if !l.duplicates.isEmpty, !l.isV3 {700                VStack(alignment: .leading, spacing: 0) {701                    Text("Aussi publiée sur").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3).padding(.bottom, 4)702                    ForEach(l.duplicates.prefix(6)) { d in703                        Button { if let link = ExternalLink(d.url) { external = link } } label: {704                            HStack {705                                VStack(alignment: .leading, spacing: 1) {706                                    Text(app.sourceName(d.source)).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)707                                    if let b = d.brokerName { Text(b).font(.caption).foregroundStyle(Theme.ink3) }708                                }709                                Spacer()710                                Image(systemName: "arrow.up.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)711                            }712                            .padding(.vertical, 9)713                            .contentShape(Rectangle())714                        }715                        .buttonStyle(.plain)716                        .disabled(ExternalLink(d.url) == nil)717                        Divider().overlay(Theme.line)718                    }719                }720            }721            Text("Immo-Ka agrège les inscriptions et renvoie toujours vers la source. Vérifiez les détails auprès du courtier ou du vendeur avant de vous engager.")722                .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)723        }724        // rien ne change si l'appel échoue ou si la propriété n'a pas de courtier vérifié725        .task(id: listing.uid) { info = await account.messaging.listingBroker(uid: listing.uid) }726    }727}728729// MARK: - Comparables730731struct ComparablesSection: View {732    let listing: Listing733734    var body: some View {735        if listing.plausiblePrice != nil, !listing.city.isEmpty {736            let l = listing737            LazyLoad(id: "comp-\(l.uid)") { () async throws -> [Listing]? in738                let c = try await APIClient.shared.comparables(for: l)739                return c.count >= 2 ? c : nil740            } content: { comps in741                VStack(alignment: .leading, spacing: 14) {742                    SectionHeader(title: "Propriétés comparables",743                                  subtitle: "\(l.kind.isEmpty ? "Propriétés" : l.kind) à \(l.cleanCity), à un prix voisin.")744                    ScrollView(.horizontal, showsIndicators: false) {745                        LazyHStack(alignment: .top, spacing: 14) {746                            ForEach(Array(comps.enumerated()), id: \.element.id) { i, c in747                                ListingLink(listing: c).frame(width: 270).staggered(i)748                            }749                        }750                        .scrollTargetLayout()751                        .padding(.horizontal, 20)752                    }753                    .scrollTargetBehavior(.viewAligned)754                    .padding(.horizontal, -20)755                }756            }757        }758    }759}760
Files main
Menu

Theme