SPB Git

Repository Public

ProsView.swift 31.7 KB 648 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Pros/ProsView.swift10// Description      : annuaire des courtiers et agences — bannières, agences11//                    inscrites à l'OACIQ et plateformes (recherche, régions,12//                    tri), fiche d'agence avec ses propriétés et ses courtiers13//                    ; registre v1 en repli.14// Module           : ImmoKa15// Repository       : https://git.spboucher.ai/immo-ka-ios-v316// Project Website  : https://www.immo-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 SwiftUI9394/// Ligne d'annuaire : initiale, nom, sous-titre, valeur à droite.95struct DirectoryRow: View {96    let title: String97    var subtitle: String?98    var value: String?99    var valueLabel: String?100101    var body: some View {102        VStack(spacing: 0) {103            HStack(alignment: .center, spacing: 14) {104                VStack(alignment: .leading, spacing: 3) {105                    Text(title).font(.editorial(18)).foregroundStyle(Theme.ink).lineLimit(2).multilineTextAlignment(.leading)106                    if let subtitle, !subtitle.isEmpty {107                        Text(subtitle).font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(2).multilineTextAlignment(.leading)108                    }109                }110                Spacer(minLength: 8)111                if let value {112                    VStack(alignment: .trailing, spacing: 1) {113                        Text(value).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)114                        if let valueLabel { Text(valueLabel).font(.caption2).foregroundStyle(Theme.ink3) }115                    }116                }117                Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)118            }119            .padding(.vertical, 13)120            Divider().overlay(Theme.line)121        }122        .contentShape(Rectangle())123        .accessibilityElement(children: .combine)124    }125}126127/// Bandeau de régions à bascule.128struct RegionChips: View {129    let regions: [RegionCount]130    @Binding var selection: String?131132    var body: some View {133        ScrollView(.horizontal, showsIndicators: false) {134            HStack(spacing: 8) {135                Chip(label: "Toutes les régions", active: selection == nil) { selection = nil }136                ForEach(regions) { r in137                    Chip(label: "\(r.region) · \(r.n)", active: selection == r.region) {138                        selection = selection == r.region ? nil : r.region139                    }140                }141            }142            .padding(.horizontal, 20)143        }144        .padding(.horizontal, -20)145    }146}147148// MARK: - Onglet « Courtiers »149150struct ProsView: View {151    enum Scope: String, CaseIterable, Identifiable {152        case franchises, agencies, platforms153        var id: String { rawValue }154        var label: String {155            switch self {156            case .franchises: "Bannières"157            case .agencies: "Agences"158            case .platforms: "Plateformes"159            }160        }161    }162    enum Sort: String, CaseIterable, Identifiable {163        case listings, brokers, name164        var id: String { rawValue }165        var label: String {166            switch self {167            case .listings: "Propriétés"168            case .brokers: "Courtiers"169            case .name: "Nom"170            }171        }172    }173174    @Environment(AppModel.self) private var app175    @State private var directory: AgencyDirectory?176    @State private var error: Error?177    @State private var query = ""178    @State private var scope: Scope = .franchises179    @State private var sort: Sort = .listings180    @State private var region: String?181    @State private var onlyWithListings = true182183    private var filtered: [AgencyEntry] {184        guard let d = directory else { return [] }185        let q = Fmt.slug(query)186        // une recherche porte sur tout l'annuaire ; sinon sur la catégorie choisie187        var out: [AgencyEntry]188        if !q.isEmpty {189            out = d.all.filter { Fmt.slug($0.name).contains(q) || Fmt.slug($0.franchise ?? "").contains(q) || $0.cities.contains { Fmt.slug($0).contains(q) } }190        } else {191            switch scope {192            case .franchises: out = d.franchises193            case .platforms: out = d.platforms194            case .agencies: out = d.agencies.filter { (!onlyWithListings || $0.activeListings > 0) && (region == nil || $0.regions.contains(region ?? "")) }195            }196        }197        switch sort {198        case .listings: out.sort { ($0.activeListings, $0.brokers ?? 0) > ($1.activeListings, $1.brokers ?? 0) }199        case .brokers: out.sort { ($0.brokers ?? 0, $0.activeListings) > ($1.brokers ?? 0, $1.activeListings) }200        case .name: out.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }201        }202        return out203    }204205    var body: some View {206        ScrollView {207            LazyVStack(alignment: .leading, spacing: 0) {208                if let d = directory {209                    header(d).padding(.bottom, 24)210                    controls(d).padding(.bottom, 10)211                    Divider().overlay(Theme.line)212                    let list = filtered213                    ForEach(Array(list.enumerated()), id: \.element.id) { i, e in214                        NavigationLink(value: Route.agency(e.name)) {215                            DirectoryRow(title: e.name, subtitle: subtitle(e),216                                         value: e.activeListings > 0 ? Fmt.int(e.activeListings) : nil,217                                         valueLabel: e.activeListings > 1 ? "propriétés" : "propriété")218                        }219                        .buttonStyle(.plain)220                        .staggered(i)221                    }222                    if list.isEmpty {223                        EmptyStateView(door: .closed, title: "Aucun résultat",224                                       message: scope == .agencies && onlyWithListings && query.isEmpty225                                           ? "Aucune agence de cette région n'a de propriété en ligne. Désactivez le filtre pour voir tout le registre."226                                           : "Essayez un autre nom, une ville ou une autre région.")227                    }228                } else if let error {229                    ErrorStateView(error: error) { Task { await load() } }230                } else {231                    ForEach(0..<8, id: \.self) { _ in Skeleton(height: 54, radius: 8).padding(.vertical, 6) }232                }233            }234            .padding(.horizontal, 20).padding(.bottom, 30)235            .frame(maxWidth: 760)236            .frame(maxWidth: .infinity)237            .animation(.snappy, value: sort)238            .animation(.snappy, value: scope)239            .animation(.snappy, value: region)240            .animation(.snappy, value: onlyWithListings)241        }242        .background(Theme.bg)243        .navigationTitle("Courtiers et agences")244        .searchable(text: $query, prompt: "Bannière, agence ou ville")245        .refreshable { await load() }246        .task { if directory == nil { await load() } }247    }248249    private func load() async {250        error = nil251        do { directory = try await APIClient.shared.agencyDirectory() } catch is CancellationError {} catch { self.error = error }252    }253254    private func subtitle(_ e: AgencyEntry) -> String? {255        var parts: [String] = []256        switch e.kind {257        case .franchise:258            if let o = e.offices, o > 1 { parts.append(Fmt.plural(o, "agence", "agences")) }259            if let b = e.brokers { parts.append(Fmt.plural(b, "courtier", "courtiers")) }260        case .agency:261            if let f = e.franchise, Fmt.slug(f) != Fmt.slug(e.name) { parts.append(f) }262            if let b = e.brokers { parts.append(Fmt.plural(b, "courtier", "courtiers")) }263            if let r = e.regions.first { parts.append(e.regions.count > 1 ? "\(r) et \(e.regions.count - 1) autre\(e.regions.count > 2 ? "s" : "")" : r) }264        case .platform:265            if let k = e.platformKind { parts.append(k == "fsbo" ? "vente sans intermédiaire" : k) }266            if let o = e.offices, o > 1 { parts.append(Fmt.plural(o, "bureau", "bureaux")) }267        }268        if let m = e.priceMedian, e.activeListings > 0 { parts.append("médiane \(Fmt.compactMoney(m))") }269        return parts.isEmpty ? nil : parts.joined(separator: " · ")270    }271272    private func header(_ d: AgencyDirectory) -> some View {273        VStack(alignment: .leading, spacing: 18) {274            Text(summary(d))275                .font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)276                .accessibilityIdentifier("pros.summary")277            VStack(spacing: 0) {278                Divider().overlay(Theme.line)279                if ServiceGeneration.current >= 3 {280                    link(.brokers, "Chercher un courtier", "Par son nom, parmi ceux que nomment les sources", "person.text.rectangle")281                    link(.neighborhoods(city: nil, name: nil), "Quartiers et villes", "Marché, parc immobilier, services et transport", "building.2")282                }283                link(.inspectors, "Inspecteurs en bâtiment", "Par région, avec leurs avis", "checklist")284                link(.movers, "Déménageurs", "Pour le jour où vous aurez les clés", "shippingbox")285                link(.cities, "Villes", "Propriétés à vendre et prix médian par ville", "mappin.and.ellipse")286                if d.agencies.isEmpty {287                    link(.registry, "Registre des agences de courtage", "Les agences inscrites à l'OACIQ et leurs courtiers", "list.bullet.rectangle")288                }289            }290        }291    }292293    private func summary(_ d: AgencyDirectory) -> String {294        if d.agencies.isEmpty {295            return "\(Fmt.int(d.franchises.count)) bannières, agences et portails publient \(Fmt.int(d.listingsTotal)) propriétés à vendre."296        }297        return "\(Fmt.int(d.total)) agences de courtage inscrites à l'OACIQ\(d.brokersTotal.map { ", \(Fmt.int($0)) courtiers" } ?? "") ; \(Fmt.int(d.listingsTotal)) propriétés à vendre publiées par \(Fmt.int(d.franchises.count)) bannières\(d.withListings.map { ", \(Fmt.int($0)) agences" } ?? "") et \(Fmt.int(d.platforms.count)) plateformes."298    }299300    @ViewBuilder301    private func controls(_ d: AgencyDirectory) -> some View {302        VStack(alignment: .leading, spacing: 12) {303            if !d.agencies.isEmpty, query.isEmpty {304                SlidingSegmented(selection: $scope, options: Scope.allCases.map { (value: $0, label: $0.label) }, label: "Catégorie de l'annuaire")305            }306            if scope == .agencies, query.isEmpty, !d.regions.isEmpty {307                ScrollView(.horizontal, showsIndicators: false) {308                    HStack(spacing: 8) {309                        Chip(label: "Avec propriétés", icon: "house", active: onlyWithListings) { onlyWithListings.toggle() }310                        Chip(label: "Toutes les régions", active: region == nil) { region = nil }311                        ForEach(d.regions) { r in312                            Chip(label: "\(r.region) · \(r.agencies)", active: region == r.region) { region = region == r.region ? nil : r.region }313                        }314                    }315                    .padding(.horizontal, 20)316                }317                .padding(.horizontal, -20)318            }319            HStack(alignment: .center) {320                Text(Fmt.plural(filtered.count, "résultat", "résultats")).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)321                    .contentTransition(.numericText())322                Spacer()323                SlidingSegmented(selection: $sort, options: Sort.allCases.map { (value: $0, label: $0.label) }, label: "Tri de l'annuaire")324            }325        }326    }327328    private func link(_ route: Route, _ title: String, _ text: String, _ icon: String) -> some View {329        NavigationLink(value: route) {330            VStack(spacing: 0) {331                HStack(spacing: 14) {332                    Image(systemName: icon).font(.system(size: 16)).foregroundStyle(Theme.brand).frame(width: 26)333                    VStack(alignment: .leading, spacing: 2) {334                        Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)335                        Text(text).font(.footnote).foregroundStyle(Theme.ink3)336                    }337                    Spacer()338                    Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)339                }340                .padding(.vertical, 12)341                Divider().overlay(Theme.line)342            }343            .contentShape(Rectangle())344        }345        .buttonStyle(.plain)346    }347}348349// MARK: - Fiche d'une bannière, d'une agence ou d'une plateforme350351struct AgencyView: View {352    let name: String353    @Environment(AppModel.self) private var app354    @Environment(\.horizontalSizeClass) private var hSize355    @State private var entry: AgencyEntry?356    @State private var offices: [AgencyEntry] = []357    @State private var loaded = false358    @State private var listings: [Listing]?359    @State private var total: Int?360    @State private var showAll = false361    @State private var external: ExternalLink?362363    var body: some View {364        ScrollView {365            LazyVStack(alignment: .leading, spacing: 28) {366                VStack(alignment: .leading, spacing: 8) {367                    if let f = entry?.franchise, Fmt.slug(f) != Fmt.slug(entry?.name ?? "") {368                        Button { app.open(.agency(f)) } label: { Text(f).eyebrowStyle() }.buttonStyle(.plain)369                    }370                    Text(entry?.name ?? name).font(.editorial(28)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)371                    if let e = entry {372                        Text(facts(e)).font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)373                    } else if loaded {374                        Text("Cette agence n'est pas dans l'annuaire.").font(.subheadline).foregroundStyle(Theme.ink2)375                    }376                }377                if let e = entry {378                    let stats = keyStats(e)379                    if !stats.isEmpty {380                        LazyVGrid(columns: [GridItem(.adaptive(minimum: 130), spacing: 16, alignment: .topLeading)], alignment: .leading, spacing: 16) {381                            ForEach(stats, id: \.1) { StatTile(value: $0.0, label: $0.1) }382                        }383                        .padding(.vertical, 16)384                        .overlay(alignment: .top) { Divider().overlay(Theme.line) }385                        .overlay(alignment: .bottom) { Divider().overlay(Theme.line) }386                    }387                    FlowLayout(spacing: 10) {388                        if e.activeListings > 0 {389                            Button { app.explore(e.filters, title: e.name) } label: { Label("Voir sur la carte", systemImage: "map") }390                                .buttonStyle(PrimaryButtonStyle())391                        }392                        if let link = ExternalLink(e.url) {393                            Button { external = link } label: { Label("Site web", systemImage: "safari") }.buttonStyle(SoftButtonStyle())394                        }395                    }396                    if !e.cities.isEmpty {397                        VStack(alignment: .leading, spacing: 10) {398                            Text("Principales villes").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)399                            FlowLayout(spacing: 8) {400                                ForEach(e.cities.prefix(8), id: \.self) { c in401                                    Chip(label: c) { var f = e.filters; f.city = c; app.explore(f, title: nil) }402                                }403                            }404                        }405                    }406                }407                if !offices.isEmpty {408                    VStack(alignment: .leading, spacing: 0) {409                        SectionHeader(title: "Agences de la bannière").padding(.bottom, 6)410                        ForEach(offices.prefix(showAll ? 400 : 8)) { o in411                            NavigationLink(value: Route.agency(o.name)) {412                                DirectoryRow(title: o.name, subtitle: o.brokers.map { Fmt.plural($0, "courtier", "courtiers") },413                                             value: o.activeListings > 0 ? Fmt.int(o.activeListings) : nil, valueLabel: "propriétés")414                            }415                            .buttonStyle(.plain)416                        }417                        if offices.count > 8 {418                            Button(showAll ? "Réduire" : "Toutes les agences (\(offices.count))") { withAnimation(.snappy) { showAll.toggle() } }419                                .font(.subheadline.weight(.semibold)).padding(.top, 12)420                        }421                    }422                }423                if let listings, !listings.isEmpty {424                    VStack(alignment: .leading, spacing: 14) {425                        SectionHeader(title: "Propriétés récentes", subtitle: total.map { "Les plus récentes parmi \(Fmt.int($0))." })426                        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 14), count: hSize == .regular ? 2 : 1), spacing: 14) {427                            ForEach(Array(listings.enumerated()), id: \.element.id) { i, l in ListingLink(listing: l).staggered(i) }428                        }429                    }430                } else if listings == nil, (entry?.activeListings ?? 0) > 0 {431                    ForEach(0..<2, id: \.self) { _ in ListingCardSkeleton() }432                }433                if let b = entry?.brokersList, !b.isEmpty {434                    VStack(alignment: .leading, spacing: 0) {435                        SectionHeader(title: "Courtiers", subtitle: "Titulaires de permis rattachés à l'agence, d'après le registre de l'OACIQ.").padding(.bottom, 6)436                        ForEach(b.prefix(showAll ? 2000 : 12)) { br in437                            HStack {438                                Text(br.name).font(.subheadline).foregroundStyle(Theme.ink)439                                Spacer()440                                if let c = br.city { Text(c).font(.footnote).foregroundStyle(Theme.ink3) }441                            }442                            .padding(.vertical, 9)443                            .accessibilityElement(children: .combine)444                            Divider().overlay(Theme.line)445                        }446                        if b.count > 12 {447                            Button(showAll ? "Réduire" : "Tous les courtiers (\(b.count))") { withAnimation(.snappy) { showAll.toggle() } }448                                .font(.subheadline.weight(.semibold)).padding(.top, 12)449                        }450                    }451                }452            }453            .padding(20)454            .frame(maxWidth: 760, alignment: .leading)455            .frame(maxWidth: .infinity)456        }457        .background(Theme.bg)458        .navigationTitle(entry?.kind == .platform ? "Plateforme" : (entry?.kind == .franchise ? "Bannière" : "Agence"))459        .navigationBarTitleDisplayMode(.inline)460        .safariSheet($external)461        .task {462            guard !loaded else { return }463            let d = try? await APIClient.shared.agencyDirectory()464            let key = Fmt.slug(name)465            // la bannière d'abord (elle porte le même nom que certaines agences), puis les plateformes, puis le registre466            var e = d?.franchises.first { Fmt.slug($0.name) == key } ?? d?.platforms.first { Fmt.slug($0.name) == key || $0.source == name }467                ?? d?.agencies.first { Fmt.slug($0.name) == key || $0.id == name }468            if let found = e, found.kind == .franchise {469                offices = (d?.agencies ?? []).filter { Fmt.slug($0.franchise ?? "") == key && Fmt.slug($0.name) != key }470                    .sorted { ($0.activeListings, $0.brokers ?? 0) > ($1.activeListings, $1.brokers ?? 0) }471            }472            if let found = e, found.kind == .agency, let full = try? await APIClient.shared.agency(found.id) {473                var f = full; f.kind = .agency474                e = f475            }476            entry = e477            loaded = true478            guard let e, e.activeListings > 0 else { listings = []; return }479            let r = try? await APIClient.shared.search(e.filters, sort: .recent, pageSize: 24)480            total = r?.total481            listings = (r?.listings ?? []).filter { $0.plausiblePrice != nil }482        }483    }484485    private func facts(_ e: AgencyEntry) -> String {486        var parts: [String] = []487        switch e.kind {488        case .franchise: parts.append("Bannière de courtage immobilier")489        case .agency: parts.append("Agence de courtage immobilier")490        case .platform: parts.append(e.platformKind == "fsbo" ? "Vente sans intermédiaire" : (e.platformKind.map { $0.prefix(1).uppercased() + $0.dropFirst() } ?? "Plateforme d'inscriptions"))491        }492        if !e.regions.isEmpty { parts.append(e.regions.prefix(3).joined(separator: ", ") + (e.regions.count > 3 ? "…" : "")) }493        return parts.joined(separator: " · ")494    }495496    private func keyStats(_ e: AgencyEntry) -> [(String, String)] {497        var out: [(String, String)] = []498        if e.activeListings > 0 { out.append((Fmt.int(e.activeListings), e.activeListings > 1 ? "Propriétés à vendre" : "Propriété à vendre")) }499        if let m = e.priceMedian, e.activeListings > 0 { out.append((Fmt.compactMoney(m), "Prix médian demandé")) }500        if let o = e.offices, o > 1 { out.append((Fmt.int(o), e.kind == .franchise ? "Agences" : "Bureaux")) }501        if let b = e.brokers { out.append((Fmt.int(b), "Courtiers")) }502        if let c = e.citiesTotal, c > 1 { out.append((Fmt.int(c), "Villes")) }503        return out504    }505}506507// MARK: - Registre des agences de courtage (OACIQ)508509struct RegistryView: View {510    @State private var directory: BannieresDirectory?511    @State private var error: Error?512    @State private var query = ""513    @State private var region: String?514    @State private var byName = false515516    private var filtered: [Banniere] {517        guard let d = directory else { return [] }518        let q = Fmt.slug(query)519        var out = d.bannieres.filter { b in520            (region == nil || b.regions.contains(region ?? "")) && (q.isEmpty || Fmt.slug(b.name).contains(q))521        }522        if byName { out.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } }523        else { out.sort { $0.brokersN > $1.brokersN } }524        return out525    }526527    var body: some View {528        ScrollView {529            LazyVStack(alignment: .leading, spacing: 0) {530                if let d = directory {531                    VStack(alignment: .leading, spacing: 16) {532                        Text("\(Fmt.int(d.total)) agences de courtage immobilier inscrites au registre de l'OACIQ, et leurs \(Fmt.int(d.brokersTotal)) courtiers.")533                            .font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)534                        RegionChips(regions: d.regions, selection: $region)535                        HStack {536                            Text(Fmt.plural(filtered.count, "résultat", "résultats")).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)537                            Spacer()538                            SlidingSegmented(selection: $byName, options: [(false, "Courtiers"), (true, "Nom")], label: "Tri du registre")539                        }540                    }541                    .padding(.bottom, 8)542                    Divider().overlay(Theme.line)543                    let list = filtered544                    ForEach(Array(list.enumerated()), id: \.element.id) { i, b in545                        NavigationLink(value: Route.banniere(b.id)) {546                            DirectoryRow(title: b.name, subtitle: b.regions.prefix(3).joined(separator: ", "),547                                         value: Fmt.int(b.brokersN), valueLabel: b.brokersN > 1 ? "courtiers" : "courtier")548                        }549                        .buttonStyle(.plain)550                        .staggered(i)551                    }552                    if list.isEmpty {553                        EmptyStateView(door: .closed, title: "Aucune agence trouvée", message: "Essayez un autre nom ou une autre région.")554                    }555                } else if let error {556                    ErrorStateView(error: error) { Task { await load() } }557                } else {558                    ForEach(0..<8, id: \.self) { _ in Skeleton(height: 54, radius: 8).padding(.vertical, 6) }559                }560            }561            .padding(.horizontal, 20).padding(.vertical, 12)562            .frame(maxWidth: 760)563            .frame(maxWidth: .infinity)564            .animation(.snappy, value: byName)565            .animation(.snappy, value: region)566        }567        .background(Theme.bg)568        .navigationTitle("Registre des agences")569        .navigationBarTitleDisplayMode(.inline)570        .searchable(text: $query, prompt: "Nom de l'agence")571        .task { if directory == nil { await load() } }572    }573574    private func load() async {575        error = nil576        do { directory = try await APIClient.shared.bannieres() } catch is CancellationError {} catch { self.error = error }577    }578}579580struct BanniereView: View {581    let id: String582    @Environment(AppModel.self) private var app583    @State private var banniere: Banniere?584    @State private var error: Error?585    @State private var query = ""586    @State private var external: ExternalLink?587588    var body: some View {589        Group {590            if let b = banniere {591                let q = Fmt.slug(query)592                let brokers = q.isEmpty ? b.brokers : b.brokers.filter { Fmt.slug($0.name).contains(q) || Fmt.slug($0.city ?? "").contains(q) }593                List {594                    Section {595                        VStack(alignment: .leading, spacing: 10) {596                            Text(b.name).font(.editorial(26)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)597                            Text("\(Fmt.plural(b.brokersN, "courtier inscrit", "courtiers inscrits"))\(b.regions.isEmpty ? "" : " · \(b.regions.joined(separator: ", "))")")598                                .font(.subheadline).num().foregroundStyle(Theme.ink2)599                            FlowLayout(spacing: 10) {600                                if let src = b.coveredBy {601                                    Button { app.open(.agency(b.name)) } label: { Label("Ses propriétés", systemImage: "house") }602                                        .buttonStyle(PrimaryButtonStyle())603                                }604                                if let link = ExternalLink(b.site) {605                                    Button { external = link } label: { Label("Site de l'agence", systemImage: "safari") }606                                        .buttonStyle(SoftButtonStyle())607                                }608                            }609                        }610                        .listRowBackground(Color.clear)611                        .listRowSeparator(.hidden)612                        .listRowInsets(EdgeInsets(top: 8, leading: 20, bottom: 12, trailing: 20))613                    }614                    if !b.brokers.isEmpty {615                        Section("Courtiers") {616                            ForEach(brokers) { br in617                                VStack(alignment: .leading, spacing: 2) {618                                    Text(br.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)619                                    if let c = br.city { Text(c).font(.caption).foregroundStyle(Theme.ink3) }620                                }621                                .listRowBackground(Theme.bg)622                                .accessibilityElement(children: .combine)623                            }624                        }625                    }626                }627                .listStyle(.plain)628                .scrollContentBackground(.hidden)629                .searchable(text: $query, prompt: "Courtier ou ville")630            } else if let error {631                ErrorStateView(error: error) { Task { await load() } }632            } else {633                BrandLoader().frame(maxWidth: .infinity, maxHeight: .infinity)634            }635        }636        .background(Theme.bg)637        .navigationTitle("Agence")638        .navigationBarTitleDisplayMode(.inline)639        .task { if banniere == nil { await load() } }640        .safariSheet($external)641    }642643    private func load() async {644        error = nil645        do { banniere = try await APIClient.shared.banniere(id) } catch is CancellationError {} catch { self.error = error }646    }647}648
Files main
Menu

Theme