@php
    $hideLabel = $hideLabel ?? false;
    $wrapperClass = $wrapperClass ?? '';
    $fieldKey = 'field_'.$field->id;
    $columns = $field->tableColumns();
    $rowsData = $value ?? [];

    if (is_string($rowsData)) {
        $rowsData = json_decode($rowsData, true) ?? [];
    }
    if (! is_array($rowsData)) {
        $rowsData = [];
    }
    if (empty($rowsData) && ! $readOnly) {
        $emptyRow = [];
        foreach ($columns as $ci => $col) {
            $emptyRow['col_'.$ci] = '';
        }
        $rowsData = [$emptyRow];
    }

    $theadBg = $readOnly ? 'bg-slate-50' : 'bg-transtev-50';
    $thCell = $readOnly ? 'px-4 py-2' : 'px-3 py-2';
    $tdCell = $readOnly ? 'px-4 py-2' : 'px-2 py-2';
@endphp

<div class="{{ $hideLabel ? '' : 'mb-5' }}" @if(! $readOnly) x-data="tableField(@js($columns), @js($rowsData), '{{ $fieldKey }}')" @endif>
    @unless($hideLabel)
        <label class="block text-sm font-medium text-slate-700 mb-2">
            {{ $field->label }}
            @if($field->required && ! $readOnly)<span class="text-red-500">*</span>@endif
        </label>
        @if(!empty($field->description))
            <p class="text-xs text-slate-500 mb-3 -mt-1">{{ $field->description }}</p>
        @endif
    @endunless

    <div class="table-scroll-wrap {{ $wrapperClass }}">
        <table>
            <thead class="{{ $theadBg }}">
                <tr>
                    @foreach($columns as $col)
                        <th class="{{ $thCell }} text-left font-semibold text-slate-600 whitespace-nowrap {{ $theadBg }} min-w-[120px]">{{ $col['label'] }}</th>
                    @endforeach
                    @unless($readOnly)
                        <th class="px-2 py-2 w-16 {{ $theadBg }}"></th>
                    @endunless
                </tr>
            </thead>
            <tbody class="{{ $readOnly ? 'divide-y divide-slate-100' : '' }}">
                @if($readOnly)
                    @forelse($rowsData as $row)
                        <tr>
                            @foreach($columns as $ci => $col)
                                @php $cell = $row['col_'.$ci] ?? null; @endphp
                                <td class="{{ $tdCell }} text-slate-700 min-w-[120px] align-top">
                                    @if($col['type'] === 'file')
                                        <x-file-preview :path="$cell" compact />
                                    @else
                                        {{ $cell ?: '—' }}
                                    @endif
                                </td>
                            @endforeach
                        </tr>
                    @empty
                        <tr>
                            <td colspan="{{ max(count($columns), 1) }}" class="px-4 py-4 text-slate-400 text-center">Aucune ligne</td>
                        </tr>
                    @endforelse
                @else
                    <template x-for="(row, rowIndex) in rows" :key="rowIndex">
                        <tr class="border-t border-slate-100">
                            <template x-for="(col, colIndex) in columns" :key="colIndex">
                                <td class="{{ $tdCell }} align-top min-w-[120px]">
                                    <template x-if="col.type === 'textarea'">
                                        <textarea :name="fieldKey + '[rows][' + rowIndex + '][col_' + colIndex + ']'" x-model="row['col_' + colIndex]" rows="2" class="input-modern text-sm w-full min-w-[100px]"></textarea>
                                    </template>
                                    <template x-if="col.type === 'select'">
                                        <select :name="fieldKey + '[rows][' + rowIndex + '][col_' + colIndex + ']'" x-model="row['col_' + colIndex]" class="input-modern text-sm w-full min-w-[100px]">
                                            <option value="">—</option>
                                            <template x-for="opt in (col.options || [])" :key="opt">
                                                <option :value="opt" x-text="opt"></option>
                                            </template>
                                        </select>
                                    </template>
                                    <template x-if="col.type === 'file'">
                                        <div class="space-y-1 min-w-[160px]">
                                            <template x-if="row['col_' + colIndex]">
                                                <a :href="'{{ route('files.show') }}?path=' + encodeURIComponent(row['col_' + colIndex]) + '&d=attachment'" class="file-preview-link file-preview-link--muted text-xs block truncate max-w-[160px]">
                                                    <span x-text="baseName(row['col_' + colIndex])"></span>
                                                </a>
                                            </template>
                                            <label class="file-dropzone file-dropzone--sm" :class="localFiles[rowIndex + '_' + colIndex] ? 'file-dropzone--filled' : ''">
                                                <svg class="file-dropzone-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M21.44 11.05 12.25 20.24a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.49"/></svg>
                                                <span class="file-dropzone-text">
                                                    <template x-if="! localFiles[rowIndex + '_' + colIndex]">
                                                        <span class="file-dropzone-accent">Choisir un fichier</span>
                                                    </template>
                                                    <template x-if="localFiles[rowIndex + '_' + colIndex]">
                                                        <span class="file-dropzone-filename" x-text="localFiles[rowIndex + '_' + colIndex]"></span>
                                                    </template>
                                                </span>
                                                <input type="file" :name="fieldKey + '[rows][' + rowIndex + '][col_' + colIndex + ']'" class="sr-only" @change="pickFile(rowIndex, colIndex, $event)">
                                            </label>
                                        </div>
                                    </template>
                                    <template x-if="!['textarea','select','file'].includes(col.type)">
                                        <input :type="col.type === 'number' ? 'number' : (col.type === 'date' ? 'date' : 'text')"
                                            :name="fieldKey + '[rows][' + rowIndex + '][col_' + colIndex + ']'"
                                            x-model="row['col_' + colIndex]"
                                            class="input-modern text-sm w-full min-w-[100px]">
                                    </template>
                                </td>
                            </template>
                            <td class="px-2 py-2 align-top w-16">
                                <button type="button" @click="removeRow(rowIndex)" class="text-red-500 text-xs hover:underline mt-2 whitespace-nowrap" x-show="rows.length > 1">Suppr.</button>
                            </td>
                        </tr>
                    </template>
                @endif
            </tbody>
        </table>
    </div>

    @unless($readOnly)
        <button type="button" @click="addRow()" class="mt-3 inline-flex items-center gap-1 text-sm font-medium text-transtev-600 hover:text-transtev-700">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
            Ajouter une ligne
        </button>
    @endunless

    @unless($hideLabel)
        @error($fieldKey)
            <p class="mt-1.5 text-sm text-red-600">{{ $message }}</p>
        @enderror
        @error($fieldKey.'.*')
            <p class="mt-1.5 text-sm text-red-600">{{ $message }}</p>
        @enderror
    @endunless
</div>

@once
<script>
function tableField(columns, initialRows, fieldKey) {
    const emptyRow = () => {
        const row = {};
        columns.forEach((_, i) => { row['col_' + i] = ''; });
        return row;
    };
    return {
        columns,
        fieldKey,
        rows: initialRows.length ? JSON.parse(JSON.stringify(initialRows)) : [emptyRow()],
        localFiles: {},
        addRow() {
            this.rows.push(emptyRow());
        },
        removeRow(index) {
            if (this.rows.length > 1) this.rows.splice(index, 1);
        },
        pickFile(rowIndex, colIndex, event) {
            const file = event.target.files[0];
            this.localFiles[rowIndex + '_' + colIndex] = file ? file.name : '';
        },
        baseName(path) {
            return path ? String(path).split('/').pop() : '';
        },
    };
}
</script>
@endonce
