<template>
    <div>
        <!-- En-tete : retour repertoire + nom du client. -->
        <div class="flex items-center gap-3">
            <MalioButtonIcon
                icon="mdi:arrow-left-bold"
                icon-size="24"
                variant="ghost"
                v-bind="{ ariaLabel: t('commercial.clients.edit.back') }"
                @click="goBack"
            />
            <h1 class="text-[32px] font-bold 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
                    :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="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="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-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="!isMainValid || 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)]">
                        <MalioInputTextArea
                            v-model="information.description"
                            :label="t('commercial.clients.form.information.description')"
                            resize="none"
                            group-class="row-span-2 pt-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"
                            :error="informationErrors.errors.foundedAt"
                        />
                        <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">
                        <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="contacts.length > 1"
                            :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="!canValidateContacts || 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="addresses.length > 1"
                            :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')"
                                @click="addAddress"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.clients.edit.save')"
                                :disabled="!canValidateAddresses || 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 (0..n) — obligatoires si type de reglement = LCR (RG-1.13). -->
                        <div
                            v-for="(rib, index) in ribs"
                            :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"
                                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
                                variant="secondary"
                                icon-name="mdi:add-bold"
                                icon-position="left"
                                :label="t('commercial.clients.form.accounting.addRib')"
                                @click="addRib"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.clients.edit.save')"
                                :disabled="!canValidateAccounting || 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 } 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/clientConsultation'
import {
    buildAccountingPayload,
    buildAddressPayload,
    buildContactPayload,
    buildInformationPayload,
    buildMainPayload,
    buildRibPayload,
    mapAccountingFormDraft,
    mapInformationDraft,
    mapMainDraft,
    resolveTabEditability,
    type AccountingFormDraft,
    type ClientEditAbilities,
    type InformationFormDraft,
    type MainFormDraft,
} from '~/modules/commercial/utils/clientEdit'
import {
    addressTypeFromFlags,
    buildClientFormTabKeys,
    hasAllRequiredAccountingFields,
    hasAtLeastOneValidContact,
    isBankRequiredForPaymentType,
    isBillingEmailRequired,
    isContactBlank,
    isContactNamed,
    isRibBlank,
    isRibRequiredForPaymentType,
} from '~/modules/commercial/utils/clientFormRules'
import {
    emptyAddress,
    emptyContact,
    emptyRib,
    type AddressFormDraft,
    type ContactFormDraft,
    type RibFormDraft,
} from '~/modules/commercial/types/clientForm'
import { extractApiErrorMessage } from '~/shared/utils/api'

// 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[]>([])

// Ids des sous-ressources existantes supprimees (DELETE differe au « Valider »).
const removedContactIds = ref<number[]>([])
const removedAddressIds = ref<number[]>([])
const removedRibIds = ref<number[]>([])

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())
    if (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 ?? ''),
        })),
)

const countryOptions: RefOption[] = [
    { value: 'France', label: 'France' },
    { value: 'Espagne', label: 'Espagne' },
]

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

// 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],
})))

const activeTab = ref('information')

// ── Navigation ──────────────────────────────────────────────────────────────
function goBack(): void {
    router.push(`/clients/${clientId}`)
}

/**
 * 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 ───────────────────────────────────────────────────────────
const isMainValid = computed(() => {
    const filled = (v: string | null | undefined) => v !== null && v !== undefined && v.trim() !== ''
    const relationValid
        = main.relationType === null
        || (main.relationType === 'distributeur' && filled(main.distributorIri))
        || (main.relationType === 'courtier' && filled(main.brokerIri))
    return filled(main.companyName)
        && main.categoryIris.length >= 1
        && relationValid
})

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 || !isMainValid.value || mainSubmitting.value) return
    mainSubmitting.value = true
    mainErrors.clearErrors()
    try {
        const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main), {
            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)
})
// RG-1.14 : au moins un contact nomme pour finaliser l'onglet.
const canValidateContacts = computed(() => hasAtLeastOneValidContact(contacts.value))

function addContact(): void {
    if (canAddContact.value) contacts.value.push(emptyContact())
}

function askRemoveContact(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.contact'), () => {
        const removed = contacts.value[index]
        if (removed?.id != null) removedContactIds.value.push(removed.id)
        contacts.value.splice(index, 1)
        contactErrors.value.splice(index, 1)
        // Garde au moins un bloc visible (cf. amorce a l'hydratation).
        if (contacts.value.length === 0) contacts.value.push(emptyContact())
    })
}

/**
 * Valide l'onglet Contact : DELETE des contacts retires (existants), puis
 * POST/PATCH des blocs restants sur la sous-ressource. Strictement scope a la
 * collection contacts (endpoints client_contact dedies).
 */
async function submitContacts(): Promise<void> {
    if (businessReadonly.value || !canValidateContacts.value || tabSubmitting.value) return
    tabSubmitting.value = true
    contactErrors.value = []
    try {
        for (const id of removedContactIds.value) {
            await api.delete(`/client_contacts/${id}`, {}, { toast: false })
        }
        removedContactIds.value = []

        // 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 QUE les amorces neuves (id null) totalement vides. Un
            // bloc existant vide est soumis -> 422 RG-1.05 inline (sinon la modif
            // serait perdue en silence avec un faux toast de succes).
            contact => 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 ───────────────────────────────────────────────────────────
const canValidateAddresses = computed(() =>
    addresses.value.length > 0
    && addresses.value.every((a) => {
        const filledBillingEmail = a.billingEmail !== null && a.billingEmail.trim() !== ''
        return addressTypeFromFlags(a) !== null
            && a.siteIris.length >= 1
            && a.categoryIris.length >= 1
            && (!isBillingEmailRequired(a) || filledBillingEmail)
    }),
)

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

function askRemoveAddress(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.address'), () => {
        const removed = addresses.value[index]
        if (removed?.id != null) removedAddressIds.value.push(removed.id)
        addresses.value.splice(index, 1)
        addressErrors.value.splice(index, 1)
        // Garde au moins un bloc visible (cf. amorce a l'hydratation).
        if (addresses.value.length === 0) addresses.value.push(emptyAddress())
    })
}

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 : DELETE des adresses retirees puis POST/PATCH. */
async function submitAddresses(): Promise<void> {
    if (businessReadonly.value || !canValidateAddresses.value || tabSubmitting.value) return
    tabSubmitting.value = true
    addressErrors.value = []
    try {
        for (const id of removedAddressIds.value) {
            await api.delete(`/client_addresses/${id}`, {}, { toast: false })
        }
        removedAddressIds.value = []

        // On tente TOUS les blocs d'adresse (collecte des erreurs par index, ERP-110).
        const hasError = await submitRows(
            addresses.value,
            addressErrors,
            async (address) => {
                const body = buildAddressPayload(address, isBillingEmailRequired(address))
                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))

function onPaymentTypeChange(value: string | number | null): void {
    accounting.paymentTypeIri = value === null ? null : String(value)
    if (!isBankRequired.value) accounting.bankIri = null
}

function ribIsComplete(rib: { label: string | null, bic: string | null, iban: string | null }): boolean {
    const filled = (v: string | null) => v !== null && v.trim() !== ''
    return filled(rib.label) && filled(rib.bic) && filled(rib.iban)
}

const canValidateAccounting = computed(() => {
    if (!hasAllRequiredAccountingFields(accounting)) return false
    if (isBankRequired.value && accounting.bankIri === null) return false
    if (isRibRequired.value && !ribs.value.some(ribIsComplete)) return false
    return true
})

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

function askRemoveRib(index: number): void {
    askConfirm(t('commercial.clients.form.confirmDelete.rib'), () => {
        const removed = ribs.value[index]
        if (removed?.id != null) removedRibIds.value.push(removed.id)
        ribs.value.splice(index, 1)
        ribErrors.value.splice(index, 1)
        // Garde au moins un bloc RIB visible (cf. amorce a l'hydratation).
        if (ribs.value.length === 0) ribs.value.push(emptyRib())
    })
}

/**
 * Valide l'onglet Comptabilite : PATCH des scalaires (groupe client:write:accounting,
 * exige accounting.manage cote back) PUIS DELETE/POST/PATCH des RIB sur la
 * sous-ressource. 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 || !canValidateAccounting.value || tabSubmitting.value) return
    tabSubmitting.value = true
    accountingErrors.clearErrors()
    // Reset des erreurs RIB des le debut : l'etape 1 (PATCH scalaires) peut
    // echouer et `return` avant submitRows (qui porte sinon le reset), laissant
    // des erreurs de RIB obsoletes affichees sous les blocs.
    ribErrors.value = []
    try {
        // 1) 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
        }

        for (const id of removedRibIds.value) {
            await api.delete(`/client_ribs/${id}`, {}, { toast: false })
        }
        removedRibIds.value = []

        // 2) POST/PATCH des RIB (erreurs inline par ligne, tous les blocs tentes).
        // Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
        // IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
        const ribHasError = await submitRows(
            ribs.value,
            ribErrors,
            async (rib) => {
                const body = buildRibPayload(rib)
                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 QUE les amorces neuves (id null) totalement vides. Un
            // RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
            // serait perdue en silence avec un faux toast de succes).
            rib => rib.id === null && isRibBlank(rib),
        )
        if (ribHasError) 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>
