<!-- resources/views/livewire/file-attachment-manager.blade.php -->
<div>
    <style>
        :root {
            --primary-color: #4361ee;
            --primary-light: #edf2ff;
            --text-primary: #2d3748;
            --text-secondary: #718096;
            --border-color: #e2e8f0;
            --hover-bg: #f7fafc;
            --body-bg: #f8fafc;
            --card-bg: #ffffff;
        }
        
        [data-theme="dark"] {
            --primary-color: #6366f1;
            --primary-light: #312e81;
            --text-primary: #f9fafb;
            --text-secondary: #9ca3af;
            --border-color: #374151;
            --hover-bg: #374151;
            --body-bg: #111827;
            --card-bg: #1f2937;
        }
        
        body {
            background-color: var(--body-bg);
            font-family: 'Segoe UI', system-ui, sans-serif;
            color: var(--text-primary);
            padding: 2rem 1.5rem;
        }
        
        .dashboard-card {
            border: none;
            border-radius: 16px;
            background: var(--card-bg);
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid var(--border-color);
        }
        
        .card-header {
            background: transparent;
            border-bottom: 1px solid var(--border-color);
            padding: 1.25rem 1.5rem;
            font-weight: 600;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #3651c4;
            border-color: #3651c4;
        }
        
        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            color: #fff;
        }
        
        .btn-outline-secondary:hover {
            background-color: #e2e8f0;
        }
        
        .btn-outline-info {
            color: #0891b2;
            border-color: #0891b2;
        }
        
        .btn-outline-info:hover {
            background-color: #0891b2;
            color: #fff;
        }
        
        .btn-outline-success {
            color: #059669;
            border-color: #059669;
        }
        
        .btn-outline-success:hover {
            background-color: #059669;
            color: #fff;
        }
        
        .table td {
            vertical-align: middle;
        }
        
        .badge-success {
            background: #d1fae5;
            color: #065f46;
            font-weight: 500;
            padding: 0.35rem 0.65rem;
            border-radius: 30px;
        }
        
        .badge-danger {
            background: #fee2e2;
            color: #b91c1c;
            font-weight: 500;
            padding: 0.35rem 0.65rem;
            border-radius: 30px;
        }
        
        .badge-info {
            background: #dbeafe;
            color: #1e40af;
            font-weight: 500;
            padding: 0.35rem 0.65rem;
            border-radius: 30px;
        }
        
        .badge-warning {
            background: #fed7aa;
            color: #92400e;
            font-weight: 500;
            padding: 0.35rem 0.65rem;
            border-radius: 30px;
        }
        
        .badge-type {
            background: var(--primary-light);
            color: var(--primary-color);
            font-weight: 500;
            padding: 0.25rem 0.75rem;
            border-radius: 30px;
            font-size: 0.8rem;
            display: inline-block;
        }
        
        .action-btn {
            padding: 0.25rem 0.8rem;
            font-size: 0.8rem;
            border-radius: 30px;
            margin: 0 2px;
        }
        
        /* DataTable Styling */
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_filter {
            margin-bottom: 1rem;
        }
        
        .dataTables_wrapper .dataTables_filter input {
            border: 1px solid var(--border-color);
            border-radius: 30px;
            padding: 0.375rem 1rem 0.375rem 2.5rem;
            background-color: var(--card-bg);
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23718096' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: left 0.8rem center;
            background-size: 16px;
        }
        
        .dataTables_wrapper .dataTables_filter input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
            outline: none;
        }
        
        .dataTables_wrapper .dataTables_length select {
            border: 1px solid var(--border-color);
            border-radius: 30px;
            padding: 0.375rem 2rem 0.375rem 1rem;
            background-color: var(--card-bg);
            color: var(--text-primary);
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23718096' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 0.8rem center;
            background-size: 14px;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }
        
        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .page-link {
            color: var(--primary-color);
            background-color: var(--card-bg);
            border-color: var(--border-color);
            margin: 0 2px;
            border-radius: 30px;
        }
        
        /* Modal Styling */
        .modal-content {
            border: none;
            border-radius: 20px;
            background: var(--card-bg);
        }
        
        .modal-header {
            border-bottom: 1px solid var(--border-color);
            background: var(--card-bg);
            padding: 1.5rem;
            border-radius: 20px 20px 0 0;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            border-top: 1px solid var(--border-color);
            padding: 1.5rem;
        }
        
        .modal-body .form-control,
        .modal-body .form-select {
            border-radius: 12px;
            border: 1px solid var(--border-color);
            padding: 0.625rem 1rem;
        }
        
        .modal-body .form-control:focus,
        .modal-body .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }
        
        .form-check-input:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        /* View Modal Specific Styling */
        .detail-row {
            display: flex;
            margin-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 0.75rem;
        }
        
        .detail-label {
            font-weight: 600;
            width: 140px;
            color: var(--text-secondary);
        }
        
        .detail-value {
            flex: 1;
            color: var(--text-primary);
        }
        
        .file-preview {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-top: 0.5rem;
            background: var(--hover-bg);
        }
        
        .file-icon {
            font-size: 1.5rem;
            margin-right: 1rem;
        }
        
        .file-info {
            display: flex;
            flex-direction: column;
        }
        
        .file-name {
            font-weight: 500;
            color: var(--text-primary);
        }
        
        .file-meta {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        /* Livewire loading indicator */
        .livewire-loading {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid rgba(67, 97, 238, 0.2);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 0.6s linear infinite;
        }
        
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
        
        /* SweetAlert2 Customization */
        .swal2-popup {
            border-radius: 16px !important;
            padding: 1.5rem !important;
        }
        
        .swal2-title {
            color: var(--text-primary) !important;
            font-size: 1.25rem !important;
            font-weight: 600 !important;
        }
        
        .swal2-html-container {
            color: var(--text-secondary) !important;
        }
        
        .swal2-timer-progress-bar {
            background: var(--primary-color) !important;
        }
        
        .swal2-toast {
            background: var(--card-bg) !important;
            border: 1px solid var(--border-color) !important;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1) !important;
        }
        
        .swal2-toast .swal2-title {
            font-size: 0.95rem !important;
            font-weight: 500 !important;
        }
        
        .swal2-confirm {
            border-radius: 30px !important;
            padding: 0.5rem 1.5rem !important;
        }
        
        .swal2-cancel {
            border-radius: 30px !important;
            padding: 0.5rem 1.5rem !important;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }
            
            .main-content {
                padding: 0.5rem;
            }
            
            .modal-dialog {
                margin: 0.5rem;
            }
            
            .detail-row {
                flex-direction: column;
            }
            
            .detail-label {
                width: 100%;
                margin-bottom: 0.25rem;
            }
            
            .action-btn {
                padding: 0.2rem 0.5rem;
                font-size: 0.75rem;
            }
        }
    </style>

    <div class="main-content" id="mainContent">
        <div class="container-fluid px-0">
            <!-- Header with Title and Add Button -->
            <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between mb-4">
                <div>
                    <h2 class="fw-semibold mb-1">📎 File Attachments</h2>
                    <p class="text-muted mb-0">Manage file attachments for documents</p>
                </div>
                <button class="btn btn-primary mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#attachmentModal" wire:click="resetForm">
                    <i class="bi bi-plus-circle me-2"></i>Add New Attachment
                </button>
            </div>

            <!-- Filter Info (if filtered by file or notice) -->
            @if($file_id || $notice_update_id)
            <div class="alert alert-info d-flex align-items-center justify-content-between mb-3" style="background: var(--primary-light); border-color: var(--primary-color); color: var(--text-primary);">
                <div>
                    <i class="bi bi-info-circle me-2"></i>
                    Showing attachments for 
                    @if($file_id && $files->firstWhere('id', $file_id))
                        <strong>File: {{ $files->firstWhere('id', $file_id)?->name }}</strong>
                    @endif
                    @if($file_id && $notice_update_id) and @endif
                    @if($notice_update_id && $noticeUpdates->firstWhere('id', $notice_update_id))
                        <strong>Notice #{{ $notice_update_id }}</strong>
                    @endif
                </div>
                <button class="btn btn-sm btn-outline-secondary" wire:click="$set('file_id', null); $set('notice_update_id', null); loadAttachments()">
                    <i class="bi bi-x"></i> Clear
                </button>
            </div>
            @endif

            <!-- Main Card with DataTable -->
            <div class="card dashboard-card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <div>
                        <i class="bi bi-paperclip me-2" style="color: var(--primary-color);"></i>
                        Registered Attachments
                        <span class="ms-2 small text-muted" id="recordCount">{{ count($attachments) }}</span>
                    </div>
                    <span wire:loading class="ms-3">
                        <span class="livewire-loading"></span>
                    </span>
                </div>
                <div class="card-body p-3 p-md-4">
                    <div class="table-responsive">
                        <table id="attachmentsTable" class="table table-hover" style="width:100%">
                            <thead class="bg-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Type</th>
                                    <th>Document</th>
                                    <th>File</th>
                                    <th>Size</th>
                                    <th>Linked To</th>
                                    <th>Status</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($attachments as $attachment)
                                    <tr>
                                        <td>{{ $attachment->id }}</td>
                                        <td>
                                            @if($attachment->attachmentType)
                                                <span class="badge-type">
                                                    <i class="bi bi-tag me-1"></i>
                                                    {{ $attachment->attachmentType->name }}
                                                </span>
                                            @else
                                                <span class="text-muted">—</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <i class="bi {{ $attachment->file_icon }} me-2 fs-5 text-{{ $attachment->file_color }}"></i>
                                                <div>
                                                    <div class="fw-medium">{{ $attachment->doc_name }}</div>
                                                    <small class="text-muted">{{ strtoupper($attachment->file_extension) }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="text-truncate" style="max-width: 200px;">
                                                {{ basename($attachment->file_name) }}
                                            </div>
                                        </td>
                                        <td>{{ $attachment->human_readable_size }}</td>
                                        <td>
                                            @if($attachment->file)
                                                <span class="badge-info">
                                                    <i class="bi bi-file-earmark me-1"></i>File
                                                </span>
                                            @elseif($attachment->noticeUpdate)
                                                <span class="badge-warning">
                                                    <i class="bi bi-megaphone me-1"></i>Notice
                                                </span>
                                            @else
                                                <span class="badge-secondary bg-secondary bg-opacity-10 text-secondary">
                                                    <i class="bi bi-dash me-1"></i>Unlinked
                                                </span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($attachment->active)
                                                <span class="badge-success">
                                                    <i class="bi bi-check-circle me-1"></i>Active
                                                </span>
                                            @else
                                                <span class="badge-danger">
                                                    <i class="bi bi-x-circle me-1"></i>Inactive
                                                </span>
                                            @endif
                                        </td>
                                        <td class="text-center">
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button class="btn btn-outline-info action-btn"
                                                        wire:click="view({{ $attachment->id }})"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#viewModal"
                                                        title="View details">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="btn btn-outline-success action-btn"
                                                        wire:click="download({{ $attachment->id }})"
                                                        title="Download file">
                                                    <i class="bi bi-download"></i>
                                                </button>
                                                <button class="btn btn-outline-primary action-btn"
                                                        wire:click="edit({{ $attachment->id }})"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#attachmentModal"
                                                        title="Edit attachment">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <button class="btn btn-outline-danger action-btn"
                                                        onclick="confirmDelete({{ $attachment->id }}, '{{ $attachment->doc_name }}')"
                                                        title="Delete attachment">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @empty
                                    <tr class="text-center">
                                        <td colspan="8" class="py-5 text-muted">
                                            <i class="bi bi-paperclip fs-1 d-block mb-3"></i>
                                            <p class="mb-0">No attachments found. Click "Add New Attachment" to create one.</p>
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- View Attachment Modal -->
        <div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true" wire:ignore.self>
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="viewModalLabel">
                            <i class="bi bi-eye me-2 text-info"></i>
                            Attachment Details
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        @if($selectedFile)
                            <div class="detail-row">
                                <span class="detail-label">ID:</span>
                                <span class="detail-value">#{{ $selectedFile->id }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Type:</span>
                                <span class="detail-value">
                                    @if($selectedFile->attachmentType)
                                        <span class="badge-type">
                                            <i class="bi bi-tag me-1"></i>
                                            {{ $selectedFile->attachmentType->name }}
                                        </span>
                                    @else
                                        <span class="text-muted">Not specified</span>
                                    @endif
                                </span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Document Name:</span>
                                <span class="detail-value fw-medium">{{ $selectedFile->doc_name }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">File Name:</span>
                                <span class="detail-value">{{ basename($selectedFile->file_name) }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">File Type:</span>
                                <span class="detail-value">{{ $selectedFile->doc_type ?? 'N/A' }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">File Size:</span>
                                <span class="detail-value">{{ $selectedFile->human_readable_size }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Linked To:</span>
                                <span class="detail-value">
                                    @if($selectedFile->file)
                                        <div><i class="bi bi-file-earmark me-1"></i> File: {{ $selectedFile->file->name }}</div>
                                    @endif
                                    @if($selectedFile->noticeUpdate)
                                        <div><i class="bi bi-megaphone me-1"></i> Notice Update #{{ $selectedFile->noticeUpdate->id }}</div>
                                    @endif
                                    @if(!$selectedFile->file && !$selectedFile->noticeUpdate)
                                        <span class="text-muted"><i class="bi bi-dash me-1"></i> Not linked to any record</span>
                                    @endif
                                </span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Status:</span>
                                <span class="detail-value">
                                    @if($selectedFile->active)
                                        <span class="badge-success"><i class="bi bi-check-circle me-1"></i>Active</span>
                                    @else
                                        <span class="badge-danger"><i class="bi bi-x-circle me-1"></i>Inactive</span>
                                    @endif
                                </span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Created By:</span>
                                <span class="detail-value">{{ $selectedFile->createdBy->name ?? 'N/A' }}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Created At:</span>
                                <span class="detail-value">{{ $selectedFile->created_at ? $selectedFile->created_at->format('F j, Y g:i A') : 'N/A' }}</span>
                            </div>
                            @if($selectedFile->updated_by && $selectedFile->updated_by != $selectedFile->created_by)
                            <div class="detail-row">
                                <span class="detail-label">Updated By:</span>
                                <span class="detail-value">{{ $selectedFile->updatedBy->name ?? 'N/A' }}</span>
                            </div>
                            @endif
                            @if($selectedFile->updated_at && $selectedFile->updated_at != $selectedFile->created_at)
                            <div class="detail-row">
                                <span class="detail-label">Updated At:</span>
                                <span class="detail-value">{{ $selectedFile->updated_at->format('F j, Y g:i A') }}</span>
                            </div>
                            @endif
                        @else
                            <div class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                        @endif
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="bi bi-x-circle me-2"></i>Close
                        </button>
                        @if($selectedFile)
                        <button type="button" class="btn btn-success" 
                                wire:click="download({{ $selectedFile->id }})">
                            <i class="bi bi-download me-2"></i>Download
                        </button>
                        <button type="button" class="btn btn-primary" 
                                wire:click="edit({{ $selectedFile->id }})"
                                data-bs-toggle="modal"
                                data-bs-target="#attachmentModal"
                                data-bs-dismiss="modal">
                            <i class="bi bi-pencil me-2"></i>Edit
                        </button>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Add/Edit Attachment Modal with Type Selection -->
        <div class="modal fade" id="attachmentModal" tabindex="-1" aria-labelledby="attachmentModalLabel" aria-hidden="true" wire:ignore.self>
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="attachmentModalLabel">
                            <i class="bi {{ $editMode ? 'bi-pencil-square' : 'bi-plus-circle' }} me-2 text-primary"></i>
                            {{ $editMode ? 'Edit Attachment' : 'Add New Attachment' }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form wire:submit="{{ $editMode ? 'update' : 'store' }}">
                        <div class="modal-body">
                            <div class="row g-3">
                                <!-- Document Name -->
                                <div class="col-12">
                                    <label class="form-label fw-medium">
                                        Document Name <span class="text-danger">*</span>
                                    </label>
                                    <input type="text"
                                        class="form-control @error('doc_name') is-invalid @enderror"
                                        wire:model="doc_name"
                                        placeholder="Enter document name">
                                    @error('doc_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- File Upload -->
                                <div class="col-12">
                                    <label class="form-label fw-medium">
                                        File 
                                        @if(!$editMode)
                                            <span class="text-danger">*</span>
                                        @endif
                                    </label>
                                    <input type="file"
                                        class="form-control @error('upload') is-invalid @enderror"
                                        wire:model="upload"
                                        accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.txt,.zip,.rar">
                                    @error('upload')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    
                                    <!-- Show selected file preview -->
                                    @if($upload)
                                        <div class="file-preview mt-2">
                                            <i class="bi bi-file-earmark me-2 fs-4"></i>
                                            <div class="file-info">
                                                <span class="file-name">{{ $upload->getClientOriginalName() }}</span>
                                                <span class="file-meta">{{ round($upload->getSize() / 1024, 2) }} KB (ready to upload)</span>
                                            </div>
                                        </div>
                                    @endif
                                    
                                    <!-- Show current file in edit mode -->
                                    @if($editMode && !$upload && $selectedFile?->file_name)
                                        <div class="file-preview mt-2">
                                            <i class="bi bi-file-earmark me-2 fs-4 text-muted"></i>
                                            <div class="file-info">
                                                <span class="file-name text-muted">{{ basename($selectedFile->file_name) }}</span>
                                                <span class="file-meta">Current file - upload new to replace</span>
                                            </div>
                                        </div>
                                    @endif
                                </div>

                                <!-- Attachment Type Selection -->
                                <div class="col-12">
                                    <label class="form-label fw-medium">
                                        Attachment Type <span class="text-muted">(optional)</span>
                                    </label>
                                    <select class="form-select @error('attachment_type_id') is-invalid @enderror"
                                            wire:model="attachment_type_id">
                                        <option value="">-- Select Type (e.g., Letter, Newspaper, Report) --</option>
                                        @foreach($attachmentTypes as $type)
                                            <option value="{{ $type->id }}" {{ $type->active ? '' : 'disabled' }}>
                                                {{ $type->name }}
                                                @if(!$type->active)
                                                    (Inactive)
                                                @endif
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('attachment_type_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle me-1"></i>
                                        Select the type of document (e.g., Barua, Gazeti, Ripoti, etc.)
                                    </small>
                                </div>

                                <!-- Link to File (Optional) -->
                                <div class="col-md-6">
                                    <label class="form-label fw-medium">Link to File</label>
                                    <select class="form-select @error('file_id') is-invalid @enderror"
                                            wire:model="file_id">
                                        <option value="">-- Not linked to file --</option>
                                        @foreach($files as $file)
                                            <option value="{{ $file->id }}">{{ $file->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('file_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Link to Notice Update (Optional) -->
                                <div class="col-md-6">
                                    <label class="form-label fw-medium">Link to Notice Update</label>
                                    <select class="form-select @error('notice_update_id') is-invalid @enderror"
                                            wire:model="notice_update_id">
                                        <option value="">-- Not linked to notice --</option>
                                        @foreach($noticeUpdates as $notice)
                                            <option value="{{ $notice->id }}">Notice #{{ $notice->id }}</option>
                                        @endforeach
                                    </select>
                                    @error('notice_update_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Status Toggle -->
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input"
                                               type="checkbox"
                                               wire:model="active"
                                               id="activeStatus"
                                               {{ $active ? 'checked' : '' }}>
                                        <label class="form-check-label fw-medium" for="activeStatus">
                                            {{ $active ? 'Active' : 'Inactive' }}
                                        </label>
                                    </div>
                                </div>

                                <!-- Note about linking -->
                                <div class="col-12">
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle me-1"></i>
                                        You can link this attachment to either a File OR a Notice Update, or leave it unlinked.
                                    </small>
                                </div>
                            </div>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                <i class="bi bi-x-circle me-2"></i>Cancel
                            </button>
                            <button type="submit" class="btn btn-primary" wire:loading.attr="disabled" wire:target="store,update,upload">
                                <span wire:loading.remove wire:target="store,update,upload">
                                    <i class="bi {{ $editMode ? 'bi-check-circle' : 'bi-save' }} me-2"></i>
                                    {{ $editMode ? 'Update Attachment' : 'Save Attachment' }}
                                </span>
                                <span wire:loading wire:target="store,update,upload">
                                    <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                    {{ $editMode ? 'Updating...' : 'Saving...' }}
                                </span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        // SweetAlert2 Toast Configuration
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            background: 'var(--card-bg)',
            color: 'var(--text-primary)',
            showClass: {
                popup: 'animate__animated animate__fadeInRight'
            },
            hideClass: {
                popup: 'animate__animated animate__fadeOutRight'
            }
        });

        // DataTable instance
        let dataTable;

        // Initialize DataTable
        function initDataTable() {
            const table = $('#attachmentsTable');
            
            if (table.length === 0) return;
            
            try {
                if ($.fn.DataTable.isDataTable('#attachmentsTable')) {
                    $('#attachmentsTable').DataTable().destroy();
                    table.next('.dataTables_wrapper').remove();
                }
                
                if (table.find('tbody tr').length > 0 && !table.find('tbody td:first').text().includes('No attachments found')) {
                    dataTable = table.DataTable({
                        language: {
                            search: "🔍 Search:",
                            lengthMenu: "Show _MENU_ entries",
                            info: "Showing _START_ to _END_ of _TOTAL_ attachments",
                            infoEmpty: "Showing 0 to 0 of 0 attachments",
                            infoFiltered: "(filtered from _MAX_ total attachments)",
                            paginate: {
                                first: "First",
                                last: "Last",
                                next: "Next",
                                previous: "Prev"
                            }
                        },
                        dom: "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                             "<'row'<'col-sm-12'tr>>" +
                             "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
                        columnDefs: [
                            { targets: [0, 1, 2, 3, 4, 5, 6], orderable: true },
                            { targets: 7, orderable: false, className: "text-center" }
                        ],
                        order: [[0, 'desc']],
                        paging: true,
                        pageLength: 10,
                        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
                    });
                    
                    $('#recordCount').text(dataTable.data().length);
                }
            } catch (e) {
                console.warn('DataTable initialization error:', e);
            }
        }

        $(document).ready(function() {
            setTimeout(() => {
                initDataTable();
            }, 100);

            // Modal Events
            $('#attachmentModal').on('hidden.bs.modal', function() {
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                $('body').css('overflow', 'auto');
                $('body').css('padding-right', '');
            });

            $('#viewModal').on('hidden.bs.modal', function() {
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                $('body').css('overflow', 'auto');
                $('body').css('padding-right', '');
            });

            $(window).on('resize', function() {
                if (dataTable) {
                    dataTable.columns.adjust();
                }
            });
        });

        // Livewire Event Listeners
        document.addEventListener('livewire:init', function() {
            Livewire.on('closeModal', () => {
                $('#attachmentModal').modal('hide');
                $('#viewModal').modal('hide');
            });

            Livewire.on('showSuccess', (message) => {
                Toast.fire({
                    icon: 'success',
                    title: message,
                    iconColor: '#10b981'
                });
                
                setTimeout(() => {
                    try {
                        if ($.fn.DataTable.isDataTable('#attachmentsTable')) {
                            $('#attachmentsTable').DataTable().destroy();
                        }
                        $('#attachmentsTable').next('.dataTables_wrapper').remove();
                        initDataTable();
                    } catch (e) {
                        console.warn('Error refreshing table:', e);
                    }
                }, 200);
            });

            Livewire.on('showError', (message) => {
                Toast.fire({
                    icon: 'error',
                    title: message,
                    iconColor: '#ef4444'
                });
            });

            Livewire.on('refreshTable', () => {
                setTimeout(() => {
                    try {
                        if ($.fn.DataTable.isDataTable('#attachmentsTable')) {
                            $('#attachmentsTable').DataTable().destroy();
                        }
                        $('#attachmentsTable').next('.dataTables_wrapper').remove();
                        initDataTable();
                    } catch (e) {
                        console.warn('Error refreshing table:', e);
                    }
                }, 100);
            });
        });

        // Confirm Delete with SweetAlert2
        window.confirmDelete = function(attachmentId, docName) {
            Swal.fire({
                title: 'Delete Attachment?',
                html: `Are you sure you want to delete <strong>"${docName}"</strong>?<br><br>This action cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                background: 'var(--card-bg)',
                color: 'var(--text-primary)',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    @this.delete(attachmentId);
                }
            });
        };
    </script>
</div>