<template>
    <div>
        <!-- En-tete : retour repertoire + nom du client. -->
        <div class="flex items-center gap-3 pt-11">
            <MalioButtonIcon
                icon="mdi:arrow-left-bold"
                icon-size="24"
                variant="ghost"
                v-bind="{ ariaLabel: t('commercial.clients.edit.back') }"
                @click="goBack"
            />
            <h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
        </div>

        <!-- Etats de chargement / introuvable. -->
        <p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.clients.edit.loading') }}</p>
        <p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.clients.edit.notFound') }}</p>

        <template v-else-if="client">
            <!-- ── Bloc principal (pre-rempli, editable si `manage`) ──────────────
                 Decision Tristan : on conserve le bloc principal en modification
                 (« pour ne pas tout casser »), edite via son propre PATCH scope
                 sur le groupe client:write:main. Readonly pour les roles sans
                 `manage` (ex. Compta). -->
            <div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
                <MalioInputText
                    v-model="main.companyName"
                    :label="t('commercial.clients.form.main.companyName')"
                    :required="true"
                    :readonly="businessReadonly"
                    :error="mainErrors.errors.companyName"
                />
                <MalioSelectCheckbox
                    :model-value="main.categoryIris"
                    :options="mainCategoryOptions"
                    :label="t('commercial.clients.form.main.categories')"
                    :display-tag="true"
                    :readonly="businessReadonly"
                    :required="true"
                    :error="mainErrors.errors.categories"
                    @update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
                />
                <MalioSelect
                    v-if="showRelationAndTriage"
                    :model-value="main.relationType"
                    :options="relationOptions"
                    :label="t('commercial.clients.form.main.relation')"
                    :empty-option-label="t('commercial.clients.form.main.relationNone')"
                    :readonly="businessReadonly"
                    @update:model-value="onRelationChange"
                />
                <MalioSelect
                    v-if="showRelationAndTriage && main.relationType === 'courtier'"
                    :model-value="main.brokerIri"
                    :options="brokerOptions"
                    :label="t('commercial.clients.form.main.brokerName')"
                    :readonly="businessReadonly"
                    :required="true"
                    :error="mainErrors.errors.broker"
                    @update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
                />
                <MalioSelect
                    v-if="showRelationAndTriage && main.relationType === 'distributeur'"
                    :model-value="main.distributorIri"
                    :options="distributorOptions"
                    :label="t('commercial.clients.form.main.distributorName')"
                    :readonly="businessReadonly"
                    :required="true"
                    :error="mainErrors.errors.distributor"
                    @update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
                />
                <MalioCheckbox
                    v-if="showRelationAndTriage"
                    v-model="main.triageService"
                    :label="t('commercial.clients.form.main.triageService')"
                    group-class="self-center"
                    :readonly="businessReadonly"
                />
            </div>

            <div v-if="!businessReadonly" class="mt-12 flex justify-center">
                <MalioButton
                    variant="primary"
                    :label="t('commercial.clients.edit.save')"
                    :disabled="mainSubmitting"
                    @click="submitMain"
                />
            </div>

            <!-- ── Onglets : navigation LIBRE, edition independante par onglet ──── -->
            <MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
                <!-- Onglet Information -->
                <template #information>
                    <div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
                        <!-- pt-1/pb-1 alignent le textarea (h-full) en haut ET en bas
                             sur les inputs (champ 40px centre dans un h-12 -> ~4px de
                             coussin de chaque cote). -->
                        <MalioInputTextArea
                            v-model="information.description"
                            :label="t('commercial.clients.form.information.description')"
                            resize="none"
                            group-class="row-span-2 pt-1 pb-1"
                            text-input="h-full text-lg"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.description"
                        />
                        <MalioInputText
                            v-model="information.competitors"
                            :label="t('commercial.clients.form.information.competitors')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.competitors"
                        />
                        <MalioDate
                            v-model="information.foundedAt"
                            :label="t('commercial.clients.form.information.foundedAt')"
                            :readonly="businessReadonly"
                            :editable="true"
                            :error="informationErrors.errors.foundedAt"
                            @update:raw-value="(v: string) => information.foundedAtRaw = v"
                        />
                        <MalioInputText
                            v-model="information.employeesCount"
                            :label="t('commercial.clients.form.information.employeesCount')"
                            :mask="EMPLOYEES_MASK"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.employeesCount"
                        />
                        <MalioInputAmount
                            v-model="information.revenueAmount"
                            :label="t('commercial.clients.form.information.revenueAmount')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.revenueAmount"
                        />
                        <MalioInputText
                            v-model="information.directorName"
                            :label="t('commercial.clients.form.information.directorName')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.directorName"
                        />
                        <MalioInputAmount
                            v-model="information.profitAmount"
                            :label="t('commercial.clients.form.information.profitAmount')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.profitAmount"
                        />
                    </div>
                    <div v-if="!businessReadonly" class="mt-12 flex justify-center">
                        <MalioButton
                            variant="primary"
                            :label="t('commercial.clients.edit.save')"
                            :disabled="tabSubmitting"
                            @click="submitInformation"
                        />
                    </div>
                </template>

                <!-- Onglet Contact -->
                <template #contact>
                    <div class="mt-12 flex flex-col gap-6">
                        <!-- ERP-172 : poubelle visible seulement s'il reste un AUTRE bloc deja
                             enregistre (id en base) — cf. isRowRemovable. Empeche de supprimer un
                             bloc tant que rien n'est sauvegarde, et de supprimer son dernier
                             bloc enregistre. -->
                        <ClientContactBlock
                            v-for="(contact, index) in contacts"
                            :key="contact.id ?? `new-${index}`"
                            :model-value="contact"
                            :title="t('commercial.clients.form.contact.title', { n: index + 1 })"
                            :removable="isRowRemovable(contacts, index)"
                            :readonly="businessReadonly"
                            :errors="contactErrors[index]"
                            @update:model-value="(v) => contacts[index] = v"
                            @remove="askRemoveContact(index)"
                        />
                        <div v-if="!businessReadonly" class="flex justify-center gap-6">
                            <MalioButton
                                variant="secondary"
                                icon-name="mdi:add-bold"
                                icon-position="left"
                                :label="t('commercial.clients.form.contact.add')"
                                :disabled="!canAddContact"
                                @click="addContact"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.clients.edit.save')"
                                :disabled="tabSubmitting"
                                @click="submitContacts"
                            />
                        </div>
                    </div>
                </template>

                <!-- Onglet Adresse -->
                <template #address>
                    <div class="mt-12 flex flex-col gap-6">
                        <ClientAddressBlock
                            v-for="(address, index) in addresses"
                            :key="address.id ?? `new-${index}`"
                            :model-value="address"
                            :title="t('commercial.clients.form.address.title', { n: index + 1 })"
                            :category-options="addressCategoryOptions"
                            :site-options="siteOptions"
                            :contact-options="contactOptions"
                            :country-options="countryOptions"
                            :removable="isRowRemovable(addresses, index)"
                            :readonly="businessReadonly"
                            :errors="addressErrors[index]"
                            @update:model-value="(v) => addresses[index] = v"
                            @remove="askRemoveAddress(index)"
                            @degraded="onAddressDegraded"
                        />
                        <div v-if="!businessReadonly" class="flex justify-center gap-6">
                            <MalioButton
                                variant="secondary"
                                icon-name="mdi:add-bold"
                                icon-position="left"
                                :label="t('commercial.clients.form.address.add')"
                                :disabled="!canAddAddress"
                                @click="addAddress"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.clients.edit.save')"
                                :disabled="tabSubmitting"
                                @click="submitAddresses"
                            />
                        </div>
                    </div>
                </template>

                <!-- Onglet Comptabilite (present uniquement si accounting.view ;
                     editable uniquement si accounting.manage). -->
                <template v-if="canAccountingView" #accounting>
                    <div class="mt-12 flex flex-col gap-6">
                        <div class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
                            <div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
                                <MalioInputText
                                    v-model="accounting.siren"
                                    :label="t('commercial.clients.form.accounting.siren')"
                                    :mask="SIREN_MASK"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.siren"
                                />
                                <MalioInputText
                                    v-model="accounting.accountNumber"
                                    :label="t('commercial.clients.form.accounting.accountNumber')"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.accountNumber"
                                />
                                <MalioSelect
                                    :model-value="accounting.tvaModeIri"
                                    :options="tvaModeOptions"
                                    :label="t('commercial.clients.form.accounting.tvaMode')"
                                    :readonly="accountingReadonly"
                                    empty-option-label=""
                                    :required="true"
                                    :error="accountingErrors.errors.tvaMode"
                                    @update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
                                />
                                <MalioInputText
                                    v-model="accounting.nTva"
                                    :label="t('commercial.clients.form.accounting.nTva')"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.nTva"
                                />
                                <MalioSelect
                                    :model-value="accounting.paymentDelayIri"
                                    :options="paymentDelayOptions"
                                    :label="t('commercial.clients.form.accounting.paymentDelay')"
                                    :readonly="accountingReadonly"
                                    empty-option-label=""
                                    :required="true"
                                    :error="accountingErrors.errors.paymentDelay"
                                    @update:model-value="(v: string | number | null) => accounting.paymentDelayIri = v === null ? null : String(v)"
                                />
                                <MalioSelect
                                    :model-value="accounting.paymentTypeIri"
                                    :options="paymentTypeOptions"
                                    :label="t('commercial.clients.form.accounting.paymentType')"
                                    :readonly="accountingReadonly"
                                    empty-option-label=""
                                    :required="true"
                                    :error="accountingErrors.errors.paymentType"
                                    @update:model-value="onPaymentTypeChange"
                                />
                                <MalioSelect
                                    v-if="isBankRequired"
                                    :model-value="accounting.bankIri"
                                    :options="bankOptions"
                                    :label="t('commercial.clients.form.accounting.bank')"
                                    :readonly="accountingReadonly"
                                    empty-option-label=""
                                    :required="true"
                                    :error="accountingErrors.errors.bank"
                                    @update:model-value="(v: string | number | null) => accounting.bankIri = v === null ? null : String(v)"
                                />
                            </div>
                        </div>

                        <!-- Blocs RIB — affiches uniquement si type de reglement = LCR (RG-1.13). -->
                        <div
                            v-for="(rib, index) in visibleRibs"
                            :key="rib.id ?? `new-${index}`"
                            class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
                        >
                            <MalioButtonIcon
                                v-if="!accountingReadonly && isRowRemovable(visibleRibs, index)"
                                icon="mdi:delete-outline"
                                variant="ghost"
                                button-class="absolute top-3 right-3"
                                v-bind="{ ariaLabel: t('commercial.clients.form.accounting.removeRib') }"
                                @click="askRemoveRib(index)"
                            />
                            <div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
                                <MalioInputText
                                    v-model="rib.label"
                                    :label="t('commercial.clients.form.accounting.ribLabel')"
                                    :readonly="accountingReadonly"
                                    :required="isRibRequired"
                                    :error="ribErrors[index]?.label"
                                />
                                <MalioInputText
                                    v-model="rib.bic"
                                    :label="t('commercial.clients.form.accounting.ribBic')"
                                    :readonly="accountingReadonly"
                                    :required="isRibRequired"
                                    :error="ribErrors[index]?.bic"
                                />
                                <MalioInputText
                                    v-model="rib.iban"
                                    :label="t('commercial.clients.form.accounting.ribIban')"
                                    :readonly="accountingReadonly"
                                    :required="isRibRequired"
                                    :error="ribErrors[index]?.iban"
                                />
                            </div>
                        </div>

                        <div v-if="!accountingReadonly" class="flex justify-center gap-6">
                            <MalioButton
                                v-if="isRibRequired"
                                variant="secondary"
                                icon-name="mdi:add-bold"
                                icon-position="left"
                                :label="t('commercial.clients.form.accounting.addRib')"
                                :disabled="!canAddRib"
                                @click="addRib"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.clients.edit.save')"
                                :disabled="tabSubmitting"
                                @click="submitAccounting"
                            />
                        </div>
                    </div>
                </template>

                <!-- Onglets non encore implementes : frame vide (navigation libre). -->
                <template #transport><ComingSoonPlaceholder /></template>
                <template #statistics><ComingSoonPlaceholder /></template>
                <template #reports><ComingSoonPlaceholder /></template>
                <template #exchanges><ComingSoonPlaceholder /></template>
            </MalioTabList>
        </template>

        <!-- Modal de confirmation generique (suppression contact / adresse / RIB). -->
        <MalioModal v-model="confirmModal.open" modal-class="max-w-md">
            <template #header>
                <h2 class="text-[24px] font-bold">{{ t('commercial.clients.form.confirmDelete.title') }}</h2>
            </template>
            <p>{{ confirmModal.message }}</p>
            <template #footer>
                <MalioButton
                    variant="secondary"
                    button-class="flex-1"
                    :label="t('commercial.clients.form.confirmDelete.cancel')"
                    @click="confirmModal.open = false"
                />
                <MalioButton
                    variant="danger"
                    button-class="flex-1"
                    :label="t('commercial.clients.form.confirmDelete.confirm')"
                    @click="runConfirm"
                />
            </template>
        </MalioModal>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useClient } from '~/modules/commercial/composables/useClient'
import { useClientReferentials, type CategoryOption, type RefOption } from '~/modules/commercial/composables/useClientReferentials'
import { useClientFormErrors } from '~/modules/commercial/composables/useClientFormErrors'
import {
    canEditClient,
    categoryOptionsOf,
    referentialOptionOf,
    siteOptionsOf,
    mapContactToDraft,
    mapAddressToDraft,
    mapRibToDraft,
    type ClientDetail,
} from '~/modules/commercial/utils/forms/clientConsultation'
import {
    buildAccountingPayload,
    buildAddressPayload,
    buildContactPayload,
    buildInformationPayload,
    buildMainPayload,
    buildRibPayload,
    mapAccountingFormDraft,
    mapInformationDraft,
    mapMainDraft,
    resolveTabEditability,
    type AccountingFormDraft,
    type ClientEditAbilities,
    type InformationFormDraft,
    type MainFormDraft,
} from '~/modules/commercial/utils/forms/clientEdit'
import {
    buildClientFormTabKeys,
    isAddressValid,
    isBankRequiredForPaymentType,
    isBillingEmailRequired,
    isContactBlank,
    isContactNamed,
    isRibBlank,
    isRibComplete,
    isRibRequiredForPaymentType,
    showsRelationAndTriageFields,
} from '~/modules/commercial/utils/forms/clientFormRules'
import {
    emptyAddress,
    emptyContact,
    emptyRib,
    type AddressFormDraft,
    type ContactFormDraft,
    type RibFormDraft,
} from '~/modules/commercial/types/clientForm'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable, removeCollectionRow } from '~/shared/utils/collectionRow'
import { readHistoryTab } from '~/shared/utils/historyTab'

// Masques de saisie (la normalisation finale reste serveur).
const SIREN_MASK = '#########'
const EMPLOYEES_MASK = '#######'

// Codes de categorie interdits sur une adresse (RG-1.29, ERP-78).
const FORBIDDEN_ADDRESS_CATEGORY_CODES = ['DISTRIBUTEUR', 'COURTIER']

const { t } = useI18n()
const api = useApi()
const toast = useToast()
const route = useRoute()
const router = useRouter()
const { can, canAny } = usePermissions()

// Gating de la route : l'edition exige de pouvoir editer au moins un onglet
// (`manage` OU `accounting.manage`). Usine et roles en lecture seule sont
// rediriges vers le repertoire (lui-meme protege).
if (!canEditClient(canAny)) {
    await navigateTo('/clients')
}

const clientId = route.params.id as string

const { client, loading, error, load } = useClient(clientId)
const referentials = useClientReferentials()

// ── Permissions / editabilite par zone (option 1 ERP-74) ────────────────────
const abilities = computed<ClientEditAbilities>(() => ({
    canManage: can('commercial.clients.manage'),
    canAccountingView: can('commercial.clients.accounting.view'),
    canAccountingManage: can('commercial.clients.accounting.manage'),
}))
const editability = computed(() => resolveTabEditability(abilities.value))
// Bloc principal + onglets Information / Contact / Adresse.
const businessReadonly = computed(() => !editability.value.businessEditable)
const canAccountingView = computed(() => editability.value.accountingVisible)
const accountingReadonly = computed(() => !editability.value.accountingEditable)

const headerTitle = computed(() => client.value?.companyName ?? t('commercial.clients.edit.title'))

// ── Brouillons editables (pre-remplis depuis le detail) ─────────────────────
const main = reactive<MainFormDraft>(mapMainDraft({} as ClientDetail))
const information = reactive<InformationFormDraft>(mapInformationDraft({} as ClientDetail))
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as ClientDetail))
const contacts = ref<ContactFormDraft[]>([])
const addresses = ref<AddressFormDraft[]>([])
const ribs = ref<RibFormDraft[]>([])


const mainSubmitting = ref(false)
const tabSubmitting = ref(false)
const addressDegradedNotified = ref(false)

/** Recopie le detail charge dans les brouillons editables. */
function hydrate(detail: ClientDetail): void {
    Object.assign(main, mapMainDraft(detail))
    Object.assign(information, mapInformationDraft(detail))
    Object.assign(accounting, mapAccountingFormDraft(detail))
    contacts.value = (detail.contacts ?? []).map(mapContactToDraft)
    addresses.value = (detail.addresses ?? []).map(mapAddressToDraft)
    ribs.value = (detail.ribs ?? []).map(mapRibToDraft)
    // Chaque bloc reste visible meme vide : si une collection est vide, on amorce
    // un bloc vierge (non persiste tant qu'incomplet — cf. submit*/canValidate*).
    if (contacts.value.length === 0) contacts.value.push(emptyContact())
    if (addresses.value.length === 0) addresses.value.push(emptyAddress())
    // RIB : amorce un bloc vide seulement si le type de reglement est une LCR
    // (sinon la section reste masquee — RG-1.13).
    if (isRibRequired.value && ribs.value.length === 0) ribs.value.push(emptyRib())
    // Charge les listes distributeur / courtier si une relation est deja posee.
    if (main.relationType === 'distributeur') referentials.loadDistributors().catch(() => {})
    if (main.relationType === 'courtier') referentials.loadBrokers().catch(() => {})
}

// ── Options de selects (referentiels UNION valeurs courantes de l'embed) ─────
// L'union garantit que les valeurs deja posees s'affichent meme quand le
// referentiel complet n'est pas chargeable (roles metier sans
// catalog.categories.view / sites.view → 403, cf. matrice § 2.7).
function mergeOptions<T extends { value: string }>(primary: T[], extra: T[]): T[] {
    const seen = new Set(primary.map(o => o.value))
    return [...primary, ...extra.filter(o => !seen.has(o.value))]
}

const embedCategoryOptions = computed<CategoryOption[]>(() => {
    const fromClient = categoryOptionsOf(client.value?.categories)
    const fromAddresses = (client.value?.addresses ?? []).flatMap(a => categoryOptionsOf(a.categories))
    return mergeOptions(fromClient, fromAddresses)
})
const mainCategoryOptions = computed(() => mergeOptions(referentials.categories.value, embedCategoryOptions.value))
// Categories autorisees sur une adresse : toutes SAUF DISTRIBUTEUR/COURTIER (RG-1.29).
const addressCategoryOptions = computed(() =>
    mainCategoryOptions.value.filter(c => !FORBIDDEN_ADDRESS_CATEGORY_CODES.includes(c.code)),
)

const embedSiteOptions = computed<RefOption[]>(() =>
    mergeOptions([], (client.value?.addresses ?? []).flatMap(a => siteOptionsOf(a.sites))),
)
const siteOptions = computed(() => mergeOptions(referentials.sites.value, embedSiteOptions.value))

// Contacts deja persistes (iri non null), rattachables a une adresse (M2M).
const contactOptions = computed<RefOption[]>(() =>
    contacts.value
        .filter(c => c.iri !== null)
        .map(c => ({
            value: c.iri as string,
            label: [c.firstName, c.lastName].filter(Boolean).join(' ') || (c.email ?? ''),
        })),
)

// Pays : referentiel `country` charge via l'API (ERP-116), en remplacement de
// l'ancienne liste codee en dur. Valeur = nom du pays (l'adresse stocke
// `country` en chaine libre, donc value === label). On merge la valeur deja
// stockee sur chaque adresse (embed) — comme les autres selects de cet ecran —
// pour ne pas vider le select si `/countries` echoue (resilience ERP-102) ou si
// un pays historique n'appartient pas au referentiel.
const embedCountryOptions = computed<RefOption[]>(() =>
    mergeOptions([], (client.value?.addresses ?? [])
        .map(a => a.country)
        .filter((c): c is string => !!c)
        .map(c => ({ value: c, label: c }))),
)
const countryOptions = computed<RefOption[]>(() =>
    mergeOptions(referentials.countries.value, embedCountryOptions.value),
)

const relationOptions = computed<RefOption[]>(() => [
    { value: 'distributeur', label: t('commercial.clients.form.main.relationDistributor') },
    { value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
])

// Codes des categories selectionnees (resolus depuis l'union referentiel + embed).
const selectedCategoryCodes = computed(() =>
    main.categoryIris
        .map(iri => mainCategoryOptions.value.find(c => c.value === iri)?.code)
        .filter((code): code is string => code !== undefined),
)

// « Relation » + « Prestation de triage » masques par defaut, reveles des qu'une
// categorie ordinaire (autre que Distributeur/Courtier) est selectionnee.
const showRelationAndTriage = computed(() => showsRelationAndTriageFields(selectedCategoryCodes.value))

// Masquer ces champs reinitialise leurs valeurs : pas de relation/triage fantome
// soumis pour un client Distributeur/Courtier.
watch(showRelationAndTriage, (visible) => {
    if (!visible) {
        main.relationType = null
        main.distributorIri = null
        main.brokerIri = null
        main.triageService = false
    }
})

// Distributeur / courtier : referentiel charge a la demande UNION valeur courante.
const currentDistributorOption = computed<RefOption[]>(() => {
    const d = client.value?.distributor
    return d && typeof d === 'object' ? [{ value: d['@id'], label: d.companyName ?? d['@id'] }] : []
})
const currentBrokerOption = computed<RefOption[]>(() => {
    const b = client.value?.broker
    return b && typeof b === 'object' ? [{ value: b['@id'], label: b.companyName ?? b['@id'] }] : []
})
const distributorOptions = computed(() => mergeOptions(referentials.distributors.value, currentDistributorOption.value))
const brokerOptions = computed(() => mergeOptions(referentials.brokers.value, currentBrokerOption.value))

// Selects comptables : referentiel UNION valeur courante de l'embed (libelle).
const tvaModeOptions = computed(() => mergeOptions(referentials.tvaModes.value, referentialOptionOf(client.value?.tvaMode)))
const paymentDelayOptions = computed(() => mergeOptions(referentials.paymentDelays.value, referentialOptionOf(client.value?.paymentDelay)))
const paymentTypeOptions = computed(() => mergeOptions(
    referentials.paymentTypes.value.map(p => ({ value: p.value, label: p.label })),
    referentialOptionOf(client.value?.paymentType),
))
const bankOptions = computed(() => mergeOptions(referentials.banks.value, referentialOptionOf(client.value?.bank)))

// ── Onglets : navigation libre (4 actifs + 4 coquilles, comme la consultation) ─
const tabKeys = computed(() => buildClientFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))

const TAB_ICONS: Record<string, string> = {
    information: 'mdi:account-outline',
    contact: 'mdi:account-box-plus-outline',
    address: 'mdi:map-marker-outline',
    transport: 'mdi:truck-delivery-outline',
    accounting: 'mdi:bank-circle-outline',
    statistics: 'mdi:finance',
    reports: 'mdi:file-document-edit-outline',
    exchanges: 'mdi:account-group-outline',
}

const tabs = computed(() => tabKeys.value.map(key => ({
    key,
    label: t(`commercial.clients.tab.${key}`),
    icon: TAB_ICONS[key],
})))

// Onglet initial : repris de la consultation (history.state), sinon Information.
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')

// ── Navigation ──────────────────────────────────────────────────────────────
/** Retour consultation en conservant l'onglet courant (via history.state). */
function goBack(): void {
    router.push({ path: `/clients/${clientId}`, state: { tab: activeTab.value } })
}

/**
 * Message d'erreur a afficher : violation 422 / detail renvoye par le serveur,
 * sinon un libelle generique. Le 409 d'unicite de nom (bloc principal) est
 * traduit explicitement par l'appelant.
 */
function apiErrorMessage(e: unknown): string {
    const data = (e as { data?: unknown })?.data
    return extractApiErrorMessage(data) || t('commercial.clients.toast.error')
}

function showError(e: unknown, opts: { duplicateCompany?: boolean } = {}): void {
    const status = (e as { response?: { status?: number } })?.response?.status
    toast.error({
        title: t('commercial.clients.toast.error'),
        message: opts.duplicateCompany && status === 409
            ? t('commercial.clients.form.duplicateCompany')
            : apiErrorMessage(e),
    })
}

// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
// Etat d'erreurs factorise avec l'ecran de creation (cf. useClientFormErrors) :
// un `useFormErrors` par groupe scalaire + un tableau d'erreurs par ligne pour
// chaque collection (aligne sur l'index visible). `mapRowError` mappe une 422
// inline et retourne true ; il ne toaste pas, le fallback `showError` reste
// local a l'edition (cf. catch des submits de collection).
const {
    mainErrors,
    informationErrors,
    accountingErrors,
    contactErrors,
    addressErrors,
    ribErrors,
    submitRows,
} = useClientFormErrors()

// ── Bloc principal ───────────────────────────────────────────────────────────
async function onRelationChange(value: string | number | null): Promise<void> {
    const relation = (value === null || value === '') ? null : (String(value) as 'distributeur' | 'courtier')
    main.relationType = relation
    // Une seule FK remplie a la fois (RG-1.03).
    if (relation !== 'distributeur') main.distributorIri = null
    if (relation !== 'courtier') main.brokerIri = null

    if (relation === 'distributeur') await referentials.loadDistributors().catch(() => {})
    if (relation === 'courtier') await referentials.loadBrokers().catch(() => {})
}

/** PATCH /clients/{id} — groupe client:write:main UNIQUEMENT (mode strict). */
async function submitMain(): Promise<void> {
    if (businessReadonly.value || mainSubmitting.value) return
    mainSubmitting.value = true
    mainErrors.clearErrors()
    try {
        const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main, { forUpdate: true }), {
            headers: { Accept: 'application/ld+json' },
            toast: false,
        })
        // Reaffiche les valeurs normalisees renvoyees par le serveur.
        Object.assign(main, mapMainDraft(updated))
        toast.success({ title: t('commercial.clients.toast.updateSuccess') })
    }
    catch (e) {
        // 409 = doublon nom de societe → erreur inline + toast ; 422 → mapping
        // inline par champ ; autre → toast de fallback. Cf. ERP-101.
        const status = (e as { response?: { status?: number } })?.response?.status
        if (status === 409) {
            const message = t('commercial.clients.form.duplicateCompany')
            mainErrors.setError('companyName', message)
            toast.error({ title: t('commercial.clients.toast.error'), message })
        }
        else {
            mainErrors.handleApiError(e, { fallbackMessage: t('commercial.clients.toast.error') })
        }
    }
    finally {
        mainSubmitting.value = false
    }
}

// ── Onglet Information ───────────────────────────────────────────────────────
/** PATCH /clients/{id} — groupe client:write:information UNIQUEMENT. */
async function submitInformation(): Promise<void> {
    if (businessReadonly.value || tabSubmitting.value) return
    tabSubmitting.value = true
    informationErrors.clearErrors()
    try {
        await api.patch(`/clients/${clientId}`, buildInformationPayload(information), { toast: false })
        toast.success({ title: t('commercial.clients.toast.updateSuccess') })
    }
    catch (e) {
        informationErrors.handleApiError(e, { fallbackMessage: t('commercial.clients.toast.error') })
    }
    finally {
        tabSubmitting.value = false
    }
}

// ── Onglet Contact ───────────────────────────────────────────────────────────
const canAddContact = computed(() => {
    const last = contacts.value[contacts.value.length - 1]
    return last === undefined || isContactNamed(last)
})
function addContact(): void {
    if (canAddContact.value) contacts.value.push(emptyContact())
}

// ERP-172 : DELETE immediat de la sous-ressource a la confirmation de la modale
// (et non plus differe au « Enregistrer »). Bloc jamais persiste (id null) : retrait
// local. Echec serveur : bloc conserve + erreur remontee.
function askRemoveContact(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.contact'), () => removeCollectionRow({
        rows: contacts.value,
        errors: contactErrors.value,
        index,
        endpoint: '/client_contacts',
        deleteRow: url => api.delete(url, {}, { toast: false }),
        makeEmpty: emptyContact,
        onError: showError,
    }))
}

/**
 * Valide l'onglet Contact : POST/PATCH des blocs restants sur la sous-ressource.
 * Strictement scope a la collection contacts (endpoints client_contact dedies). La
 * suppression est traitee a part, en DELETE immediat (askRemoveContact, ERP-172).
 */
async function submitContacts(): Promise<void> {
    if (businessReadonly.value || tabSubmitting.value) return
    tabSubmitting.value = true
    contactErrors.value = []
    try {
        // RG-1.14 : au moins un contact requis. Si l'onglet ne contient QUE des
        // amorces neuves vides (ex. tous les contacts existants supprimes), on ne
        // les skippe pas -> le back renvoie la 422 RG-1.05 « prénom ou nom
        // obligatoire » inline (la RG-1.14 n'a pas d'equivalent back au POST).
        const hasSubmittableContact = contacts.value.some(c => c.id !== null || !isContactBlank(c))
        // On tente TOUS les blocs (collecte des erreurs par index, ERP-110). Seuls
        // les blocs TOTALEMENT vides sont ignores : un bloc partiellement rempli
        // sans nom (email seul) est soumis -> 422 RG-1.05 inline sous le bloc.
        const hasError = await submitRows(
            contacts.value,
            contactErrors,
            async (contact) => {
                const body = buildContactPayload(contact)
                if (contact.id === null) {
                    const created = await api.post<{ '@id'?: string, id: number }>(
                        `/clients/${clientId}/contacts`,
                        body,
                        { headers: { Accept: 'application/ld+json' }, toast: false },
                    )
                    contact.id = created.id
                    contact.iri = created['@id'] ?? null
                }
                else {
                    await api.patch(`/client_contacts/${contact.id}`, body, { toast: false })
                }
            },
            error => showError(error),
            // On ne saute une amorce neuve (id null) totalement vide QUE si un autre
            // bloc sera soumis : sinon on la soumet pour declencher la 422 RG-1.05
            // (un onglet Contact vide ne doit pas passer en faux succes).
            contact => hasSubmittableContact && contact.id === null && isContactBlank(contact),
        )
        // Tant qu'un bloc reste en erreur : pas de toast succes.
        if (hasError) return
        toast.success({ title: t('commercial.clients.toast.updateSuccess') })
    }
    catch (e) {
        showError(e)
    }
    finally {
        tabSubmitting.value = false
    }
}

// ── Onglet Adresse ───────────────────────────────────────────────────────────
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
const canAddAddress = computed(() => {
    const last = addresses.value[addresses.value.length - 1]
    return last !== undefined && isAddressValid(last)
})

function addAddress(): void {
    if (canAddAddress.value) addresses.value.push(emptyAddress())
}

function askRemoveAddress(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.address'), () => removeCollectionRow({
        rows: addresses.value,
        errors: addressErrors.value,
        index,
        endpoint: '/client_addresses',
        deleteRow: url => api.delete(url, {}, { toast: false }),
        makeEmpty: emptyAddress,
        onError: showError,
    }))
}

function onAddressDegraded(): void {
    if (addressDegradedNotified.value) return
    addressDegradedNotified.value = true
    toast.warning({
        title: t('commercial.clients.toast.error'),
        message: t('commercial.clients.form.address.degraded'),
    })
}

/** Valide l'onglet Adresse : POST/PATCH des blocs restants (suppression en DELETE immediat, ERP-172). */
async function submitAddresses(): Promise<void> {
    if (businessReadonly.value || tabSubmitting.value) return
    tabSubmitting.value = true
    addressErrors.value = []
    try {
        // On tente TOUS les blocs d'adresse (collecte des erreurs par index, ERP-110).
        const hasError = await submitRows(
            addresses.value,
            addressErrors,
            async (address) => {
                // Edition d'une adresse existante : champ requis vide envoye en `''`
                // (NotBlank 422) au lieu d'etre omis — sinon le PATCH garderait
                // l'ancienne valeur (faux 200). Creation (id null) : omit classique.
                const body = buildAddressPayload(address, isBillingEmailRequired(address), { forUpdate: address.id !== null })
                if (address.id === null) {
                    const created = await api.post<{ id: number }>(
                        `/clients/${clientId}/addresses`,
                        body,
                        { headers: { Accept: 'application/ld+json' }, toast: false },
                    )
                    address.id = created.id
                }
                else {
                    await api.patch(`/client_addresses/${address.id}`, body, { toast: false })
                }
            },
            error => showError(error),
        )
        if (hasError) return
        toast.success({ title: t('commercial.clients.toast.updateSuccess') })
    }
    catch (e) {
        showError(e)
    }
    finally {
        tabSubmitting.value = false
    }
}

// ── Onglet Comptabilite ──────────────────────────────────────────────────────
const selectedPaymentTypeCode = computed(() =>
    referentials.paymentTypes.value.find(p => p.value === accounting.paymentTypeIri)?.code ?? null,
)
const isBankRequired = computed(() => isBankRequiredForPaymentType(selectedPaymentTypeCode.value))
const isRibRequired = computed(() => isRibRequiredForPaymentType(selectedPaymentTypeCode.value))

// Les blocs RIB ne sont affiches que pour une LCR (RG-1.13).
const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])

function onPaymentTypeChange(value: string | number | null): void {
    accounting.paymentTypeIri = value === null ? null : String(value)
    if (!isBankRequired.value) accounting.bankIri = null
    // ERP-121 : un RIB est une coordonnee bancaire du client, decouplee du mode de
    // reglement. Au passage hors-LCR on ne SUPPRIME plus les RIB existants : ils
    // restent en base, simplement masques a l'ecran (visibleRibs = []), et
    // reapparaissent tels quels si l'on repasse en LCR. Seule la corbeille d'un
    // bloc (askRemoveRib) retire reellement un RIB.
    if (isRibRequired.value) {
        if (ribs.value.length === 0) ribs.value.push(emptyRib())
    }
    else {
        // Hors-LCR : on nettoie seulement les erreurs inline (plus affichees).
        ribErrors.value = []
    }
}

// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
const canAddRib = computed(() => {
    const last = ribs.value[ribs.value.length - 1]
    return last !== undefined && isRibComplete(last)
})

function addRib(): void {
    if (canAddRib.value) ribs.value.push(emptyRib())
}

// ERP-172 : DELETE immediat du RIB. Le back refuse la suppression du dernier RIB
// d'une LCR (RG-1.13) -> 409 remonte via showError (message back), bloc conserve.
function askRemoveRib(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.rib'), () => removeCollectionRow({
        rows: ribs.value,
        errors: ribErrors.value,
        index,
        endpoint: '/client_ribs',
        deleteRow: url => api.delete(url, {}, { toast: false }),
        makeEmpty: emptyRib,
        onError: showError,
    }))
}

/**
 * Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
 * PATCH des scalaires (groupe client:write:accounting, exige accounting.manage cote
 * back). Les RIB crees d'abord : le back valide RG-1.13 (LCR => au moins un RIB
 * persiste) sur le PATCH scalaires.
 *
 * ERP-172 : la suppression d'un RIB est traitee en DELETE immediat (askRemoveRib),
 * plus de DELETE differe ici.
 * ERP-121 : les RIB ne sont (re)soumis QUE sous LCR — hors-LCR ce sont des
 * coordonnees dormantes conservees telles quelles, masquees a l'ecran et jamais
 * re-ecrites. Aucun champ main/information dans le payload (mode strict RG-1.28 :
 * sinon 403 sur tout le payload).
 */
async function submitAccounting(): Promise<void> {
    if (accountingReadonly.value || tabSubmitting.value) return
    tabSubmitting.value = true
    accountingErrors.clearErrors()
    try {
        // 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
        // ligne, tous les blocs tentes). Le back exige >=1 RIB persiste pour valider
        // une LCR a l'etape 2. Hors-LCR (ERP-121), les RIB sont des coordonnees
        // dormantes : rien d'editable n'est affiche, on ne les re-soumet pas.
        // On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
        // sinon (ex. l'unique RIB existant supprime, remplace par un bloc vide), on la
        // soumet pour declencher la 422 NotBlank inline plutot que de laisser le DELETE
        // echouer en « dernier RIB d'une LCR » (message plat sans propertyPath).
        if (isRibRequired.value) {
            const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
            const ribHasError = await submitRows(
                ribs.value,
                ribErrors,
                async (rib) => {
                    // Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
                    // 422) au lieu d'etre omis (sinon le PATCH garderait l'ancienne valeur).
                    const body = buildRibPayload(rib, { forUpdate: rib.id !== null })
                    if (rib.id === null) {
                        const created = await api.post<{ id: number }>(
                            `/clients/${clientId}/ribs`,
                            body,
                            { headers: { Accept: 'application/ld+json' }, toast: false },
                        )
                        rib.id = created.id
                    }
                    else {
                        await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
                    }
                },
                error => showError(error),
                // On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
                // est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
                // inline (sinon la modif serait perdue en silence avec un faux toast succes).
                rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
            )
            if (ribHasError) return
        }

        // 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
        try {
            await api.patch(`/clients/${clientId}`, buildAccountingPayload(accounting, isBankRequired.value), { toast: false })
        }
        catch (error) {
            accountingErrors.handleApiError(error, { fallbackMessage: t('commercial.clients.toast.error') })
            return
        }

        toast.success({ title: t('commercial.clients.toast.updateSuccess') })
    }
    catch (e) {
        showError(e)
    }
    finally {
        tabSubmitting.value = false
    }
}

// ── Modal de confirmation generique ──────────────────────────────────────────
const confirmModal = reactive({
    open: false,
    message: '',
    action: null as null | (() => void),
})

function askConfirm(message: string, action: () => void): void {
    confirmModal.message = message
    confirmModal.action = action
    confirmModal.open = true
}

function runConfirm(): void {
    confirmModal.action?.()
    confirmModal.action = null
    confirmModal.open = false
}

useHead({ title: headerTitle })

onMounted(async () => {
    // Referentiels en best-effort (echec non bloquant : l'embed alimente les
    // libelles des valeurs courantes).
    referentials.loadCommon().catch(() => {})
    await load()
    if (client.value) hydrate(client.value)
})
</script>
