@php
    $mode = $mode ?? 'show';
    $layout = $layout ?? 'card';
    $attachments = $attachments ?? ($voucher->attachments ?? collect());
    $canUpload = isset($voucher)
        ? app(\App\Services\VoucherAttachmentService::class)->canUpload(auth()->user(), $voucher)
        : auth()->user()->hasPermission('vouchers', 'create');
    $canView = auth()->user()->hasPermission('vouchers', 'view');
    $attachmentService = app(\App\Services\VoucherAttachmentService::class);
    $allowedExtensions = implode(', ', array_map('strtoupper', config('attachments.allowed_extensions', [])));
    $maxMb = round(((int) config('attachments.max_size_kb', 10240)) / 1024, 1);
    $isInline = $layout === 'inline';
@endphp

@if($canView || $canUpload)
@if($isInline)
<div class="voucher-attachments-inline" id="voucherAttachmentsCard">
    <div class="voucher-attachments-inline-head">
        <span class="voucher-attachments-inline-title">
            <i class="bi bi-paperclip me-1 text-primary"></i>Attach Documents
        </span>
        @if($attachments->count())
            <span class="badge bg-light text-dark border">{{ $attachments->count() }}</span>
        @endif
    </div>

    @if($canUpload && in_array($mode, ['create', 'edit'], true))
        <input type="file"
               name="attachments[]"
               class="form-control form-control-sm voucher-attachment-input"
               multiple
               accept=".{{ implode(',.', config('attachments.allowed_extensions', [])) }}">
        <div class="form-text voucher-attachments-inline-hint">
            {{ $allowedExtensions }} up to {{ $maxMb }} MB each. Files upload when you save the voucher.
        </div>
        <div class="voucher-attachment-pending-list d-none" id="voucherAttachmentPendingList"></div>
    @endif

    @if($mode === 'show' && $canUpload && isset($voucher))
        <form method="POST"
              action="{{ route('vouchers.attachments.store', [$voucherType, $voucher]) }}"
              enctype="multipart/form-data"
              class="voucher-attachment-upload-form"
              id="voucherAttachmentUploadForm">
            @csrf
            <div class="d-flex flex-wrap gap-2 align-items-center">
                <input type="file"
                       name="attachments[]"
                       class="form-control form-control-sm voucher-attachment-input"
                       multiple
                       accept=".{{ implode(',.', config('attachments.allowed_extensions', [])) }}">
                <button type="submit" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-upload me-1"></i>Upload
                </button>
            </div>
            <div class="form-text voucher-attachments-inline-hint">
                {{ $allowedExtensions }} up to {{ $maxMb }} MB each.
            </div>
        </form>
    @endif

    <div id="voucherAttachmentList" class="voucher-attachments-inline-list">
        @if($attachments->isEmpty())
            <div class="text-muted voucher-attachments-inline-empty" id="voucherAttachmentEmpty">
                <i class="bi bi-inbox me-1"></i>No documents attached yet.
            </div>
        @else
            <div class="table-responsive">
                <table class="table table-sm mb-0 voucher-attachment-table">
                    <thead class="table-light">
                        <tr>
                            <th>File</th>
                            <th class="d-none d-md-table-cell">Description</th>
                            <th class="d-none d-lg-table-cell">Uploaded By</th>
                            <th class="d-none d-lg-table-cell">Date</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($attachments as $attachment)
                            @include('accounting.vouchers._attachment_row', [
                                'attachment' => $attachment,
                                'voucher' => $voucher,
                                'voucherType' => $voucherType,
                                'attachmentService' => $attachmentService,
                            ])
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</div>
@else
<div class="card mb-4" id="voucherAttachmentsCard">
    <div class="card-header fw-semibold d-flex align-items-center justify-content-between">
        <span><i class="bi bi-paperclip me-2 text-primary"></i>Documents</span>
        @if($attachments->count())
            <span class="badge bg-light text-dark border">{{ $attachments->count() }}</span>
        @endif
    </div>
    <div class="card-body">
        @if($canUpload && in_array($mode, ['create', 'edit'], true))
            <div class="mb-3">
                <label class="form-label fw-semibold">Attach Documents</label>
                <input type="file"
                       name="attachments[]"
                       class="form-control form-control-sm voucher-attachment-input"
                       multiple
                       accept=".{{ implode(',.', config('attachments.allowed_extensions', [])) }}">
                <div class="form-text" style="font-size:11.5px">
                    {{ $allowedExtensions }} up to {{ $maxMb }} MB each. Files upload when you save the voucher.
                </div>
            </div>
            <div class="voucher-attachment-pending-list mb-3 d-none" id="voucherAttachmentPendingList"></div>
        @endif

        @if($mode === 'show' && $canUpload && isset($voucher))
            <form method="POST"
                  action="{{ route('vouchers.attachments.store', [$voucherType, $voucher]) }}"
                  enctype="multipart/form-data"
                  class="voucher-attachment-upload-form mb-3"
                  id="voucherAttachmentUploadForm">
                @csrf
                <label class="form-label fw-semibold">Add Documents</label>
                <div class="d-flex flex-wrap gap-2 align-items-center">
                    <input type="file"
                           name="attachments[]"
                           class="form-control form-control-sm voucher-attachment-input"
                           style="max-width:320px"
                           multiple
                           accept=".{{ implode(',.', config('attachments.allowed_extensions', [])) }}">
                    <button type="submit" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-upload me-1"></i>Upload
                    </button>
                </div>
                <div class="form-text" style="font-size:11.5px">
                    {{ $allowedExtensions }} up to {{ $maxMb }} MB each.
                </div>
            </form>
        @endif

        <div id="voucherAttachmentList">
            @if($attachments->isEmpty())
                <div class="text-muted" style="font-size:13px" id="voucherAttachmentEmpty">
                    <i class="bi bi-inbox me-1"></i>No documents attached yet.
                </div>
            @else
                <div class="table-responsive">
                    <table class="table table-sm mb-0 voucher-attachment-table" style="font-size:13px">
                        <thead class="table-light">
                            <tr>
                                <th>File</th>
                                <th class="d-none d-md-table-cell">Description</th>
                                <th class="d-none d-lg-table-cell">Uploaded By</th>
                                <th class="d-none d-lg-table-cell">Date</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($attachments as $attachment)
                                @include('accounting.vouchers._attachment_row', [
                                    'attachment' => $attachment,
                                    'voucher' => $voucher,
                                    'voucherType' => $voucherType,
                                    'attachmentService' => $attachmentService,
                                ])
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        </div>
    </div>
</div>
@endif
@endif

@if(in_array($mode, ['create', 'edit', 'show'], true))
@push('scripts')
<script>
(function () {
    const pendingList = document.getElementById('voucherAttachmentPendingList');
    document.querySelectorAll('.voucher-attachment-input').forEach((input) => {
        input.addEventListener('change', () => {
            if (!pendingList) return;
            const files = Array.from(input.files || []);
            if (!files.length) {
                pendingList.classList.add('d-none');
                pendingList.innerHTML = '';
                return;
            }
            pendingList.classList.remove('d-none');
            pendingList.innerHTML = files.map((file) => (
                `<div class="d-flex align-items-center gap-2 py-1" style="font-size:12.5px">
                    <i class="bi bi-file-earmark text-primary"></i>
                    <span>${file.name}</span>
                    <span class="text-muted">(${Math.max(1, Math.round(file.size / 1024))} KB)</span>
                </div>`
            )).join('');
        });
    });

    const uploadForm = document.getElementById('voucherAttachmentUploadForm');
    if (uploadForm) {
        uploadForm.addEventListener('submit', async (event) => {
            event.preventDefault();
            const fileInput = uploadForm.querySelector('input[type="file"]');
            if (!fileInput || !fileInput.files.length) {
                alert('Please choose at least one file.');
                return;
            }

            const submitBtn = uploadForm.querySelector('button[type="submit"]');
            const originalHtml = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Uploading…';

            try {
                const response = await fetch(uploadForm.action, {
                    method: 'POST',
                    body: new FormData(uploadForm),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json',
                    },
                });

                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.message || 'Upload failed.');
                }

                const list = document.getElementById('voucherAttachmentList');
                const empty = document.getElementById('voucherAttachmentEmpty');
                if (empty) empty.remove();

                let tbody = list.querySelector('tbody');
                if (!tbody) {
                    list.innerHTML = `
                        <div class="table-responsive">
                            <table class="table table-sm mb-0 voucher-attachment-table" style="font-size:13px">
                                <thead class="table-light">
                                    <tr>
                                        <th>File</th>
                                        <th class="d-none d-md-table-cell">Description</th>
                                        <th class="d-none d-lg-table-cell">Uploaded By</th>
                                        <th class="d-none d-lg-table-cell">Date</th>
                                        <th class="text-end">Actions</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>`;
                    tbody = list.querySelector('tbody');
                }

                (data.attachments || []).forEach((item) => {
                    const tr = document.createElement('tr');
                    tr.dataset.attachmentId = item.id;
                    tr.innerHTML = `
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <i class="bi ${item.is_pdf ? 'bi-file-earmark-pdf text-danger' : (item.is_image ? 'bi-file-earmark-image text-primary' : 'bi-file-earmark text-secondary')}"></i>
                                <div>
                                    <div class="fw-semibold">${item.file_name}</div>
                                    <div class="text-muted" style="font-size:11.5px">${item.file_size_human}</div>
                                </div>
                            </div>
                        </td>
                        <td class="d-none d-md-table-cell text-muted">${item.description || '—'}</td>
                        <td class="d-none d-lg-table-cell text-muted">${item.uploaded_by || '—'}</td>
                        <td class="d-none d-lg-table-cell text-muted">${item.created_at || '—'}</td>
                        <td class="text-end">
                            <a href="${item.download_url}" class="btn btn-link btn-sm p-0 me-2">Download</a>
                            <button type="button" class="btn btn-link btn-sm text-danger p-0 voucher-attachment-delete" data-url="${item.delete_url}">Remove</button>
                        </td>`;
                    tbody.prepend(tr);
                });

                uploadForm.reset();
                fileInput.value = '';
            } catch (error) {
                alert(error.message || 'Upload failed.');
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHtml;
            }
        });
    }

    document.addEventListener('click', async (event) => {
        const btn = event.target.closest('.voucher-attachment-delete');
        if (!btn) return;
        if (!confirm('Remove this document?')) return;

        const row = btn.closest('tr');
        const url = btn.dataset.url;
        btn.disabled = true;

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                },
                body: new URLSearchParams({ _method: 'DELETE' }),
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.message || 'Delete failed.');
            row?.remove();
            const tbody = document.querySelector('#voucherAttachmentList tbody');
            if (tbody && !tbody.children.length) {
                document.getElementById('voucherAttachmentList').innerHTML =
                    '<div class="text-muted voucher-attachments-inline-empty" style="font-size:13px" id="voucherAttachmentEmpty"><i class="bi bi-inbox me-1"></i>No documents attached yet.</div>';
            }
        } catch (error) {
            alert(error.message || 'Delete failed.');
            btn.disabled = false;
        }
    });
})();
</script>
@endpush
@endif
