SPB Git

Repository Public

ListingView.swift 31.0 KB 634 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/ListingView.swift10// Description      : fiche logement — galerie, prix et verdict, description,11//                    inclusions, détails, analyses, carte, scores de quartier,12//                    quartier, gestionnaire. L'ordre est celui du site.13// Module           : LouKa14// Repository       : https://git.spboucher.ai/lou-ka-ios-v315// Project Website  : https://www.lou-ka.com16// Created          : 2026-11-2517// Last Modified    : 2026-11-3018//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293@MainActor94@Observable95final class ListingModel {96    let uid: String97    var listing: Listing?98    var error: Error?99    var loading = false100101    init(uid: String) { self.uid = uid }102103    func load(force: Bool = false) async {104        if listing != nil, !force { return }105        loading = true106        error = nil107        // la route v3 fait foi (annonce publique, retirée ou inconnue) ; la route v2 apporte les blocs riches108        async let rich = try? APIClient.shared.listing(uid)109        do {110            let v3 = try await APIClient.shared.listingV3(uid)111            listing = (await rich)?.merging(v3: v3) ?? v3112        } catch is CancellationError {113        } catch {114            _ = await rich115            // hors ligne : la dernière fiche connue reste lisible116            if listing == nil { self.error = error }117        }118        loading = false119    }120}121122struct ListingView: View {123    let uid: String124    @Environment(AppModel.self) private var app125    @Environment(Library.self) private var library126    @Environment(\.horizontalSizeClass) private var hSize127    @Environment(DoorCenter.self) private var door128    @State private var model: ListingModel129    @State private var photo = 0130    @State private var showGallery = false131    @State private var external: ExternalLink?132    @Namespace private var galleryNS133134    init(uid: String) {135        self.uid = uid136        _model = State(initialValue: ListingModel(uid: uid))137    }138139    var body: some View {140        Group {141            if let l = model.listing {142                content(l)143            } else if let error = model.error {144                if case APIError.notFound = error {145                    EmptyStateView(door: .closed, title: "Logement introuvable",146                                   message: "Cette adresse ne correspond à aucune annonce publique.",147                                   actionTitle: "Explorer la carte") { app.tab = .explore }148                } else if case APIError.gone = error {149                    EmptyStateView(door: .closed, title: "Annonce retirée",150                                   message: "La source ne publie plus cette annonce. Un retrait est une observation : il ne dit pas que le logement a été loué.",151                                   actionTitle: "Explorer la carte") { app.tab = .explore }152                } else {153                    ErrorStateView(error: error) { Task { await model.load(force: true) } }154                }155            } else {156                loadingView157            }158        }159        .background(Theme.bg)160        .navigationBarTitleDisplayMode(.inline)161        .toolbar {162            if let l = model.listing {163                ToolbarItemGroup(placement: .topBarTrailing) {164                    if let url = l.publicURL {165                        ShareLink(item: url, subject: Text(l.displayTitle),166                                  message: Text("\(l.displayTitle) — \(l.plausiblePrice.map { Fmt.money($0) + " par mois" } ?? "prix sur demande")")) {167                            Image(systemName: "square.and.arrow.up")168                        }169                        .accessibilityLabel("Partager")170                    }171                    Button {172                        let added = library.toggleFavorite(l)173                        if added { Haptics.success() } else { Haptics.tap() }174                        app.showToast(added ? "Ajouté à vos favoris" : "Retiré des favoris")175                    } label: {176                        Image(systemName: library.isFavorite(l.uid) ? "heart.fill" : "heart")177                            .foregroundStyle(library.isFavorite(l.uid) ? Theme.heart : Theme.ink)178                            .heartBurst(library.isFavorite(l.uid))179                    }180                    .accessibilityLabel(library.isFavorite(l.uid) ? "Retirer des favoris" : "Ajouter aux favoris")181                    .accessibilityIdentifier("listing.favorite")182                }183            }184        }185        .task {186            await model.load()187            if let l = model.listing {188                library.markSeen(uid)189                SpotlightIndex.index(l, favorite: library.isFavorite(uid))190            }191        }192        // Handoff et « ouvrir dans Safari » : la fiche porte son adresse publique193        .userActivity("com.spboucher.louka.v2.logement", isActive: model.listing != nil) { activity in194            guard let l = model.listing else { return }195            activity.title = l.displayTitle196            activity.webpageURL = l.publicURL197            activity.isEligibleForHandoff = true198            activity.isEligibleForSearch = false199        }200        .fullScreenCover(isPresented: $showGallery) {201            GalleryViewer(images: model.listing?.images ?? [], index: $photo)202                .navigationTransition(.zoom(sourceID: "galerie", in: galleryNS))203        }204        .safariSheet($external)205    }206207    private var loadingView: some View {208        ScrollView {209            VStack(alignment: .leading, spacing: 16) {210                Skeleton(height: 320, radius: 0)211                VStack(alignment: .leading, spacing: 12) {212                    Skeleton(height: 34).frame(width: 170)213                    Skeleton(height: 18).frame(maxWidth: 280)214                    Skeleton(height: 14).frame(width: 200)215                    Skeleton(height: 120, radius: 18)216                }217                .padding(.horizontal, 20)218            }219        }220        .accessibilityLabel("Chargement de la fiche")221    }222223    private func content(_ l: Listing) -> some View {224        ScrollViewReader { proxy in225        ScrollView {226            VStack(alignment: .leading, spacing: 0) {227                // 1. galerie228                GalleryCarousel(images: l.images, title: l.displayTitle, index: $photo) { showGallery = true }229                    .frame(height: hSize == .regular ? 460 : 320)230                    .frame(maxWidth: .infinity)231                    .clipped()232                    // cible du passage du seuil : l'embrasure de la porte vient exactement sur cette photo233                    .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { door.heroRect = $0 }234                    // transition partagée vers la visionneuse plein écran : la photo s'agrandit depuis la galerie235                    .matchedTransitionSource(id: "galerie", in: galleryNS)236237                // chaque bloc porte son propre espacement : un bloc sans données ne laisse aucun vide,238                // et les blocs sous la ligne de flottaison ne se chargent qu'à leur apparition239                LazyVStack(alignment: .leading, spacing: 0) {240                    if !l.active { inactiveBanner.padding(.bottom, 30) }241                    // 2. prix, verdict, adresse, faits clés, actions242                    SummarySection(listing: l, external: $external).padding(.bottom, 30).id("summary")243                    // 3. description244                    DescriptionSection(listing: l).padding(.bottom, 30).id("description")245                    // 4. inclusions et commodités246                    InclusionsSection(listing: l).padding(.bottom, 30)247                    // 5. détails pratiques248                    PracticalSection(listing: l).padding(.bottom, 30)249                    // 6. analyses250                    ValuationSection(listing: l).id("analyses")251                    ComparablesSection(listing: l).id("comparables")252                    TrueCostSection(listing: l).id("cout")253                    HistorySection(listing: l)254                    ElsewhereSection(listing: l).id("ailleurs")255                    // 7. carte et à proximité256                    LocationSection(listing: l).padding(.bottom, 30).id("location")257                    // 8. scores de quartier258                    ScoresSection(listing: l).padding(.bottom, 30).id("scores")259                    // 9. quartier et dossiers publics260                    NeighbourhoodSection(listing: l).padding(.bottom, 30).id("quartier")261                    BuildingSection(listing: l).padding(.bottom, 30)262                    RentRegistrySection(listing: l)263                    TribunalSection(listing: l)264                    EnvironmentSection(listing: l)265                    // gestionnaire266                    SourceSection(listing: l, external: $external).id("source")267                }268                .padding(.horizontal, 20)269                .padding(.top, 22)270                .padding(.bottom, 30)271                .frame(maxWidth: 760, alignment: .leading)272                .frame(maxWidth: .infinity)273            }274        }275        .safeAreaInset(edge: .bottom) { actionBar(l) }276        .refreshable { await model.load(force: true) }277        .task {278            // ancre de départ imposée par argument de lancement (captures d'écran des sections basses)279            guard let anchor = UserDefaults.standard.string(forKey: "LKAnchor") else { return }280            try? await Task.sleep(for: .seconds(1.2))281            proxy.scrollTo(anchor, anchor: .top)282            try? await Task.sleep(for: .seconds(1.5))283            proxy.scrollTo(anchor, anchor: .top)284        }285        }286    }287288    private var inactiveBanner: some View {289        Label("Cette annonce n'est plus en ligne. La fiche reste consultable.", systemImage: "clock.badge.xmark")290            .font(.subheadline.weight(.medium))291            .foregroundStyle(Theme.high)292            .padding(14)293            .frame(maxWidth: .infinity, alignment: .leading)294            .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))295    }296297    private func actionBar(_ l: Listing) -> some View {298        HStack(spacing: 12) {299            VStack(alignment: .leading, spacing: 1) {300                PriceText(price: l.price, size: 21)301                if let v = l.fvVerdict {302                    Text(v.label + (l.fvDeviation.map { v == .marche ? "" : " · \(Fmt.pct($0))" } ?? ""))303                        .font(.caption.weight(.medium)).foregroundStyle(Theme.color(for: v)).lineLimit(1).minimumScaleFactor(0.8)304                }305            }306            Spacer(minLength: 8)307            if let link = ExternalLink(l.url) {308                Button {309                    Haptics.tap()310                    external = link311                } label: {312                    HStack(spacing: 8) {313                        Text("Voir l'annonce").lineLimit(1).fixedSize()314                        Image(systemName: "arrow.up.right").font(.system(size: 13, weight: .bold))315                    }316                }317                .buttonStyle(PrimaryButtonStyle())318                .accessibilityHint("Ouvre l'annonce originale sur \(app.sourceName(l.source))")319                .accessibilityIdentifier("listing.open")320            }321        }322        .padding(.horizontal, 18)323        .padding(.vertical, 10)324        .background(.bar)325        .overlay(alignment: .top) { Rectangle().fill(Theme.line).frame(height: 1) }326    }327}328329// MARK: - 2. Résumé330331struct SummarySection: View {332    let listing: Listing333    @Binding var external: ExternalLink?334    @Environment(Library.self) private var library335    @Environment(AppModel.self) private var app336    @State private var pdf: ExternalLink?337338    var body: some View {339        let l = listing340        VStack(alignment: .leading, spacing: 16) {341            HStack(alignment: .top) {342                VStack(alignment: .leading, spacing: 4) {343                    PriceText(price: l.price, size: 36)344                    if l.priceFrom, l.plausiblePrice != nil {345                        Text("Loyer « à partir de » selon la source").font(.caption).foregroundStyle(Theme.ink3)346                    }347                    if let d = l.plausibleDrop, let prev = l.pricePrev {348                        Label("Baisse de \(Fmt.pct(-d, signed: false)) · était \(Fmt.money(prev))\(l.priceChangedAt.map { ", \(Fmt.ago($0))" } ?? "")", systemImage: "arrow.down")349                            .font(.caption.weight(.medium)).num().foregroundStyle(Theme.good)350                    }351                }352                Spacer()353                VerdictPill(verdict: l.fvVerdict, deviation: l.fvDeviation, large: true)354            }355            VStack(alignment: .leading, spacing: 5) {356                Text(l.displayTitle).font(.title3.weight(.semibold)).foregroundStyle(Theme.ink)357                    .fixedSize(horizontal: false, vertical: true)358                if !l.address.isEmpty, l.address != l.displayTitle {359                    Label(l.address, systemImage: "mappin.and.ellipse").font(.subheadline).foregroundStyle(Theme.ink2)360                }361                Text(l.place).font(.subheadline).foregroundStyle(Theme.ink3)362            }363364            let facts = keyFacts(l)365            if !facts.isEmpty {366                LazyVGrid(columns: [GridItem(.adaptive(minimum: 104), spacing: 10)], spacing: 10) {367                    ForEach(facts, id: \.label) { f in368                        VStack(alignment: .leading, spacing: 6) {369                            Image(systemName: f.icon).font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.brand)370                            Text(f.value).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.75)371                            Text(f.label).font(.caption2).foregroundStyle(Theme.ink3)372                        }373                        .frame(maxWidth: .infinity, alignment: .leading)374                        .padding(12)375                        .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))376                        .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))377                        .accessibilityElement(children: .ignore)378                        .accessibilityLabel("\(f.label) : \(f.value)")379                    }380                }381            }382383            HStack(spacing: 10) {384                let inCompare = library.compareIDs.contains(l.uid)385                Button {386                    switch library.toggleCompare(l.uid) {387                    case .added: Haptics.success(); app.showToast("Ajouté au comparateur")388                    case .removed: Haptics.tap(); app.showToast("Retiré du comparateur")389                    case .full: Haptics.warning(); app.showToast("Le comparateur contient déjà \(Library.compareMax) logements")390                    }391                } label: {392                    Label(inCompare ? "Dans le comparateur" : "Comparer", systemImage: inCompare ? "checkmark" : "scalemass")393                }394                .buttonStyle(SoftButtonStyle())395                Button {396                    let a = app.costAssumptions397                    Task { if let u = await APIClient.shared.reportURL(listing: l.uid, assumptions: a) { pdf = ExternalLink(url: u) } }398                } label: {399                    Label("Rapport PDF", systemImage: "doc.richtext")400                }401                .accessibilityHint("Rapport complet du logement : estimation, comparables, coût réel, quartier")402                .buttonStyle(SoftButtonStyle())403            }404            if !l.dupSources.isEmpty {405                Text("Aussi publiée sur : \(l.dupSources.map { app.sourceName($0) }.joined(separator: ", "))")406                    .font(.caption).foregroundStyle(Theme.ink3)407            }408        }409        .safariSheet($pdf)410    }411412    private struct Fact { let icon: String; let value: String; let label: String }413414    private func keyFacts(_ l: Listing) -> [Fact] {415        var out: [Fact] = []416        if !l.unitType.isEmpty { out.append(Fact(icon: "square.split.bottomrightquarter", value: l.unitType, label: "Grandeur")) }417        if let b = l.bedrooms, b > 0 { out.append(Fact(icon: "bed.double", value: Fmt.int(b), label: b > 1 ? "Chambres" : "Chambre")) }418        if let b = l.bathrooms, b > 0 {419            out.append(Fact(icon: "shower", value: b == b.rounded() ? Fmt.int(b) : String(format: "%.1f", b).replacingOccurrences(of: ".", with: ","), label: "Salle de bain"))420        }421        if let a = l.areaSqft { out.append(Fact(icon: "ruler", value: "\(Fmt.int(a)) pi²", label: "Superficie")) }422        if let d = Fmt.availability(l.availabilityDate) { out.append(Fact(icon: "calendar", value: d, label: "Disponible")) }423        if let y = l.yearBuilt, y > 1700 { out.append(Fact(icon: "hammer", value: String(y), label: "Construction")) }424        if let p = l.pricePerSqft { out.append(Fact(icon: "dollarsign.square", value: String(format: "%.2f $", p).replacingOccurrences(of: ".", with: ","), label: "Par pi²")) }425        return out426    }427}428429// MARK: - 3. Description430431struct DescriptionSection: View {432    let listing: Listing433    @State private var expanded = false434435    var body: some View {436        let digest = listing.digest437        let text = digest?.texteNettoye ?? listing.description438        if !(text.isEmpty && digest?.enBref == nil) {439            VStack(alignment: .leading, spacing: 12) {440                SectionHeader(title: "Description")441                if let bref = digest?.enBref {442                    HStack(alignment: .top, spacing: 10) {443                        Image(systemName: "text.quote").foregroundStyle(Theme.brand)444                        Text(bref).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)445                    }446                    .padding(14)447                    .frame(maxWidth: .infinity, alignment: .leading)448                    .background(Theme.brandSoft, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))449                }450                if let sections = digest?.sections, sections.count > 1, expanded {451                    ForEach(Array(sections.enumerated()), id: \.offset) { _, s in452                        VStack(alignment: .leading, spacing: 4) {453                            if !s.titre.isEmpty { Text(s.titre).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink) }454                            Text(s.texte).font(.subheadline).foregroundStyle(Theme.ink2).lineSpacing(3)455                        }456                    }457                } else if !text.isEmpty {458                    Text(text).font(.subheadline).foregroundStyle(Theme.ink2).lineSpacing(3)459                        .lineLimit(expanded ? nil : 7)460                }461                if text.count > 380 {462                    Button(expanded ? "Réduire" : "Lire la suite") { withAnimation(.snappy) { expanded.toggle() } }463                        .font(.subheadline.weight(.semibold))464                }465                if let inc = digest?.incoherences, !inc.isEmpty {466                    Label(inc.joined(separator: " · "), systemImage: "exclamationmark.bubble")467                        .font(.caption).foregroundStyle(Theme.high)468                }469            }470        }471    }472}473474// MARK: - 4. Inclusions475476struct InclusionsSection: View {477    let listing: Listing478479    static let inclusionLabels: [String: (String, String)] = [480        "heating": ("Chauffage", "flame"), "electricity": ("Électricité", "bolt"), "hot_water": ("Eau chaude", "drop"),481        "internet": ("Internet", "wifi"), "cable": ("Câble", "tv"), "water": ("Eau", "drop"),482    ]483    static let applianceLabels: [String: (String, String)] = [484        "fridge": ("Réfrigérateur", "refrigerator"), "stove": ("Cuisinière", "stove"), "oven": ("Four", "oven"),485        "dishwasher": ("Lave-vaisselle", "dishwasher"), "washer": ("Laveuse", "washer"), "dryer": ("Sécheuse", "dryer"),486        "washer_dryer": ("Laveuse-sécheuse", "washer"), "microwave": ("Micro-ondes", "microwave"),487    ]488489    var body: some View {490        let d = listing.details491        let included = d.inclusions.filter(\.value).keys.sorted().map { Self.inclusionLabels[$0] ?? ($0.replacingOccurrences(of: "_", with: " ").capitalized, "checkmark") }492        let notIncluded = d.inclusions.filter { !$0.value }.keys.sorted().map { Self.inclusionLabels[$0]?.0 ?? $0 }493        let appliances = d.appliances.filter(\.value).keys.sorted().map { Self.applianceLabels[$0] ?? ($0.replacingOccurrences(of: "_", with: " ").capitalized, "checkmark") }494        var features: [(String, String)] = []495        if d.ac == true { features.append(("Climatisation", "snowflake")) }496        if d.balcony == true { features.append(("Balcon", "sun.max")) }497        if d.elevator == true { features.append(("Ascenseur", "arrow.up.arrow.down")) }498        if d.laundry == true { features.append(("Buanderie", "washer")) }499        if d.storage == true { features.append(("Rangement", "archivebox")) }500        if d.gym == true { features.append(("Gym", "dumbbell")) }501        if d.pool == true { features.append(("Piscine", "figure.pool.swim")) }502        if d.parking?.available == true { features.append(("Stationnement", "parkingsign")) }503        let extra = listing.amenities.filter { a in !features.contains { $0.0.caseInsensitiveCompare(a) == .orderedSame } }504505        return Group {506            if !(included.isEmpty && appliances.isEmpty && features.isEmpty && extra.isEmpty && notIncluded.isEmpty) {507                VStack(alignment: .leading, spacing: 14) {508                    SectionHeader(title: "Inclusions et commodités")509                    if !included.isEmpty { group("Inclus dans le loyer", included, tint: Theme.good) }510                    if !notIncluded.isEmpty {511                        Text("Non inclus : \(notIncluded.joined(separator: ", ").lowercased())").font(.footnote).foregroundStyle(Theme.ink3)512                    }513                    if !appliances.isEmpty { group("Électroménagers", appliances, tint: Theme.ink2) }514                    if !features.isEmpty { group("Immeuble et logement", features, tint: Theme.ink2) }515                    if !extra.isEmpty { group("Mentionné dans l'annonce", extra.prefix(18).map { ($0, "checkmark") }, tint: Theme.ink3) }516                }517            }518        }519    }520521    private func group(_ title: String, _ items: [(String, String)], tint: Color) -> some View {522        VStack(alignment: .leading, spacing: 8) {523            Text(title).font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)524            FlowLayout(spacing: 8) {525                ForEach(items, id: \.0) { label, icon in526                    Label(label, systemImage: icon)527                        .font(.footnote.weight(.medium)).foregroundStyle(tint == Theme.good ? Theme.good : Theme.ink)528                        .padding(.horizontal, 11).padding(.vertical, 7)529                        .background(tint == Theme.good ? Theme.goodSoft : Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))530                }531            }532        }533    }534}535536// MARK: - 5. Détails pratiques537538struct PracticalSection: View {539    let listing: Listing540541    var body: some View {542        let l = listing543        var rows: [(String, String)] = []544        if let d = Fmt.availability(l.availabilityDate, withYear: true) { rows.append(("Disponibilité", d)) }545        if let m = l.digest?.bailMinMois { rows.append(("Bail minimal", "\(m) mois")) }546        switch l.pets {547        case "oui": rows.append(("Animaux", "Acceptés"))548        case "conditions": rows.append(("Animaux", "Acceptés sous conditions"))549        case "non": rows.append(("Animaux", "Non acceptés"))550        default: break551        }552        if let f = l.furnished { rows.append(("Meublé", f ? "Oui" : "Non")) }553        if let p = l.details.parking, p.available {554            var v = p.included == true ? "Inclus" : "Disponible"555            if let price = p.price, price > 0 { v = "\(Fmt.money(price)) / mois" }556            if let t = p.type { v += " (\(t))" }557            rows.append(("Stationnement", v))558        }559        if let s = l.details.smoking { rows.append(("Fumeurs", s ? "Acceptés" : "Non-fumeur")) }560        if let fl = l.details.floor { rows.append(("Étage", String(fl))) }561        if let dep = l.digest?.depot { rows.append(("Dépôt mentionné", dep)) }562        if let c = l.digest?.contraintes, !c.isEmpty { rows.append(("Conditions", c.joined(separator: ", "))) }563        if let fs = l.firstSeen { rows.append(("En ligne depuis", Fmt.date(fs))) }564        if let u = l.updatedAt { rows.append(("Dernière mise à jour", Fmt.ago(u))) }565566        return Group {567            if !rows.isEmpty {568                VStack(alignment: .leading, spacing: 10) {569                    SectionHeader(title: "Détails pratiques")570                    VStack(spacing: 0) {571                        ForEach(Array(rows.enumerated()), id: \.offset) { i, r in572                            KeyValueRow(label: r.0, value: r.1)573                            if i < rows.count - 1 { Divider().overlay(Theme.line) }574                        }575                    }576                    .cardStyle(padding: 14)577                }578            }579        }580    }581}582583// MARK: - Source584585struct SourceSection: View {586    let listing: Listing587    @Binding var external: ExternalLink?588    @Environment(AppModel.self) private var app589    @Environment(Account.self) private var account590    /// Gestionnaire vérifié de ce logement, s'il y en a un ; demandé sans bloquer l'affichage.591    @State private var info: ListingManagerInfo?592593    private var verified: ListingManagerInfo.Manager? { info?.manager.flatMap { $0.verified ? $0 : nil } }594595    var body: some View {596        VStack(alignment: .leading, spacing: 10) {597            SectionHeader(title: "Publié par")598            NavigationLink(value: Route.manager(listing.source)) {599                HStack(spacing: 14) {600                    if let m = verified {601                        ManagerLogo(image: m.logo, name: m.name)602                    } else {603                        Image(systemName: "building.2.fill").foregroundStyle(Theme.brand)604                            .frame(width: 46, height: 46).background(Theme.brandSoft, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))605                    }606                    VStack(alignment: .leading, spacing: 4) {607                        Text(verbatim: verified.map { $0.name.isEmpty ? app.sourceName(listing.source) : $0.name } ?? app.sourceName(listing.source))608                            .font(.headline).foregroundStyle(Theme.ink)609                        if verified != nil { VerifiedBadge() }610                        Text(verified == nil ? "Voir ses logements et ses loyers demandés" : "Voir sa fiche et ses logements").font(.footnote).foregroundStyle(Theme.ink3)611                    }612                    Spacer()613                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)614                }615                .cardStyle(padding: 14)616            }617            .buttonStyle(.plain)618            if let info { ListingManagerBlock(listing: listing, info: info) }619            HStack(spacing: 10) {620                if let phone = listing.details.phone, let tel = URL(string: "tel:\(phone.filter { $0.isNumber || $0 == "+" })") {621                    Link(destination: tel) { Label(phone, systemImage: "phone") }.buttonStyle(SoftButtonStyle())622                }623                if let email = listing.details.email, let mail = URL(string: "mailto:\(email)") {624                    Link(destination: mail) { Label("Courriel", systemImage: "envelope") }.buttonStyle(SoftButtonStyle())625                }626            }627            Text("Lou-Ka agrège les annonces et renvoie toujours vers la source. Vérifiez les détails auprès de l'annonceur avant de vous engager.")628                .font(.caption).foregroundStyle(Theme.ink3)629        }630        // rien ne change si l'appel échoue ou si le logement n'a pas de gestionnaire vérifié631        .task(id: listing.uid) { info = await account.messaging.listingManager(uid: listing.uid) }632    }633}634
Files main
Menu

Theme