<template>
  <div>
    <DocumentPreviewModal
      :document="previewDocument"
      :visible="previewVisible"
      :documents="componentDocuments"
      @close="closePreview"
    />
    <DocumentEditModal
      :visible="editModalVisible"
      :document="editingDocument"
      @close="editModalVisible = false"
      @updated="handleDocumentUpdated"
    />

    <!-- ═══ HEADER BAR ═══ -->
    <div
      class="group/header flex items-center gap-3 px-4 py-3 rounded-xl cursor-pointer select-none transition-all duration-200"
      :class="[
        component.pendingEntity
          ? 'bg-error/10 border border-error/40 hover:border-error/60'
          : 'bg-base-200/70 border border-base-300/30 hover:border-base-300/60 hover:bg-base-200',
        !isCollapsed ? 'sticky top-16 z-10 shadow-md ring-1 ring-base-300/20' : 'shadow-sm',
      ]"
      @click="toggleCollapse"
    >
      <!-- Chevron -->
      <div
        class="w-6 h-6 rounded-md grid place-items-center shrink-0 transition-all duration-200"
        :class="isCollapsed ? 'bg-base-300/40' : 'bg-primary/15'"
      >
        <IconLucideChevronRight
          class="w-3.5 h-3.5 transition-transform duration-200"
          :class="[
            isCollapsed ? 'text-base-content/40' : 'rotate-90 text-primary',
          ]"
          aria-hidden="true"
        />
      </div>

      <!-- Content -->
      <div class="flex-1 min-w-0 space-y-1.5">
        <!-- Row 1: Name + identifiers -->
        <div class="flex items-center gap-2 flex-wrap">
          <h3 class="text-sm font-bold tracking-tight truncate" :class="component.pendingEntity ? 'text-error' : 'text-base-content'">
            <NuxtLink
              v-if="!isEditMode && !component.pendingEntity && component.composantId"
              :to="machineId
                ? { path: `/component/${component.composantId}`, query: { from: 'machine', machineId } }
                : `/component/${component.composantId}`"
              class="hover:text-primary transition-colors"
              @click.stop
            >
              {{ component.name }}
            </NuxtLink>
            <span v-else>{{ component.name }}</span>
          </h3>
          <button
            v-if="component.pendingEntity"
            type="button"
            class="badge badge-error badge-sm cursor-pointer hover:badge-outline transition-colors"
            title="Cliquer pour associer un item"
            @click.stop="$emit('fill-entity', component.linkId, component.modelTypeId)"
          >
            À remplir
          </button>
          <span v-if="component.reference" class="text-[0.65rem] font-mono text-base-content/70 bg-base-300/50 px-1.5 py-0.5 rounded border border-base-300/40">{{ component.reference }}</span>
          <span v-if="component.referenceAuto" class="text-[0.65rem] font-mono font-semibold text-secondary bg-secondary/20 px-1.5 py-0.5 rounded border border-secondary/30" title="Référence auto">{{ component.referenceAuto }}</span>
          <span v-if="component.prix" class="text-[0.65rem] font-bold text-primary bg-primary/20 px-1.5 py-0.5 rounded border border-primary/30">{{ component.prix }}€</span>
        </div>

        <!-- Row 1.5: Machine context fields (badges plus gros, visibles en lecture ET en edition) -->
        <div
          v-if="visibleContextFieldTags.length"
          class="flex flex-wrap items-center gap-2"
        >
          <span
            v-for="field in visibleContextFieldTags"
            :key="field.name"
            class="inline-flex items-baseline gap-1.5 px-2.5 py-1 rounded-md"
            :class="contextFieldBadgeClass(field)"
          >
            <span class="text-[0.65rem] font-semibold uppercase tracking-wide opacity-70">{{ field.name }}</span>
            <span class="text-sm font-bold">{{ field.value }}</span>
          </span>
        </div>

        <!-- Row 2: Metadata tags -->
        <div
          v-if="componentConstructeursDisplay.length || displayProductName"
          class="flex flex-wrap items-center gap-1.5"
        >
          <span
            v-for="constructeur in componentConstructeursDisplay"
            :key="constructeur.id"
            class="text-[0.65rem] text-base-content/45"
          >
            {{ constructeur.name }}
            <span v-if="supplierReferenceMap.get(constructeur.id)" class="opacity-60">({{ supplierReferenceMap.get(constructeur.id) }})</span>
          </span>
          <span v-if="displayProductName" class="text-[0.65rem] font-semibold text-info bg-info/20 px-1.5 py-0.5 rounded border border-info/30">
            {{ displayProductName }}
          </span>
        </div>
      </div>

      <!-- Delete button -->
      <button
        v-if="showDelete"
        type="button"
        class="btn btn-ghost btn-xs btn-circle text-error opacity-0 group-hover/header:opacity-100 transition-opacity shrink-0"
        title="Supprimer ce composant"
        @click.stop="$emit('delete')"
      >
        <IconLucideTrash2 class="w-3.5 h-3.5" aria-hidden="true" />
      </button>
    </div>

    <!-- ═══ EXPANDED PANEL ═══ -->
    <div v-show="!isCollapsed && !component.pendingEntity" class="ml-[1.125rem] border-l-2 border-primary/30 pl-5 pt-3 pb-1 space-y-3">

      <!-- ── Section: Informations ── -->
      <div class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">Informations</p>
        </div>
        <div class="p-4">
          <!-- Edit mode -->
          <div v-if="isEditMode" class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div class="form-control">
              <label class="label py-0.5"><span class="label-text text-[0.65rem] font-semibold text-base-content/50 uppercase tracking-wide">Nom</span></label>
              <input v-model="component.name" type="text" class="input input-bordered input-sm" @blur="updateComponent">
            </div>
            <div class="form-control">
              <label class="label py-0.5"><span class="label-text text-[0.65rem] font-semibold text-base-content/50 uppercase tracking-wide">Référence</span></label>
              <input v-model="component.reference" type="text" class="input input-bordered input-sm" @blur="updateComponent">
            </div>
            <div class="form-control">
              <label class="label py-0.5"><span class="label-text text-[0.65rem] font-semibold text-base-content/50 uppercase tracking-wide">Prix</span></label>
              <input v-model="component.prix" type="number" step="0.01" class="input input-bordered input-sm" @blur="updateComponent">
            </div>
            <div class="form-control">
              <label class="label py-0.5"><span class="label-text text-[0.65rem] font-semibold text-base-content/50 uppercase tracking-wide">Fournisseur</span></label>
              <ConstructeurSelect
                class="w-full"
                :model-value="componentConstructeurIds"
                :initial-options="componentConstructeursDisplay"
                @update:model-value="handleConstructeurChange"
              />
            </div>
          </div>
          <!-- Read-only mode -->
          <div v-else class="grid grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-4">
            <div>
              <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/50 mb-1">Nom</p>
              <p class="text-sm text-base-content font-medium">{{ component.name }}</p>
            </div>
            <div>
              <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/50 mb-1">Référence</p>
              <p class="text-sm text-base-content" :class="component.reference ? 'font-mono' : 'text-base-content/30'">{{ component.reference || '—' }}</p>
            </div>
            <div v-if="component.referenceAuto">
              <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/50 mb-1">Réf. auto</p>
              <p class="text-sm text-base-content font-mono">{{ component.referenceAuto }}</p>
            </div>
            <div>
              <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/50 mb-1">Prix</p>
              <p class="text-sm" :class="component.prix ? 'text-base-content font-semibold' : 'text-base-content/30'">{{ component.prix ? `${component.prix} €` : '—' }}</p>
            </div>
            <div>
              <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/50 mb-1">Fournisseur</p>
              <div v-if="componentConstructeursDisplay.length" class="space-y-1">
                <p
                  v-for="constructeur in componentConstructeursDisplay"
                  :key="constructeur.id"
                  class="text-sm text-base-content"
                >
                  {{ constructeur.name }}
                  <span v-if="supplierReferenceMap.get(constructeur.id)" class="text-xs text-base-content/50">
                    — Réf. {{ supplierReferenceMap.get(constructeur.id) }}
                  </span>
                  <span v-if="formatConstructeurContact(constructeur)" class="text-[0.65rem] text-base-content/40 block">
                    {{ formatConstructeurContact(constructeur) }}
                  </span>
                </p>
              </div>
              <p v-else class="text-sm text-base-content/30">—</p>
            </div>
          </div>
        </div>
      </div>

      <!-- ── Section: Produit catalogue ── -->
      <div v-if="displayProduct" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-info/10 border-b border-info/20">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-info">Produit catalogue</p>
        </div>
        <div class="p-4">
          <div class="flex items-start justify-between gap-3">
            <div class="space-y-1.5">
              <p class="text-sm font-bold text-base-content">{{ displayProductName }}</p>
              <div class="flex flex-wrap gap-x-4 gap-y-1">
                <p
                  v-for="info in productInfoRows"
                  :key="info.label"
                  class="text-xs text-base-content/55"
                >
                  <span class="font-semibold">{{ info.label }}</span> : {{ info.value }}
                </p>
              </div>
            </div>
            <NuxtLink
              v-if="component.product?.id"
              :to="`/product/${component.product.id}`"
              class="btn btn-ghost btn-xs shrink-0 gap-1"
            >
              <IconLucideExternalLink class="w-3 h-3" aria-hidden="true" />
              Voir
            </NuxtLink>
          </div>
          <!-- Product documents -->
          <div v-if="productDocuments.length" class="mt-3 pt-3 border-t border-base-200/50 space-y-2">
            <p class="text-[0.6rem] font-semibold uppercase tracking-wide text-base-content/35">Documents du produit</p>
            <div
              v-for="document in productDocuments"
              :key="document.id || document.path || document.name"
              class="flex items-center justify-between gap-3 text-xs"
            >
              <div class="flex items-center gap-2 min-w-0">
                <div class="flex-shrink-0 overflow-hidden rounded border border-base-200 bg-base-200/70 flex items-center justify-center h-8 w-7">
                  <img
                    v-if="isImageDocument(document) && (document.fileUrl || document.path)"
                    :src="document.fileUrl || document.path"
                    class="h-full w-full object-cover"
                    :alt="`Aperçu de ${document.name}`"
                  >
                  <iframe
                    v-else-if="shouldInlinePdf(document)"
                    :src="documentPreviewSrc(document)"
                    class="h-full w-full border-0 bg-white"
                    title="Aperçu PDF"
                  />
                  <component
                    v-else
                    :is="documentIcon(document).component"
                    class="h-4 w-4"
                    :class="documentIcon(document).colorClass"
                    aria-hidden="true"
                  />
                </div>
                <span class="truncate text-base-content">{{ document.name }}</span>
              </div>
              <div class="flex items-center gap-1 shrink-0">
                <button
                  type="button"
                  class="btn btn-ghost btn-xs"
                  :disabled="!canPreviewDocument(document)"
                  @click="openPreview(document)"
                >
                  Consulter
                </button>
                <button type="button" class="btn btn-ghost btn-xs" @click="downloadDocument(document)">
                  Télécharger
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- ── Section: Champs personnalisés ── -->
      <div v-if="displayedCustomFields.length" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">Champs personnalisés item</p>
        </div>
        <div class="p-4">
          <CustomFieldDisplay
            :fields="displayedCustomFields"
            :is-edit-mode="isEditMode"
            :columns="2"
            :show-header="false"
            :with-top-border="false"
            :editable="false"
            @field-blur="updateComponentCustomField"
          />
        </div>
      </div>

      <div v-if="mergedContextFields.length" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-secondary/10 border-b border-secondary/20">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-secondary">Champs personnalisés machine</p>
        </div>
        <div class="p-4">
          <CustomFieldDisplay
            :fields="mergedContextFields"
            :is-edit-mode="isEditMode"
            :columns="2"
            :show-header="false"
            :with-top-border="false"
            :editable="true"
            :emit-blur="false"
            @field-input="queueContextCustomFieldUpdate"
          />
        </div>
      </div>

      <!-- ── Section: Documents ── -->
      <div class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50 flex items-center justify-between">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">Documents</p>
          <span v-if="isEditMode && selectedFiles.length" class="badge badge-outline badge-xs">
            {{ selectedFiles.length }} fichier{{ selectedFiles.length > 1 ? 's' : '' }}
          </span>
        </div>
        <div class="p-4 space-y-3">
          <p v-if="loadingDocuments" class="text-xs text-base-content/50">Chargement...</p>

          <DocumentUpload
            v-if="isEditMode"
            v-model="selectedFiles"
            title="Déposer des fichiers pour ce composant"
            subtitle="Formats acceptés : PDF, images, documents..."
            @files-added="handleFilesAdded"
          />

          <DocumentListInline
            :documents="componentDocuments"
            :can-delete="isEditMode"
            :can-edit="isEditMode"
            :delete-disabled="uploadingDocuments"
            empty-text="Aucun document lié à ce composant."
            @preview="openPreview"
            @edit="openEditModal"
            @delete="removeDocument"
          />
        </div>
      </div>

      <!-- ── Section: Pièces du composant ── -->
      <div v-if="linkedPieces.length > 0" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">
            Pièces du composant
            <span class="ml-1 text-base-content/25">({{ linkedPieces.length }})</span>
          </p>
        </div>
        <div class="p-3 space-y-2">
          <PieceItem
            v-for="piece in linkedPieces"
            :key="piece.id"
            :piece="piece"
            :is-edit-mode="isEditMode"
            @update="updatePiece"
            @edit="editPiece"
            @custom-field-update="updatePieceCustomField"
            @fill-entity="(linkId, typeId) => $emit('fill-entity', linkId, typeId)"
          />
        </div>
      </div>

      <!-- ── Section: Pièces structure ── -->
      <div v-if="structurePieces.length > 0" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">
            Pièces incluses par défaut
            <span class="ml-1 text-base-content/25">({{ structurePieces.length }})</span>
          </p>
        </div>
        <div class="p-3 space-y-2">
          <PieceItem
            v-for="piece in structurePieces"
            :key="piece.id"
            :piece="piece"
            :is-edit-mode="false"
          />
        </div>
      </div>

      <!-- ── Section: Sous-composants ── -->
      <div v-if="childComponents.length > 0" class="rounded-xl bg-base-100 border border-base-200/60 overflow-hidden">
        <div class="px-4 py-2 bg-base-200/30 border-b border-base-200/50">
          <p class="text-[0.6rem] font-bold uppercase tracking-[0.15em] text-base-content/50">
            Sous-composants
            <span class="ml-1 text-base-content/25">({{ childComponents.length }})</span>
          </p>
        </div>
        <div class="p-3 space-y-2">
          <ComponentItem
            v-for="subComponent in childComponents"
            :key="subComponent.id"
            :component="subComponent"
            :is-edit-mode="isEditMode"
            :collapse-all="collapseAll"
            :toggle-token="toggleToken"
            @update="$emit('update', $event)"
            @edit-piece="$emit('edit-piece', $event)"
            @custom-field-update="$emit('custom-field-update', $event)"
            @fill-entity="(linkId, typeId) => $emit('fill-entity', linkId, typeId)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import PieceItem from './PieceItem.vue'
import DocumentUpload from './DocumentUpload.vue'
import ConstructeurSelect from './ConstructeurSelect.vue'
import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue'
import IconLucideChevronRight from '~icons/lucide/chevron-right'
import IconLucideTrash2 from '~icons/lucide/trash-2'
import IconLucideExternalLink from '~icons/lucide/external-link'
import { canPreviewDocument, isImageDocument } from '~/utils/documentPreview'
import { useConstructeurs } from '~/composables/useConstructeurs'
import {
  formatConstructeurContact as formatConstructeurContactSummary,
  resolveConstructeurs,
  uniqueConstructeurIds,
  parseConstructeurLinksFromApi,
} from '~/shared/constructeurUtils'
import {
  shouldInlinePdf,
  documentPreviewSrc,
  documentIcon,
  downloadDocument,
} from '~/shared/utils/documentDisplayUtils'
import { useEntityDocuments } from '~/composables/useEntityDocuments'
import { useEntityProductDisplay } from '~/composables/useEntityProductDisplay'
import { useCustomFields } from '~/composables/useCustomFields'
import { mergeDefinitionsWithValues } from '~/shared/utils/customFields'

const route = useRoute()
const machineId = computed(() => route.params.id as string | undefined)

const props = defineProps({
  component: { type: Object, required: true },
  isEditMode: { type: Boolean, default: false },
  showDelete: { type: Boolean, default: false },
  collapseAll: { type: Boolean, default: true },
  toggleToken: { type: Number, default: 0 },
})

const emit = defineEmits(['update', 'edit-piece', 'custom-field-update', 'delete', 'fill-entity'])

// --- Shared composables ---
const {
  documents: componentDocuments,
  selectedFiles,
  uploadingDocuments,
  loadingDocuments,
  previewDocument,
  previewVisible,
  openPreview,
  closePreview,
  ensureDocumentsLoaded,
  handleFilesAdded,
  removeDocument,
  editDocument,
} = useEntityDocuments({ entity: () => props.component, entityType: 'composant' })

const {
  displayProduct,
  displayProductName,
  productInfoRows,
  productDocuments,
} = useEntityProductDisplay({ entity: () => props.component })

const {
  updateCustomFieldValue: updateCustomFieldValueApi,
  upsertCustomFieldValue,
} = useCustomFields()
const { showSuccess, showError } = useToast()

// Parent already pre-merges standalone custom fields into props.component.customFields
const displayedCustomFields = computed(() => {
  const fields = props.component?.customFields
  return Array.isArray(fields) ? fields.filter((f) => !f.machineContextOnly) : []
})

const updateComponentCustomField = async (field) => {
  if (!field || field.readOnly) return

  const e = props.component
  const fieldValueId = field.customFieldValueId

  if (fieldValueId) {
    const result = await updateCustomFieldValueApi(fieldValueId, { value: field.value ?? '' })
    if (result.success) {
      showSuccess(`Champ "${field.name}" mis à jour avec succès`)
    } else {
      showError(`Erreur lors de la mise à jour du champ "${field.name}"`)
    }
    return
  }

  if (!e?.id) {
    showError('Impossible de créer la valeur pour ce champ')
    return
  }

  const metadata = field.customFieldId ? undefined : {
    customFieldName: field.name,
    customFieldType: field.type,
    customFieldRequired: field.required,
    customFieldOptions: field.options,
  }
  const result = await upsertCustomFieldValue(
    field.customFieldId,
    'composant',
    e.id,
    field.value ?? '',
    metadata,
  )

  if (result.success) {
    const newValue = result.data
    if (newValue?.id) {
      field.customFieldValueId = newValue.id
      field.value = newValue.value ?? field.value ?? ''
      if (newValue.customField?.id) {
        field.customFieldId = newValue.customField.id
      }
    }
    showSuccess(`Champ "${field.name}" créé avec succès`)
  } else {
    showError(`Erreur lors de la sauvegarde du champ "${field.name}"`)
  }
}

// Context fields are NOT pre-merged — merge locally
const mergedContextFields = computed(() => {
  const definitions = props.component?.contextCustomFields ?? []
  const values = props.component?.contextCustomFieldValues ?? []
  if (!definitions.length && !values.length) return []
  return mergeDefinitionsWithValues(definitions, values)
})

// Context fields shown as tags on the header (consultation mode)
const visibleContextFieldTags = computed(() =>
  mergedContextFields.value.filter(f => f.value !== null && f.value !== undefined && String(f.value).trim() !== ''),
)

const CONTEXT_FIELD_COLORS = [
  'bg-secondary/25 text-secondary border border-secondary/35',
  'bg-accent/25 text-accent border border-accent/35',
  'bg-info/25 text-info border border-info/35',
  'bg-success/25 text-success border border-success/35',
  'bg-warning/25 text-warning border border-warning/35',
]

const contextFieldBadgeClass = (field: any) => {
  const idx = visibleContextFieldTags.value.indexOf(field)
  return CONTEXT_FIELD_COLORS[idx % CONTEXT_FIELD_COLORS.length]
}

const queueContextCustomFieldUpdate = (field, value) => {
  const linkId = props.component?.linkId
  if (!linkId || !field) return

  const customFieldId = field.customFieldId
  const customFieldValueId = field.customFieldValueId
  if (!customFieldId && !customFieldValueId) return

  field.value = value
  emit('custom-field-update', {
    entityType: 'machineComponentLink',
    entityId: linkId,
    fieldId: customFieldId,
    customFieldValueId,
    value: value ?? '',
    fieldName: field.name || 'Champ contextuel',
  })
}

// --- Document edit modal ---
const editingDocument = ref(null)
const editModalVisible = ref(false)

const openEditModal = (doc) => {
  editingDocument.value = doc
  editModalVisible.value = true
}
const handleDocumentUpdated = async (data) => {
  if (!editingDocument.value?.id) return
  await editDocument(editingDocument.value.id, data)
  editModalVisible.value = false
  editingDocument.value = null
}

// --- Collapse state ---
const isCollapsed = ref(true)

watch(
  () => props.toggleToken,
  () => {
    isCollapsed.value = props.collapseAll
    if (!isCollapsed.value) ensureDocumentsLoaded()
  },
  { immediate: true },
)

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  if (!isCollapsed.value) ensureDocumentsLoaded()
}

// --- Child components ---
const childComponents = computed(() => {
  const list = props.component.subcomponents || props.component.subComponents || []
  return Array.isArray(list) ? list : []
})

// --- Pieces split: real links vs structure definitions ---
const allPieces = computed(() => {
  const list = props.component.pieces
  return Array.isArray(list) ? list : []
})
const linkedPieces = computed(() => allPieces.value.filter((p) => !p._structurePiece))
const structurePieces = computed(() => allPieces.value.filter((p) => p._structurePiece))

// --- Constructeurs ---
const { constructeurs } = useConstructeurs()

const componentConstructeurLinks = computed(() =>
  parseConstructeurLinksFromApi(
    Array.isArray(props.component.constructeurs) ? props.component.constructeurs : [],
  ),
)

const supplierReferenceMap = computed(() => {
  const map = new Map()
  componentConstructeurLinks.value.forEach(l => {
    if (l.supplierReference) map.set(l.constructeurId, l.supplierReference)
  })
  return map
})

const componentConstructeurIds = computed(() =>
  componentConstructeurLinks.value.map(l => l.constructeurId).filter(Boolean),
)

const componentConstructeursDisplay = computed(() => {
  // Extract nested constructeur objects from link entries
  const linkConstructeurs = componentConstructeurLinks.value
    .filter(l => l.constructeur && l.constructeur.id)
    .map(l => l.constructeur)
  return resolveConstructeurs(
    componentConstructeurIds.value,
    linkConstructeurs,
    constructeurs.value,
  )
})

const formatConstructeurContact = (constructeur) =>
  formatConstructeurContactSummary(constructeur)

const handleConstructeurChange = async (value) => {
  const ids = uniqueConstructeurIds(value)
  props.component.constructeurIds = [...ids]
  props.component.constructeurId = null
  props.component.constructeur = null
  props.component.constructeurs = resolveConstructeurs(
    ids,
    constructeurs.value,
    Array.isArray(props.component.constructeurs) ? props.component.constructeurs : [],
  )
  await updateComponent()
}

// --- Update / Event forwarding ---
const updateComponent = () => {
  emit('update', {
    ...props.component,
    constructeurIds: componentConstructeurIds.value,
  })
}

const updatePiece = (updatedPiece) => {
  emit('edit-piece', updatedPiece)
}

const editPiece = (piece) => {
  emit('edit-piece', piece)
}

const updatePieceCustomField = (fieldUpdate) => {
  emit('custom-field-update', fieldUpdate)
  emit('edit-piece', { ...fieldUpdate, type: 'custom-field-update' })
}
</script>
