<!-- resources/views/livewire/categories/index.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;
        }
        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;
        }
        .table td {
            vertical-align: middle;
        }
        .badge-success {
            background: #d1fae5;
            color: #065f46;
            font-weight: 500;
        }
        .badge-warning {
            background: #fed7aa;
            color: #92400e;
            font-weight: 500;
        }
        .badge-danger {
            background: #fee2e2;
            color: #b91c1c;
        }
        .action-btn {
            padding: 0.25rem 0.8rem;
            font-size: 0.8rem;
            border-radius: 30px;
            margin: 0 2px;
        }
        .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;
            background-color: var(--card-bg);
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 30px;
        }
        .modal-content {
            border: none;
            border-radius: 20px;
        }
        .modal-header {
            border-bottom: 1px solid var(--border-color);
            background: var(--card-bg);
        }
        .modal-body .form-control {
            border-radius: 12px;
            border: 1px solid var(--border-color);
        }
        /* 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-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;
        }
        
        /* DataTable styling for Livewire updates */
        .dataTables_filter input {
            background-color: var(--card-bg);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }
        .dataTables_filter input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
            outline: none;
        }
        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        .page-link {
            color: var(--primary-color);
        }
        table.dataTable td {
            border-bottom: 1px solid var(--border-color) !important;
        }
    </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">Categories</h2>
                </div>
                <button class="btn btn-primary mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#addModal" wire:click="resetForm">
                    <i class="bi bi-plus-circle me-2"></i>Add new Category
                </button>
            </div>

            <!-- main card with datatable -->
            <div class="card dashboard-card">
                <div class="card-header d-flex align-items-center">
                    <i class="bi bi-table me-2" style="color: var(--primary-color);"></i> 
                    Registered Categories 
                    <span class="ms-2 small text-muted" id="recordCount"><?php echo e(count($categories)); ?></span>
                    <span wire:loading class="ms-3">
                        <span class="livewire-loading"></span>
                    </span>
                </div>
                <div class="card-body p-3 p-md-4">
                    <table id="categoriesTable" class="table table-hover" style="width:100%">
                        <thead class="bg-light">
                            <tr>
                                <th>ID</th>
                                <th>Category name</th>
                                <th>Created By</th>
                                <th>Updated By</th>
                                <th>Status</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                <tr>
                                    <td><?php echo e($category->id); ?></td>
                                    <td><?php echo e($category->name); ?></td>
                                    <td><?php echo e($category->created_by ?? 'N/A'); ?></td>
                                    <td><?php echo e($category->updated_by ?? 'N/A'); ?></td>
                                    <td>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($category->active ?? true): ?>
                                            <span class="badge badge-success">Active</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">Inactive</span>
                                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-outline-primary action-btn" 
                                                wire:click="edit(<?php echo e($category->id); ?>)"
                                                data-bs-toggle="modal" 
                                                data-bs-target="#addModal">
                                            <i class="bi bi-pencil"></i> Edit
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger action-btn"
                                                wire:click="delete(<?php echo e($category->id); ?>)"
                                                onclick="confirmDelete(event, <?php echo e($category->id); ?>)">
                                            <i class="bi bi-trash"></i> Delete
                                        </button>
                                    </td>
                                </tr>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Category Modal -->
        <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true" wire:ignore.self>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addModalLabel">
                            <i class="bi <?php echo e($editMode ? 'bi-pencil-square' : 'bi-plus-circle'); ?> me-2 text-primary"></i>
                            <?php echo e($editMode ? 'Edit Category' : 'Add New Category'); ?>

                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form wire:submit="<?php echo e($editMode ? 'update' : 'store'); ?>">
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">Category Name <span class="text-danger">*</span></label>
                                <input type="text" 
                                       class="form-control <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                       wire:model="name"
                                       placeholder="Enter category name">
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback d-block"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Status</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" 
                                           type="checkbox" 
                                           wire:model="active"
                                           id="activeStatus"
                                           <?php echo e($active ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="activeStatus">
                                        <?php echo e($active ? 'Active' : 'Inactive'); ?>

                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary" wire:loading.attr="disabled" wire:target="store,update">
                                <span wire:loading.remove wire:target="store,update">
                                    <i class="bi <?php echo e($editMode ? 'bi-check-circle' : 'bi-save'); ?> me-2"></i>
                                    <?php echo e($editMode ? 'Update Category' : 'Save Category'); ?>

                                </span>
                                <span wire:loading wire:target="store,update">
                                    <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                    <?php echo e($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.datatables.net/1.13.6/js/dataTables.bootstrap5.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 configuration
        const dataTableConfig = {
            language: {
                search: "🔍 Search:",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ categories",
                infoEmpty: "Showing 0 to 0 of 0 categories",
                infoFiltered: "(filtered from _MAX_ total categories)",
                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, width: "5%" },
                { targets: 5, width: "15%", className: "text-center", orderable: false }
            ],
            order: [[0, 'desc']] // Order by ID descending by default
        };

        // Initialize DataTable
        function initDataTable() {
            if ($.fn.DataTable.isDataTable('#categoriesTable')) {
                $('#categoriesTable').DataTable().destroy();
                $('#categoriesTable').next('.dataTables_wrapper').remove();
            }
            $('#categoriesTable').DataTable(dataTableConfig);
        }

        $(document).ready(function() {
            initDataTable();

            // Ensure modal backdrop is properly removed
            $('#addModal').on('hidden.bs.modal', function () {
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
            });
        });

        // Livewire Event Listeners
        document.addEventListener('livewire:init', function() {
            // Close Modal
            Livewire.on('closeModal', () => {
                $('#addModal').modal('hide');
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
            });

            // Show success message
            Livewire.on('showSuccess', (message) => {
                Toast.fire({
                    icon: 'success',
                    title: message,
                    iconColor: '#10b981'
                });
            });

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

            // REFRESH DATATABLE - FIXED VERSION
            Livewire.on('refreshTable', () => {
                setTimeout(() => {
                    initDataTable();
                    
                    // Update record count
                    const count = window.Livewire.find('<?php echo e($_instance->getId()); ?>').categories.length;
                    $('#recordCount').text(count);
                }, 100);
            });

            // Set edit mode
            Livewire.on('setEditMode', (data) => {
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').editMode = true;
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').name = data.name;
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').active = data.active;
            });

            // Reset form
            Livewire.on('resetForm', () => {
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').editMode = false;
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').name = '';
                window.Livewire.find('<?php echo e($_instance->getId()); ?>').active = true;
            });
        });

        // Confirm delete with SweetAlert2
        window.confirmDelete = function(event, categoryId) {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, delete it!',
                background: 'var(--card-bg)',
                color: 'var(--text-primary)',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    window.Livewire.find('<?php echo e($_instance->getId()); ?>').delete(categoryId);
                }
            });
        };
    </script>
</div><?php /**PATH /Users/malando/Downloads/laravelApps/mswaada/resources/views/livewire/category-controller.blade.php ENDPATH**/ ?>