@php
    $hasValue = function ($value) {
        return !($value === null || $value === '' || (is_array($value) && count($value) === 0));
    };
    $format = function ($field, $value) {
        if ($field['type'] === 'checkbox') {
            return $value ? 'Yes' : 'No';
        }
        if ($field['type'] === 'date' && $value) {
            try {
                return \Illuminate\Support\Carbon::parse($value)->format('d/m/Y');
            } catch (\Throwable $e) {
                return $value;
            }
        }
        if (is_array($value)) {
            return implode(', ', $value);
        }
        return $value;
    };

    $scalarFields = collect($fields)
        ->reject(fn ($field) => in_array($field['type'], ['textarea', 'repeater', 'multiselect']))
        ->filter(fn ($field) => $hasValue($data[$field['key']] ?? null));
    $blockFields = collect($fields)
        ->filter(fn ($field) => in_array($field['type'], ['textarea', 'repeater', 'multiselect']));
@endphp

@if ($scalarFields->isNotEmpty())
    <div class="table-wrap">
        <table class="table">
            <tbody>
                @foreach ($scalarFields as $field)
                    <tr>
                        <td><strong>{{ $field['label'] }}</strong></td>
                        <td>{{ $format($field, $data[$field['key']] ?? null) }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
@endif

@foreach ($blockFields as $field)
    @php $value = $data[$field['key']] ?? null; @endphp
    @continue(!$hasValue($value))

    @if ($field['type'] === 'textarea')
        {{-- A "full" editor is the whole section body; the section already has its own
             heading and the author writes headings inside, so skip the field sub-heading. --}}
        @if (empty($field['full']))
            <h3>{{ $field['label'] }}</h3>
        @endif
        {{-- Rich text authored by mtc admins in the editor; rendered as saved HTML. --}}
        <div class="doc-richtext">{!! $value !!}</div>
    @elseif ($field['type'] === 'multiselect')
        <h3>{{ $field['label'] }}</h3>
        <ul class="bullets">
            @foreach ($value as $item)
                <li>{{ $item }}</li>
            @endforeach
        </ul>
    @elseif ($field['type'] === 'repeater')
        @php
            $childFields = $field['fields'] ?? [];
            $rows = is_array($value) ? $value : [];
            // Some repeaters are pre-seeded (e.g. one integration per type); only show
            // rows that have been filled in (preview_key set) in the client-facing doc.
            if (!empty($field['preview_key'])) {
                $rows = array_values(array_filter(
                    $rows,
                    fn ($row) => is_array($row) && !empty($row[$field['preview_key']] ?? null)
                ));
            }
            // A flat table only works when every column is a simple scalar. If any child
            // is rich text / a list / a nested repeater, render each entry as a sub-block
            // so that content renders properly (not as escaped HTML in a cell).
            $hasComplexChild = collect($childFields)
                ->contains(fn ($child) => in_array($child['type'], ['textarea', 'multiselect', 'repeater']));
            $itemLabel = $field['item_label'] ?? $field['label'];
        @endphp
        @if (count($rows))
            <h3>{{ $field['label'] }}</h3>
            @if ($hasComplexChild)
                @foreach ($rows as $index => $row)
                    <h4>{{ $itemLabel }} {{ $index + 1 }}</h4>
                    @include('spec-document._fields', ['fields' => $childFields, 'data' => is_array($row) ? $row : []])
                @endforeach
            @else
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                            <tr>
                                @foreach ($childFields as $child)
                                    <th>{{ $child['label'] }}</th>
                                @endforeach
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($rows as $row)
                                <tr>
                                    @foreach ($childFields as $child)
                                        <td>{{ $format($child, is_array($row) ? ($row[$child['key']] ?? null) : null) }}</td>
                                    @endforeach
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        @endif
    @endif
@endforeach
