<template>
    <div>
        <!-- En-tete : retour consultation + nom du fournisseur. -->
        <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.suppliers.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.suppliers.edit.loading') }}</p>
        <p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.suppliers.edit.notFound') }}</p>

        <template v-else-if="supplier">
            <!-- ── Bloc principal (pre-rempli, editable si `manage`) ──────────────
                 Conserve en modification (miroir client) ; edite via son propre
                 PATCH scope sur le groupe supplier:write:main. Readonly pour les
                 roles sans `manage` (ex. Compta). Pas de contact inline (ERP-106). -->
            <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.suppliers.form.main.companyName')"
                    :required="true"
                    :readonly="businessReadonly"
                    :error="mainErrors.errors.companyName"
                />
                <MalioSelectCheckbox
                    :model-value="main.categoryIris"
                    :options="mainCategoryOptions"
                    :label="t('commercial.suppliers.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)"
                />
            </div>

            <div v-if="!businessReadonly" class="mt-12 flex justify-center">
                <MalioButton
                    variant="primary"
                    :label="t('commercial.suppliers.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) sur les inputs. -->
                        <MalioInputTextArea
                            v-model="information.description"
                            :label="t('commercial.suppliers.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.suppliers.form.information.competitors')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.competitors"
                        />
                        <MalioDate
                            v-model="information.foundedAt"
                            :label="t('commercial.suppliers.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.suppliers.form.information.employeesCount')"
                            :mask="EMPLOYEES_MASK"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.employeesCount"
                        />
                        <MalioInputAmount
                            v-model="information.revenueAmount"
                            :label="t('commercial.suppliers.form.information.revenueAmount')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.revenueAmount"
                        />
                        <MalioInputText
                            v-model="information.directorName"
                            :label="t('commercial.suppliers.form.information.directorName')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.directorName"
                        />
                        <MalioInputAmount
                            v-model="information.profitAmount"
                            :label="t('commercial.suppliers.form.information.profitAmount')"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.profitAmount"
                        />
                        <!-- Volume previsionnel : specifique fournisseur (entier). -->
                        <MalioInputText
                            v-model="information.volumeForecast"
                            :label="t('commercial.suppliers.form.information.volumeForecast')"
                            :mask="VOLUME_FORECAST_MASK"
                            :readonly="businessReadonly"
                            :error="informationErrors.errors.volumeForecast"
                        />
                    </div>
                    <div v-if="!businessReadonly" class="mt-12 flex justify-center">
                        <MalioButton
                            variant="primary"
                            :label="t('commercial.suppliers.edit.save')"
                            :disabled="tabSubmitting"
                            @click="submitInformation"
                        />
                    </div>
                </template>

                <!-- Onglet Contacts -->
                <template #contacts>
                    <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. -->
                        <SupplierContactBlock
                            v-for="(contact, index) in contacts"
                            :key="contact.id ?? `new-${index}`"
                            :model-value="contact"
                            :title="t('commercial.suppliers.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.suppliers.form.contact.add')"
                                :disabled="!canAddContact"
                                @click="addContact"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.suppliers.edit.save')"
                                :disabled="tabSubmitting"
                                @click="submitContacts"
                            />
                        </div>
                    </div>
                </template>

                <!-- Onglet Adresses -->
                <template #addresses>
                    <div class="mt-12 flex flex-col gap-6">
                        <SupplierAddressBlock
                            v-for="(address, index) in addresses"
                            :key="address.id ?? `new-${index}`"
                            :model-value="address"
                            :title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
                            :category-options="mainCategoryOptions"
                            :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.suppliers.form.address.add')"
                                :disabled="!canAddAddress"
                                @click="addAddress"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.suppliers.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.suppliers.form.accounting.siren')"
                                    :mask="SIREN_MASK"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.siren"
                                />
                                <MalioInputText
                                    v-model="accounting.accountNumber"
                                    :label="t('commercial.suppliers.form.accounting.accountNumber')"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.accountNumber"
                                />
                                <MalioSelect
                                    :model-value="accounting.tvaModeIri"
                                    :options="tvaModeOptions"
                                    :label="t('commercial.suppliers.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.suppliers.form.accounting.nTva')"
                                    :readonly="accountingReadonly"
                                    :required="true"
                                    :error="accountingErrors.errors.nTva"
                                />
                                <MalioSelect
                                    :model-value="accounting.paymentDelayIri"
                                    :options="paymentDelayOptions"
                                    :label="t('commercial.suppliers.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.suppliers.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.suppliers.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-2.08). -->
                        <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.suppliers.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.suppliers.form.accounting.ribLabel')"
                                    :readonly="accountingReadonly"
                                    :required="isRibRequired"
                                    :error="ribErrors[index]?.label"
                                />
                                <MalioInputText
                                    v-model="rib.bic"
                                    :label="t('commercial.suppliers.form.accounting.ribBic')"
                                    :readonly="accountingReadonly"
                                    :required="isRibRequired"
                                    :error="ribErrors[index]?.bic"
                                />
                                <MalioInputText
                                    v-model="rib.iban"
                                    :label="t('commercial.suppliers.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.suppliers.form.accounting.addRib')"
                                :disabled="!canAddRib"
                                @click="addRib"
                            />
                            <MalioButton
                                variant="primary"
                                :label="t('commercial.suppliers.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.suppliers.form.confirmDelete.title') }}</h2>
            </template>
            <p>{{ confirmModal.message }}</p>
            <template #footer>
                <MalioButton
                    variant="secondary"
                    button-class="flex-1"
                    :label="t('commercial.suppliers.form.confirmDelete.cancel')"
                    @click="confirmModal.open = false"
                />
                <MalioButton
                    variant="danger"
                    button-class="flex-1"
                    :label="t('commercial.suppliers.form.confirmDelete.confirm')"
                    @click="runConfirm"
                />
            </template>
        </MalioModal>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
import { useSupplierReferentials, type CategoryOption, type RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
import { useSupplierFormErrors } from '~/modules/commercial/composables/useSupplierFormErrors'
import {
    canEditSupplier,
    categoryOptionsOf,
    referentialOptionOf,
    siteOptionsOf,
    mapContactToDraft,
    mapAddressToDraft,
    mapRibToDraft,
    type SupplierDetail,
} from '~/modules/commercial/utils/forms/supplierConsultation'
import {
    buildAccountingPayload,
    buildAddressPayload,
    buildContactPayload,
    buildInformationPayload,
    buildMainPayload,
    buildRibPayload,
    mapAccountingFormDraft,
    mapInformationDraft,
    mapMainDraft,
    resolveTabEditability,
    type AccountingFormDraft,
    type InformationFormDraft,
    type MainFormDraft,
    type SupplierEditAbilities,
} from '~/modules/commercial/utils/forms/supplierEdit'
import {
    buildSupplierFormTabKeys,
    isAddressValid,
    isBankRequiredForPaymentType,
    isContactBlank,
    isContactNamed,
    isRibBlank,
    isRibComplete,
    isRibRequiredForPaymentType,
} from '~/modules/commercial/utils/forms/supplierFormRules'
import {
    emptyAddress,
    emptyContact,
    emptyRib,
    type SupplierAddressFormDraft,
    type SupplierContactFormDraft,
    type SupplierRibFormDraft,
} from '~/modules/commercial/types/supplierForm'
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 = '#######'
// Volume previsionnel : champ texte borne aux chiffres (entier >= 0 cote back).
const VOLUME_FORECAST_MASK = '##########'

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 (!canEditSupplier(canAny)) {
    await navigateTo('/suppliers')
}

const supplierId = route.params.id as string

const { supplier, loading, error, load } = useSupplier(supplierId)
const referentials = useSupplierReferentials()

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

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

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


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

/** Recopie le detail charge dans les brouillons editables. */
function hydrate(detail: SupplierDetail): 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*/canAdd*).
    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-2.08).
    if (isRibRequired.value && ribs.value.length === 0) ribs.value.push(emptyRib())
}

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

// Categories issues de l'embed (fournisseur + adresses), role-independantes.
const embedCategoryOptions = computed<CategoryOption[]>(() => {
    const fromSupplier = categoryOptionsOf(supplier.value?.categories)
    const fromAddresses = (supplier.value?.addresses ?? []).flatMap(a => categoryOptionsOf(a.categories))
    return mergeOptions(fromSupplier, fromAddresses)
})
// Toutes les categories de type FOURNISSEUR sont autorisees, sur le bloc principal
// comme sur une adresse (pas de restriction Distributeur/Courtier comme au M1 — RG-2.10).
const mainCategoryOptions = computed(() => mergeOptions(referentials.categories.value, embedCategoryOptions.value))

const embedSiteOptions = computed<RefOption[]>(() =>
    mergeOptions([], (supplier.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), aligne sur l'ecran
// client. 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'est plus au referentiel.
const embedCountryOptions = computed<RefOption[]>(() =>
    mergeOptions([], (supplier.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),
)

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

// ── Onglets : navigation libre (3 actifs + Compta + 4 coquilles) ────────────
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))

const TAB_ICONS: Record<string, string> = {
    information: 'mdi:account-outline',
    contacts: 'mdi:account-box-plus-outline',
    addresses: '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.suppliers.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: `/suppliers/${supplierId}`, 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.suppliers.toast.error')
}

function showError(e: unknown): void {
    toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(e) })
}

// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
const {
    mainErrors,
    informationErrors,
    accountingErrors,
    contactErrors,
    addressErrors,
    ribErrors,
    submitRows,
} = useSupplierFormErrors()

// ── Bloc principal ───────────────────────────────────────────────────────────
/** PATCH /suppliers/{id} — groupe supplier: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<SupplierDetail>(`/suppliers/${supplierId}`, buildMainPayload(main, { forUpdate: true }), {
            headers: { Accept: 'application/ld+json' },
            toast: false,
        })
        // Reaffiche les valeurs normalisees renvoyees par le serveur (UPPERCASE, RG-2.12).
        Object.assign(main, mapMainDraft(updated))
        toast.success({ title: t('commercial.suppliers.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.suppliers.form.duplicateCompany')
            mainErrors.setError('companyName', message)
            toast.error({ title: t('commercial.suppliers.toast.error'), message })
        }
        else {
            mainErrors.handleApiError(e, { fallbackMessage: t('commercial.suppliers.toast.error') })
        }
    }
    finally {
        mainSubmitting.value = false
    }
}

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

// ── Onglet Contacts ───────────────────────────────────────────────────────────
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.suppliers.form.confirmDelete.contact'), () => removeCollectionRow({
        rows: contacts.value,
        errors: contactErrors.value,
        index,
        endpoint: '/supplier_contacts',
        deleteRow: url => api.delete(url, {}, { toast: false }),
        makeEmpty: emptyContact,
        onError: showError,
    }))
}

/**
 * Valide l'onglet Contacts : POST/PATCH des blocs restants sur la sous-ressource.
 * Strictement scope a la collection contacts (endpoints supplier_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-2.13 : au moins un contact requis. Si l'onglet ne contient QUE des
        // amorces neuves vides, on les soumet -> 422 RG-2.04 inline (nom OU prenom).
        const hasSubmittableContact = contacts.value.some(c => c.id !== null || !isContactBlank(c))
        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 }>(
                        `/suppliers/${supplierId}/contacts`,
                        body,
                        { headers: { Accept: 'application/ld+json' }, toast: false },
                    )
                    contact.id = created.id
                    contact.iri = created['@id'] ?? null
                }
                else {
                    await api.patch(`/supplier_contacts/${contact.id}`, body, { toast: false })
                }
            },
            error => showError(error),
            contact => hasSubmittableContact && contact.id === null && isContactBlank(contact),
        )
        if (hasError) return
        toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
    }
    catch (e) {
        showError(e)
    }
    finally {
        tabSubmitting.value = false
    }
}

// ── Onglet Adresses ───────────────────────────────────────────────────────────
// « + 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.suppliers.form.confirmDelete.address'), () => removeCollectionRow({
        rows: addresses.value,
        errors: addressErrors.value,
        index,
        endpoint: '/supplier_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.suppliers.toast.error'),
        message: t('commercial.suppliers.form.address.degraded'),
    })
}

/** Valide l'onglet Adresses : 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 {
        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, { forUpdate: address.id !== null })
                if (address.id === null) {
                    const created = await api.post<{ id: number }>(
                        `/suppliers/${supplierId}/addresses`,
                        body,
                        { headers: { Accept: 'application/ld+json' }, toast: false },
                    )
                    address.id = created.id
                }
                else {
                    await api.patch(`/supplier_addresses/${address.id}`, body, { toast: false })
                }
            },
            error => showError(error),
        )
        if (hasError) return
        toast.success({ title: t('commercial.suppliers.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-2.08).
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 fournisseur, 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-2.08) -> 409 remonte via showError (message back), bloc conserve.
function askRemoveRib(index: number): void {
    askConfirm(t('commercial.suppliers.form.confirmDelete.rib'), () => removeCollectionRow({
        rows: ribs.value,
        errors: ribErrors.value,
        index,
        endpoint: '/supplier_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 supplier:write:accounting, exige accounting.manage
 * cote back) PUIS DELETE des RIB explicitement retires. Les RIB crees d'abord : le
 * back valide RG-2.08 (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-2.16 :
 * 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). 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).
        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 }>(
                            `/suppliers/${supplierId}/ribs`,
                            body,
                            { headers: { Accept: 'application/ld+json' }, toast: false },
                        )
                        rib.id = created.id
                    }
                    else {
                        await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
                    }
                },
                error => showError(error),
                rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
            )
            if (ribHasError) return
        }

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

        toast.success({ title: t('commercial.suppliers.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 (supplier.value) hydrate(supplier.value)
})
</script>
