SPB Git

Repository Public

ListingSections.swift 29.7 KB 552 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Features/Listing/ListingSections.swift10// Description      : blocs d'analyse de la fiche — juste valeur, coût réel,11//                    historique, carte, scores, quartier, immeuble, registre12//                    des loyers, tribunal du logement, environnement. Chargés à13//                    l'apparition.14// Module           : LouKa15// Repository       : https://git.spboucher.ai/lou-ka-ios-v316// Project Website  : https://www.lou-ka.com17// Created          : 2026-11-2518// Last Modified    : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Charts93import MapKit94import SwiftUI9596/// Charge une donnée à l'apparition ; rien n'est affiché si elle est absente ou en erreur.97struct LazyLoad<T: Sendable, Content: View>: View {98    let id: String99    let load: @Sendable () async throws -> T100    @ViewBuilder let content: (T) -> Content101    @State private var value: T?102103    var body: some View {104        Group {105            if let value {106                content(value).padding(.bottom, 30).transition(.opacity)107            } else {108                Color.clear.frame(height: 1)109            }110        }111        .task(id: id) {112            guard value == nil else { return }113            let v = try? await load()114            withAnimation(.easeOut(duration: 0.3)) { value = v }115        }116    }117}118119/// Pastille de statut d'une donnée (observée, calculée, estimée…).120struct StatusTag: View {121    let status: String122    var body: some View {123        let (label, color): (String, Color) = switch status {124        case "observed": ("observé", Theme.brand)125        case "calculated": ("calculé", Theme.ink2)126        case "estimated": ("estimé", Theme.high)127        case "inferred": ("déduit", Theme.ink3)128        case "included": ("inclus", Theme.good)129        default: ("inconnu", Theme.ink3)130        }131        Text(label).font(.system(size: 10, weight: .semibold)).foregroundStyle(color)132            .padding(.horizontal, 6).padding(.vertical, 2.5).background(color.opacity(0.13), in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))133    }134}135136// MARK: - 6c. Historique137138struct HistorySection: View {139    let listing: Listing140    var body: some View {141        let uid = listing.uid142        LazyLoad(id: "hi-\(uid)") { try await APIClient.shared.historique(uid) } content: { h in143            let prices = h.timeline.filter { $0.type == "prix" && Listing.priceIsPlausible($0.prix) }.sorted { $0.ts < $1.ts }144            if h.joursEnLigne != nil || !prices.isEmpty {145                VStack(alignment: .leading, spacing: 14) {146                    SectionHeader(eyebrow: "Analyse", title: "Historique de l'annonce")147                    VStack(alignment: .leading, spacing: 14) {148                        HStack(spacing: 18) {149                            if let j = h.joursEnLigne { mini("\(Fmt.int(j)) j", "en ligne") }150                            if let m = h.modifications { mini(Fmt.int(m), m > 1 ? "modifications" : "modification") }151                            if let v = h.variation, abs(v) >= 0.005, abs(v) < 0.6 {152                                mini(Fmt.pct(v), "depuis la mise en ligne", color: v < 0 ? Theme.good : Theme.high)153                            }154                        }155                        if prices.count >= 2 {156                            Chart(prices) { e in157                                LineMark(x: .value("Date", Date(timeIntervalSince1970: e.ts)), y: .value("Loyer", e.prix ?? 0))158                                    .interpolationMethod(.stepEnd).foregroundStyle(Theme.brand)159                                PointMark(x: .value("Date", Date(timeIntervalSince1970: e.ts)), y: .value("Loyer", e.prix ?? 0))160                                    .foregroundStyle(Theme.brand)161                            }162                            .chartYScale(domain: .automatic(includesZero: false))163                            .frame(height: 130)164                            .accessibilityLabel("Évolution du loyer affiché")165                        }166                        ForEach(h.timeline.prefix(5)) { e in167                            HStack(alignment: .firstTextBaseline) {168                                Circle().fill(Theme.brand).frame(width: 6, height: 6)169                                Text(eventLabel(e)).font(.footnote).foregroundStyle(Theme.ink2)170                                Spacer()171                                Text(Fmt.ago(e.ts)).font(.caption).foregroundStyle(Theme.ink3)172                            }173                        }174                        Text("Observations directes de Lou-Ka à chaque synchronisation de la source.").font(.caption).foregroundStyle(Theme.ink3)175                    }176                    .cardStyle()177                }178            }179        }180    }181182    private func mini(_ value: String, _ label: String, color: Color = Theme.ink) -> some View {183        VStack(alignment: .leading, spacing: 2) {184            Text(value).font(.headline).num().foregroundStyle(color)185            Text(label).font(.caption2).foregroundStyle(Theme.ink3)186        }187    }188189    private func eventLabel(_ e: Historique.Event) -> String {190        switch e.type {191        case "prix":192            if let a = e.prixAvant, let p = e.prix { return "Loyer : \(Fmt.money(a)) → \(Fmt.money(p))" }193            return "Loyer modifié"194        case "creation", "premiere_observation": return "Première observation"195        case "texte", "description": return "Description modifiée"196        case "photos", "images": return "Photos modifiées"197        case "disponibilite": return "Disponibilité modifiée"198        case "retrait": return "Annonce retirée"199        case "retour": return "Annonce remise en ligne"200        default: return e.type.replacingOccurrences(of: "_", with: " ").capitalized201        }202    }203}204205// MARK: - 7. Carte et à proximité206207struct LocationSection: View {208    let listing: Listing209    @State private var scene: MKLookAroundScene?210    @State private var showLookAround = false211212    static let poiLabels: [String: (String, String)] = [213        "epicerie": ("Épicerie", "cart"), "pharmacie": ("Pharmacie", "cross.case"), "ecole": ("École", "graduationcap"),214        "parc": ("Parc", "tree"), "bus": ("Arrêt de bus", "bus"), "metro": ("Métro", "tram"), "cafe": ("Café", "cup.and.saucer"),215        "restaurant": ("Restaurant", "fork.knife"), "banque": ("Banque", "building.columns"), "garderie": ("Garderie", "figure.and.child.holdinghands"),216        "hopital": ("Hôpital", "cross"), "bibliotheque": ("Bibliothèque", "books.vertical"), "gym": ("Gym", "dumbbell"),217    ]218219    var body: some View {220        if let c = listing.coordinate {221            VStack(alignment: .leading, spacing: 14) {222                SectionHeader(title: "Emplacement", subtitle: listing.address.isEmpty ? listing.place : listing.address)223                Map(initialPosition: .camera(MapCamera(centerCoordinate: c, distance: 1400)), interactionModes: [.pan, .zoom]) {224                    Annotation(listing.displayTitle, coordinate: c) {225                        Image(systemName: "house.fill").font(.system(size: 14, weight: .bold)).foregroundStyle(Theme.brandInk)226                            .frame(width: 34, height: 34).background(Theme.brand, in: Circle())227                            .overlay(Circle().strokeBorder(Theme.heritageOrange, lineWidth: 2.5)).shadow(color: .black.opacity(0.2), radius: 3, y: 1)228                    }229                    .annotationTitles(.hidden)230                    ForEach(listing.poi.filter { $0.lat != nil && $0.lng != nil }.prefix(14)) { p in231                        Marker(p.name, systemImage: Self.poiLabels[p.cat]?.1 ?? "mappin",232                               coordinate: .init(latitude: p.lat ?? 0, longitude: p.lng ?? 0))233                            .tint(Theme.forest)234                    }235                }236                .mapStyle(.standard(emphasis: .muted, pointsOfInterest: .excludingAll))237                .frame(height: 240)238                .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))239                .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))240                .accessibilityLabel("Carte de l'emplacement du logement")241242                HStack(spacing: 10) {243                    Button {244                        let item = MKMapItem(placemark: MKPlacemark(coordinate: c))245                        item.name = listing.displayTitle246                        item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit])247                    } label: { Label("Itinéraire", systemImage: "arrow.triangle.turn.up.right.diamond") }248                    .buttonStyle(SoftButtonStyle())249                    if scene != nil {250                        Button { showLookAround = true } label: { Label("Vue de la rue", systemImage: "binoculars") }251                            .buttonStyle(SoftButtonStyle())252                    }253                }254255                let pois = nearest(listing.poi)256                if !pois.isEmpty {257                    VStack(spacing: 0) {258                        ForEach(Array(pois.enumerated()), id: \.element.id) { i, p in259                            HStack(spacing: 12) {260                                Image(systemName: Self.poiLabels[p.cat]?.1 ?? "mappin").font(.system(size: 14)).foregroundStyle(Theme.ink2)261                                    .frame(width: 32, height: 32).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 10, style: .continuous))262                                VStack(alignment: .leading, spacing: 1) {263                                    Text(Self.poiLabels[p.cat]?.0 ?? p.cat.capitalized).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)264                                    if !p.name.isEmpty { Text(p.name).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1) }265                                }266                                Spacer()267                                Text(Fmt.distance(p.distM)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink2)268                            }269                            .padding(.vertical, 8)270                            .accessibilityElement(children: .combine)271                            if i < pois.count - 1 { Divider().overlay(Theme.line) }272                        }273                    }274                    .cardStyle(padding: 14)275                }276            }277            .task(id: listing.uid) {278                scene = try? await MKLookAroundSceneRequest(coordinate: c).scene279            }280            .lookAroundViewer(isPresented: $showLookAround, initialScene: scene)281        }282    }283284    /// Le plus proche de chaque catégorie, par distance.285    private func nearest(_ pois: [Poi]) -> [Poi] {286        var best: [String: Poi] = [:]287        for p in pois where p.distM > 0 { if best[p.cat].map({ p.distM < $0.distM }) ?? true { best[p.cat] = p } }288        return Array(best.values.sorted { $0.distM < $1.distM }.prefix(8))289    }290}291292// MARK: - 8. Scores de quartier293294struct ScoresSection: View {295    let listing: Listing296    @Environment(AppModel.self) private var app297298    var body: some View {299        let s = listing.scores300        if !s.isEmpty {301            let personal = s.weighted(app.scoreWeights) ?? s.global302            VStack(alignment: .leading, spacing: 14) {303                SectionHeader(eyebrow: "Quartier", title: "Scores de quartier") {304                    NavigationLink(value: Route.scoresGuide) { Image(systemName: "slider.horizontal.3").foregroundStyle(Theme.ink3) }305                        .accessibilityLabel("Régler les pondérations des scores")306                }307                VStack(spacing: 18) {308                    HStack(spacing: 16) {309                        ScoreRing(value: personal, size: 84, lineWidth: 7)310                        VStack(alignment: .leading, spacing: 3) {311                            Text(ScoreSet.label(personal) ?? "Score").font(.title3.weight(.semibold)).foregroundStyle(Theme.ink)312                            Text(app.scoreWeights == ScoreSet.defaultWeights ? "Score global sur 100" : "Score global selon vos pondérations")313                                .font(.footnote).foregroundStyle(Theme.ink3)314                        }315                        Spacer()316                    }317                    ScoreRadar(scores: s, size: 230)318                    ScoreBars(scores: s)319                    if let d = listing.scoreDetails {320                        let bits = [d.metroM.map { "Métro à \(Fmt.distance($0))" }, d.busStopM.map { "Arrêt de bus à \(Fmt.distance($0))" },321                                    d.bikeKm.map { String(format: "%.1f km de voies cyclables à moins de 1 km", $0).replacingOccurrences(of: ".", with: ",") }].compactMap { $0 }322                        if !bits.isEmpty {323                            Text(bits.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .leading)324                        }325                    }326                }327                .cardStyle()328            }329        }330    }331}332333// MARK: - 9. Quartier, immeuble, dossiers publics334335/// Le lieu de l'annonce : lien vers le portrait du quartier (loyers, scores, services), et l'îlot de chaleur336/// quand la donnée existe. Les blocs de revenu, de population et de criminalité de la V2 sont retirés, comme sur le site.337struct NeighbourhoodSection: View {338    let listing: Listing339    var body: some View {340        let city = listing.cleanCity341        if !city.isEmpty {342            VStack(alignment: .leading, spacing: 12) {343                SectionHeader(eyebrow: "Quartier", title: "Autour de ce logement")344                let sector = Fmt.cleanCity(listing.sector)345                let hasSector = !sector.isEmpty && sector != city346                NavigationLink(value: hasSector347                               ? Route.neighborhood(slug: Fmt.slug(sector), city: Fmt.slug(city), name: sector)348                               : Route.neighborhood(slug: Fmt.slug(city), city: nil, name: city)) {349                    HStack(spacing: 12) {350                        Image(systemName: "map").foregroundStyle(Theme.brand).frame(width: 28)351                        VStack(alignment: .leading, spacing: 2) {352                            Text("Portrait de \(hasSector ? sector : city)").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)353                            Text("Loyers affichés, scores, services à distance de marche, transport").font(.caption).foregroundStyle(Theme.ink3)354                        }355                        Spacer()356                        Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)357                    }358                    .cardStyle(padding: 14)359                }360                .buttonStyle(.plain)361                if let h = listing.quartier?.chaleurClasse {362                    Label(h >= 7 ? "Îlot de chaleur marqué en été" : h <= 3 ? "Secteur plutôt frais en été" : "Température estivale dans la moyenne",363                          systemImage: "thermometer.sun").font(.footnote).foregroundStyle(Theme.ink2)364                }365            }366        }367    }368}369370struct BuildingSection: View {371    let listing: Listing372    var body: some View {373        if let b = listing.immeuble, (b.annoncesTotal ?? 0) > 1 {374            VStack(alignment: .leading, spacing: 14) {375                SectionHeader(eyebrow: "Immeuble", title: "Passeport de l'immeuble", subtitle: "Ce que Lou-Ka a observé à cette adresse.")376                VStack(spacing: 0) {377                    if let n = b.annoncesActives { KeyValueRow(label: "Logements à louer en ce moment", value: Fmt.int(n)) ; Divider().overlay(Theme.line) }378                    if let n = b.annonces12m { KeyValueRow(label: "Annonces sur 12 mois", value: Fmt.int(n)); Divider().overlay(Theme.line) }379                    if let n = b.unitesEstimees, n > 0 { KeyValueRow(label: "Logements estimés", value: Fmt.int(n)); Divider().overlay(Theme.line) }380                    if let m = b.loyerMedian { KeyValueRow(label: "Loyer médian observé", value: Fmt.money(m)); Divider().overlay(Theme.line) }381                    if let v = b.variation12m, abs(v) < 0.6 {382                        KeyValueRow(label: "Loyers sur 12 mois", value: Fmt.pct(v), valueColor: v > 0.03 ? Theme.high : v < -0.03 ? Theme.good : Theme.ink)383                        Divider().overlay(Theme.line)384                    }385                    if let r = b.rotationClasse { KeyValueRow(label: "Rotation des logements", value: r.capitalized) ; Divider().overlay(Theme.line) }386                    if let p = b.premiereObservation { KeyValueRow(label: "Suivi depuis", value: Fmt.date(p)) }387                }388                .cardStyle(padding: 14)389                let others = b.unitesActives.filter { $0.uid != listing.uid }.prefix(6)390                if !others.isEmpty {391                    Text("Autres logements à louer dans l'immeuble").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)392                    FlowLayout(spacing: 8) {393                        ForEach(Array(others)) { u in394                            NavigationLink(value: Route.listing(u.uid)) {395                                Text("\(u.unitType ?? "Logement") · \(u.price.map { Fmt.money($0) } ?? "prix sur demande")")396                                    .font(.footnote.weight(.medium)).num().foregroundStyle(Theme.ink)397                                    .padding(.horizontal, 12).padding(.vertical, 8).background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))398                            }399                            .buttonStyle(.plain)400                        }401                    }402                }403            }404        }405    }406}407408struct RentRegistrySection: View {409    let listing: Listing410    var body: some View {411        if let lat = listing.lat, let lng = listing.lng, listing.coordinate != nil {412            LazyLoad(id: "rdl-\(listing.uid)") { try await APIClient.shared.rdl(lat: lat, lng: lng) } content: { r in413                if r.n > 0 {414                    VStack(alignment: .leading, spacing: 14) {415                        SectionHeader(eyebrow: "Dossier public", title: "Registre des loyers",416                                      subtitle: "\(Fmt.plural(r.n, "loyer déclaré", "loyers déclarés")) par des locataires à moins de \(r.radiusM) m.")417                        VStack(spacing: 0) {418                            if let m = r.median { KeyValueRow(label: "Loyer médian déclaré", value: Fmt.money(m)); Divider().overlay(Theme.line) }419                            if let m = r.medianRecent { KeyValueRow(label: "Médiane des déclarations récentes", value: Fmt.money(m)); Divider().overlay(Theme.line) }420                            ForEach(Array(r.items.prefix(5))) { i in421                                HStack {422                                    VStack(alignment: .leading, spacing: 1) {423                                        Text(i.address).font(.footnote).foregroundStyle(Theme.ink).lineLimit(1)424                                        Text([i.rooms.map { "\(Fmt.int($0)) pièces" }, i.year.map { String($0) }, Fmt.distance(i.distM)].compactMap { $0 }.joined(separator: " · "))425                                            .font(.caption2).foregroundStyle(Theme.ink3)426                                    }427                                    Spacer()428                                    Text(Fmt.money(i.price)).font(.footnote.weight(.semibold)).num().foregroundStyle(Theme.ink)429                                }430                                .padding(.vertical, 7)431                                .accessibilityElement(children: .combine)432                            }433                        }434                        .cardStyle(padding: 14)435                        Text("Source : registre-des-loyers.ca, déclarations volontaires de locataires.").font(.caption).foregroundStyle(Theme.ink3)436                    }437                }438            }439        }440    }441}442443struct TribunalSection: View {444    let listing: Listing445    @State private var external: ExternalLink?446    var body: some View {447        if listing.address.count > 6 {448            let address = listing.address, city: String? = listing.city.isEmpty ? nil : listing.city449            LazyLoad(id: "tal-\(listing.uid)") { try await APIClient.shared.tal(address: address, city: city) } content: { t in450                if t.status == "ok" {451                    VStack(alignment: .leading, spacing: 14) {452                        SectionHeader(eyebrow: "Dossier public", title: "Tribunal administratif du logement")453                        VStack(alignment: .leading, spacing: 10) {454                            if (t.n ?? 0) == 0 {455                                Label("Aucune décision publiée trouvée à cette adresse.", systemImage: "checkmark.seal").font(.subheadline).foregroundStyle(Theme.good)456                            } else {457                                Text(Fmt.plural(t.n ?? 0, "décision publiée à cette adresse", "décisions publiées à cette adresse"))458                                    .font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)459                                if let e = t.eviction, e > 0 {460                                    Label("\(e) concernant une éviction ou une reprise", systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.high)461                                }462                                ForEach(Array(t.decisions.prefix(4))) { d in463                                    Button { external = ExternalLink(d.url) } label: {464                                        HStack {465                                            VStack(alignment: .leading, spacing: 1) {466                                                Text(d.citation ?? "Décision").font(.footnote).foregroundStyle(Theme.ink).lineLimit(1)467                                                Text([d.date, d.demandeur.map { "demande du \($0)" }, d.verdict].compactMap { $0 }.joined(separator: " · "))468                                                    .font(.caption2).foregroundStyle(Theme.ink3)469                                            }470                                            Spacer()471                                            Image(systemName: "arrow.up.right").font(.caption).foregroundStyle(Theme.ink3)472                                        }473                                    }474                                    .buttonStyle(.plain)475                                }476                            }477                            Text("Source : décisions publiées par SOQUIJ. Une décision n'indique pas qui avait raison ; lisez-la avant de conclure.")478                                .font(.caption).foregroundStyle(Theme.ink3)479                        }480                        .frame(maxWidth: .infinity, alignment: .leading)481                        .cardStyle()482                    }483                    .safariSheet($external)484                }485            }486        }487    }488}489490struct EnvironmentSection: View {491    let listing: Listing492493    struct Env: Sendable {494        var inondation: Inondation?495        var air: AirNearby?496    }497498    var body: some View {499        if let lat = listing.lat, let lng = listing.lng, listing.coordinate != nil {500            let hiver = listing.hiver501            LazyLoad(id: "env-\(listing.uid)") {502                async let i = try? APIClient.shared.inondation(lat: lat, lng: lng)503                async let a = try? APIClient.shared.air(lat: lat, lng: lng)504                return await Env(inondation: i, air: a)505            } content: { env in506                let flood = env.inondation.flatMap { $0.couvert ? $0 : nil }507                let air = env.air.flatMap { $0.mesures.isEmpty ? nil : $0 }508                if flood != nil || air != nil || hiver != nil {509                    VStack(alignment: .leading, spacing: 14) {510                        SectionHeader(eyebrow: "Dossier public", title: "Environnement")511                        VStack(alignment: .leading, spacing: 14) {512                            if let f = flood {513                                let (text, color, icon): (String, Color, String) = switch f.statut {514                                case "en_zone": ("Adresse située en zone inondable cartographiée", Theme.bad, "water.waves")515                                case "a_proximite": ("Zone inondable cartographiée à proximité", Theme.high, "water.waves")516                                default: ("Hors des zones inondables cartographiées", Theme.good, "checkmark.seal")517                                }518                                Label(text, systemImage: icon).font(.subheadline.weight(.medium)).foregroundStyle(color)519                            }520                            if let a = air {521                                VStack(alignment: .leading, spacing: 6) {522                                    Text("Qualité de l'air\(a.station.map { " · station \($0)" } ?? "")\(a.distanceKm.map { String(format: " (%.0f km)", $0) } ?? "")")523                                        .font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)524                                    ForEach(a.mesures.prefix(4)) { m in525                                        KeyValueRow(label: m.polluant.uppercased(),526                                                    value: String(format: "%.1f %@", m.moyenne, m.unite).replacingOccurrences(of: ".", with: ","),527                                                    valueColor: m.ref.map { m.moyenne > $0 ? Theme.high : Theme.good } ?? Theme.ink)528                                    }529                                }530                            }531                            if let h = hiver {532                                HStack(spacing: 14) {533                                    ScoreRing(value: h.score, size: 54)534                                    VStack(alignment: .leading, spacing: 2) {535                                        Text("Vie quotidienne en hiver").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)536                                        Text(h.detail.prefix(3).map { d in d.distanceM.map { "\(d.critere) à \(Fmt.distance($0))" } ?? d.critere }.joined(separator: " · "))537                                            .font(.caption).foregroundStyle(Theme.ink3)538                                    }539                                }540                            }541                            Text("Sources : zones inondables du gouvernement du Québec, réseau de surveillance de la qualité de l'air.")542                                .font(.caption).foregroundStyle(Theme.ink3)543                        }544                        .frame(maxWidth: .infinity, alignment: .leading)545                        .cardStyle()546                    }547                }548            }549        }550    }551}552
Files main
Menu

Theme