@extends('admin.layouts.app')

@section('title', 'Categories Management')

@section('content')
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Categories Management</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Organize platform categories</div>
        </div>
        
        <div style="padding: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <div style="display: flex; gap: 12px; align-items: center;">
                    <div style="position: relative;">
                        <input type="text" id="searchInput" placeholder="Search categories..." style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; width: 300px;">
                        <button onclick="searchCategories()" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-secondary); cursor: pointer;">🔍</button>
                    </div>
                    <select id="statusFilter" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        <option value="">All Status</option>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 8px;">
                    <button onclick="showAddCategoryModal()" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">Add Category</button>
                    <button onclick="exportCategories()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Export Categories</button>
                    <button onclick="showBulkActions()" style="padding: 8px 16px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer;">Bulk Actions</button>
                </div>
            </div>
            
            <div class="table-card" style="border: none; padding: 0;">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 50px;">
                                <input type="checkbox" id="selectAll" style="width: 16px; height: 16px;">
                            </th>
                            <th>Category</th>
                            <th>Slug</th>
                            <th>Subcategories</th>
                            <th>Status</th>
                            <th>Ads</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="categoriesTableBody">
                        <!-- Categories will be loaded here via JavaScript -->
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination with Page Size Selector -->
            <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <div style="display: flex; gap: 16px; align-items: center;">
                    <div style="color: var(--text-secondary); font-size: 0.875rem;">
                        Showing <span id="showingStart">1</span> to <span id="showingEnd">5</span> of <span id="totalCount">24</span> categories
                    </div>
                    <div style="display: flex; gap: 8px; align-items: center;">
                        <label style="font-size: 0.875rem; color: var(--text-secondary);">Show:</label>
                        <select id="pageSize" style="padding: 6px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                            <option value="10">10</option>
                            <option value="25" selected>25</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                </div>
                <div style="display: flex; gap: 8px; align-items: center;">
                    <button id="prevPage" onclick="changePage(-1)" style="padding: 6px 12px; border: 1px solid var(--border-color); border-radius: 6px; background: white; cursor: pointer;">Previous</button>
                    <div id="pageNumbers" style="display: flex; gap: 4px;">
                        <!-- Page numbers will be generated here -->
                    </div>
                    <button id="nextPage" onclick="changePage(1)" style="padding: 6px 12px; border: 1px solid var(--border-color); border-radius: 6px; background: white; cursor: pointer;">Next</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Category Statistics -->
    <div class="dashboard-grid">
        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Total Categories</div>
                    <div class="card-value">{{ $totalCategories }}</div>
                </div>
                <div class="stat-icon">📁</div>
            </div>
            <div class="card-change">Well organized</div>
        </div>

        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Subcategories</div>
                    <div class="card-value">{{ $totalSubcategories }}</div>
                </div>
                <div class="stat-icon">📂</div>
            </div>
            <div class="card-change">Nested structure</div>
        </div>

        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Active Categories</div>
                    <div class="card-value">{{ $activeCategories }}</div>
                </div>
                <div class="stat-icon">✅</div>
            </div>
            <div class="card-change">Ready for use</div>
        </div>

        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Inactive Categories</div>
                    <div class="card-value">{{ $inactiveCategories }}</div>
                </div>
                <div class="stat-icon">⚠️</div>
            </div>
            <div class="card-change">Need review</div>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div id="addCategoryModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Add New Category</h3>
                <button onclick="hideAddCategoryModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="addCategoryForm" style="padding: 20px;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category Name</label>
                        <input type="text" name="name" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category Icon</label>
                        <div style="display: flex; gap: 12px; align-items: center;">
                            <input type="text" name="icon" placeholder="e.g., 🏠, 🚗, 📱" style="flex: 1; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <div style="display: flex; gap: 8px;">
                                <label style="background: #3b82f6; color: white; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 0.875rem; font-weight: 600;">
                                    Upload Image
                                    <input type="file" name="icon_image" accept="image/*" style="display: none;" onchange="previewIconImage(this)">
                                </label>
                            </div>
                        </div>
                        <div id="iconPreview" style="margin-top: 8px; display: none;">
                            <img id="iconPreviewImg" style="max-width: 40px; max-height: 40px; border-radius: 8px; border: 1px solid var(--border-color);">
                            <button type="button" onclick="removeIconImage()" style="margin-left: 8px; padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Remove</button>
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" rows="3" placeholder="Describe this category..." style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Order</label>
                        <input type="number" name="order" value="0" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideAddCategoryModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Add Category</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Category Modal -->
    <div id="editCategoryModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Edit Category</h3>
                <button onclick="hideEditCategoryModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="editCategoryForm" style="padding: 20px;">
                <input type="hidden" name="category_id" id="editCategoryId">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category Name</label>
                        <input type="text" name="name" id="editCategoryName" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category Icon</label>
                        <div style="display: flex; gap: 12px; align-items: center;">
                            <input type="text" name="icon" id="editCategoryIcon" placeholder="e.g., 🏠, 🚗, 📱" style="flex: 1; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <div style="display: flex; gap: 8px;">
                                <label style="background: #3b82f6; color: white; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 0.875rem; font-weight: 600;">
                                    Upload Image
                                    <input type="file" name="icon_image" accept="image/*" style="display: none;" onchange="previewEditIconImage(this)">
                                </label>
                            </div>
                        </div>
                        <div id="editIconPreview" style="margin-top: 8px; display: none;">
                            <img id="editIconPreviewImg" style="max-width: 40px; max-height: 40px; border-radius: 8px; border: 1px solid var(--border-color);">
                            <button type="button" onclick="removeEditIconImage()" style="margin-left: 8px; padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Remove</button>
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" id="editCategoryDescription" rows="3" placeholder="Describe this category..." style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" id="editCategoryStatus" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Order</label>
                        <input type="number" name="order" id="editCategoryOrder" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideEditCategoryModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Update Category</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Subcategories Modal -->
    <div id="subcategoriesModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="subcategoriesTitle">Subcategories</h3>
                <button onclick="hideSubcategoriesModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <div>
                        <button onclick="showAddSubcategoryModal()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">Add Subcategory</button>
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button onclick="exportSubcategories()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Export</button>
                        <button onclick="showSubcategoryBulkActions()" style="padding: 8px 16px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer;">Bulk Actions</button>
                    </div>
                </div>
                
                <div class="table-card" style="border: none; padding: 0;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th style="width: 50px;">
                                    <input type="checkbox" id="selectAllSubcategories" style="width: 16px; height: 16px;">
                                </th>
                                <th>Subcategory</th>
                                <th>Slug</th>
                                <th>Status</th>
                                <th>Ads</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="subcategoriesTableBody">
                            <!-- Subcategories will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Subcategory Modal -->
    <div id="addSubcategoryModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Add Subcategory</h3>
                <button onclick="hideAddSubcategoryModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="addSubcategoryForm" style="padding: 20px;">
                <input type="hidden" name="category_id" id="addSubcategoryCategoryId">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Subcategory Name</label>
                        <input type="text" name="name" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Subcategory Icon</label>
                        <input type="text" name="icon" placeholder="e.g., 🏠, 🚗, 📱" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" rows="3" placeholder="Describe this subcategory..." style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Order</label>
                        <input type="number" name="order" value="0" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideAddSubcategoryModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Add Subcategory</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Subcategory Modal -->
    <div id="editSubcategoryModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Edit Subcategory</h3>
                <button onclick="hideEditSubcategoryModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="editSubcategoryForm" style="padding: 20px;">
                <input type="hidden" name="subcategory_id" id="editSubcategoryId">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Subcategory Name</label>
                        <input type="text" name="name" id="editSubcategoryName" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Subcategory Icon</label>
                        <input type="text" name="icon" id="editSubcategoryIcon" placeholder="e.g., 🏠, 🚗, 📱" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" id="editSubcategoryDescription" rows="3" placeholder="Describe this subcategory..." style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" id="editSubcategoryStatus" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Order</label>
                        <input type="number" name="order" id="editSubcategoryOrder" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideEditSubcategoryModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Update Subcategory</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Confirmation Modal -->
    <div id="confirmModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="confirmTitle">Confirm Action</h3>
                <button onclick="hideConfirmModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                <p id="confirmMessage">Are you sure you want to perform this action?</p>
                <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
                    <button onclick="hideConfirmModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button id="confirmActionBtn" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Confirm</button>
                </div>
        </div>
    </div>

    <!-- Fields Management Modal -->
    <div id="fieldsModal" class="modal" style="display: none; z-index: 1050;">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="fieldsModalTitle">Manage Custom Fields</h3>
                <button onclick="hideFieldsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                
                <!-- List View -->
                <div id="fieldsListContainer">
                    <div style="margin-bottom: 20px; text-align: right;">
                        <button onclick="showAddFieldForm()" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">+ Add New Field</button>
                    </div>
                    
                    <div class="table-card" style="border: none; padding: 0;">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Field Name</th>
                                    <th>Type</th>
                                    <th>Required</th>
                                    <th>Options</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="fieldsTableBody">
                                <!-- Fields Loaded via JS -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Add/Edit Form -->
                <div id="fieldFormContainer" style="display: none;">
                    <h4 id="fieldFormTitle" style="margin-top: 0;">Assign Field from Library</h4>
                    <form id="fieldForm">
                        <input type="hidden" id="fieldId" name="field_id">
                        
                        <!-- Library Selection -->
                        <div id="librarySelectionContainer" style="margin-bottom: 20px; padding: 15px; background: #f8fafc; border-radius: 8px; border: 1px solid #e2e8f0;">
                            <label style="display: block; font-weight: 600; margin-bottom: 8px;">Select Field <span style="color: red;">*</span></label>
                            <div style="display: flex; gap: 8px;">
                                <select name="global_field_id" id="globalFieldSelect" style="flex: 1; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    <option value="">Loading library...</option>
                                </select>
                                <a href="{{ route('admin.global_fields.index') }}" target="_blank" style="padding: 10px 16px; background: #64748b; color: white; text-decoration: none; border-radius: 6px; display: flex; align-items: center; white-space: nowrap;">Manage Library</a>
                            </div>
                            <div style="margin-top: 8px; font-size: 0.85rem;">
                                <a href="#" onclick="toggleManualMode(event)" style="color: var(--primary-color);">Or create a one-off custom field (Advanced)</a>
                            </div>
                        </div>

                        <!-- Manual Fields (Hidden by Default) -->
                        <div id="manualFieldContainer" style="display: none; border: 1px dashed var(--border-color); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
                                <div>
                                    <label style="display: block; font-weight: 600; margin-bottom: 8px;">Field Name <span style="color: red;">*</span></label>
                                    <input type="text" name="name" id="fieldName" style="width: 100%; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;">
                                </div>
                                <div>
                                    <label style="display: block; font-weight: 600; margin-bottom: 8px;">Data Type <span style="color: red;">*</span></label>
                                    <select name="type" id="fieldType" onchange="toggleFieldOptions()" style="width: 100%; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;">
                                        <option value="text">Text Input</option>
                                        <option value="number">Number Input</option>
                                        <option value="dropdown">Dropdown Selection</option>
                                        <option value="radio">Radio Buttons</option>
                                        <option value="checkbox">Checkbox (Multiple)</option>
                                        <option value="date">Date Picker</option>
                                    </select>
                                </div>
                            </div>

                            <div id="fieldOptionsContainer" style="margin-bottom: 16px; display: none;">
                                <label style="display: block; font-weight: 600; margin-bottom: 8px;">Options (Comma Separated) <span style="color: red;">*</span></label>
                                <textarea name="options_text" id="fieldOptions" rows="3" placeholder="Option 1, Option 2, Option 3" style="width: 100%; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;"></textarea>
                            </div>
                            
                            <div style="margin-bottom: 16px;">
                                <label style="display: block; font-weight: 600; margin-bottom: 8px;">Icon (Optional)</label>
                                <div style="display: flex; gap: 8px;">
                                     <input type="text" name="icon" placeholder="Emoji or Class" style="flex: 1; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;">
                                     <input type="file" name="icon_image" accept="image/png, image/jpeg, image/svg+xml">
                                </div>
                            </div>
                        </div>

                        <!-- Common Settings -->
                        <div style="background: #f1f5f9; padding: 15px; border-radius: 8px;">
                            <label style="display: block; font-weight: 600; margin-bottom: 8px;">Settings for this Subcategory</label>
                            <div style="display: flex; gap: 20px;">
                                <label style="display: flex; align-items: center; gap: 8px;">
                                    <input type="checkbox" name="is_required" value="1">
                                    Required Field
                                </label>
                                <label style="display: flex; align-items: center; gap: 8px;">
                                    Order: 
                                    <input type="number" name="sort_order" value="0" style="width: 60px; padding: 4px; border: 1px solid var(--border-color); border-radius: 4px;">
                                </label>
                            </div>
                        </div>
                        
                        <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 20px;">
                            <button type="button" onclick="cancelFieldForm()" style="padding: 10px 20px; border: 1px solid var(--border-color); background: white; border-radius: 6px; cursor: pointer;">Cancel</button>
                            <button type="submit" style="padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">Save Assignment</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // State management
        let categories = [];
        let filteredCategories = [];
        let currentPage = 1;
        let pageSize = 25;
        let totalCategories = 0;
        let currentCategoryId = null;
        let currentSubcategories = [];

        // Initialize with real data
        function initializeCategories() {
            categories = @json($categories);
            totalCategories = categories.length;
            filteredCategories = [...categories];
            // renderNestedCategories(); // Use simple render for now or adapt if renderNestedCategories exists (it doesn't in previous view_file output?)
            // wait, renderNestedCategories was NOT in previous file output?
            // Ah, line 512 called it. But where is it defined?
            // Previous view_file showed lines 400-1199. It wasn't visible.
            // Let's assume renderCategories handles it or I'll just call renderCategories.
            renderCategories();
            updatePagination();
            initDragAndDrop();
        }

        // Filtering and Search
        function searchCategories() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;

            filteredCategories = categories.filter(category => {
                const matchesSearch = category.name.toLowerCase().includes(searchTerm) || 
                                     category.description.toLowerCase().includes(searchTerm) ||
                                     category.slug.includes(searchTerm);
                const matchesStatus = !statusFilter || category.status === statusFilter;
                
                return matchesSearch && matchesStatus;
            });

            currentPage = 1;
            renderCategories();
            updatePagination();
        }

        // Pagination Logic
        function changePage(direction) {
            const totalPages = Math.ceil(filteredCategories.length / pageSize);
            const newPage = currentPage + direction;
            
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                renderCategories();
                updatePagination();
            }
        }

        function changePageSize() {
            pageSize = parseInt(document.getElementById('pageSize').value);
            currentPage = 1;
            renderCategories();
            updatePagination();
        }

        function goToPage(page) {
            const totalPages = Math.ceil(filteredCategories.length / pageSize);
            if (page >= 1 && page <= totalPages) {
                currentPage = page;
                renderCategories();
                updatePagination();
            }
        }

        function updatePagination() {
            const totalPages = Math.ceil(filteredCategories.length / pageSize);
            const start = (currentPage - 1) * pageSize + 1;
            const end = Math.min(currentPage * pageSize, filteredCategories.length);
            const total = filteredCategories.length;

            document.getElementById('showingStart').textContent = start;
            document.getElementById('showingEnd').textContent = end;
            document.getElementById('totalCount').textContent = total;

            // Update Previous/Next buttons
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;

            // Generate page numbers
            const pageNumbersContainer = document.getElementById('pageNumbers');
            pageNumbersContainer.innerHTML = '';

            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const btn = document.createElement('button');
                btn.textContent = i;
                btn.onclick = () => goToPage(i);
                btn.style.padding = '6px 12px';
                btn.style.border = '1px solid var(--border-color)';
                btn.style.borderRadius = '6px';
                btn.style.background = i === currentPage ? 'var(--primary-color)' : 'white';
                btn.style.color = i === currentPage ? 'white' : 'black';
                btn.style.cursor = 'pointer';
                pageNumbersContainer.appendChild(btn);
            }
        }

        // Rendering
        function renderCategories() {
            const tbody = document.getElementById('categoriesTableBody');
            tbody.innerHTML = '';

            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageCategories = filteredCategories.slice(startIndex, endIndex);

            pageCategories.forEach(category => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="category-checkbox" data-category-id="${category.id}" style="width: 16px; height: 16px;"></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: #f8fafc; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; border: 1px solid var(--border-color);">
                                ${category.icon || '📁'}
                            </div>
                            <div>
                                <div style="font-weight: 600;">${category.name}</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">${category.description || ''}</div>
                            </div>
                        </div>
                    </td>
                    <td style="color: var(--text-secondary);">${category.slug}</td>
                    <td style="font-weight: 600;">${category.subcategories_count}</td>
                    <td>${getStatusBadge(category.status)}</td>
                    <td style="font-weight: 600; color: var(--primary-color);">${category.ads_count.toLocaleString()}</td>
                    <td>
                        ${getCategoryActionButtons(category)}
                    </td>
                `;
                tbody.appendChild(row);
            });

            // Update select all checkbox
            const checkboxes = document.querySelectorAll('.category-checkbox');
            const selectAll = document.getElementById('selectAll');
            selectAll.checked = checkboxes.length > 0 && Array.from(checkboxes).every(cb => cb.checked);
        }

        function getStatusBadge(status) {
            const statusConfig = {
                'active': { bg: '#dcfce7', color: '#10b981', text: 'Active' },
                'inactive': { bg: '#fee2e2', color: '#ef4444', text: 'Inactive' }
            };
            const config = statusConfig[status] || statusConfig.inactive;
            return `<span class="status-badge" style="background: ${config.bg}; color: ${config.color};">${config.text}</span>`;
        }

        function getCategoryActionButtons(category) {
            let buttons = '';
            
            // Edit button
            buttons += `<button onclick="editCategory(${category.id}, '${category.name}', '${category.icon}', '${category.description}', '${category.status}', ${category.order})" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Edit</button>`;

            // Subcategories button
            buttons += `<button onclick="showSubcategories(${category.id}, '${category.name}')" style="padding: 4px 8px; background: #f59e0b; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Subcategories</button>`;

            // Status-specific buttons
            if (category.status === 'active') {
                buttons += `<button onclick="deactivateCategory(${category.id}, '${category.name}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Deactivate</button>`;
            } else {
                buttons += `<button onclick="activateCategory(${category.id}, '${category.name}')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Activate</button>`;
            }

            // Delete button
            buttons += `<button onclick="deleteCategory(${category.id}, '${category.name}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Delete</button>`;
            
             // Fields button - REMOVED for Main Category as per user request
            // Main Categories do not need custom fields, only subcategories
            // buttons += `<button onclick="showFieldsManager('category', ${category.id}, '${category.name}')" ...`;

            return `<div style="display: flex; gap: 8px;">${buttons}</div>`;
        }

        // Modal Functions
        function showAddCategoryModal() {
            document.getElementById('addCategoryModal').style.display = 'block';
        }

        function hideAddCategoryModal() {
            document.getElementById('addCategoryModal').style.display = 'none';
        }

        function showEditCategoryModal(categoryId, name, icon, description, status, order) {
            document.getElementById('editCategoryId').value = categoryId;
            document.getElementById('editCategoryName').value = name;
            document.getElementById('editCategoryIcon').value = icon;
            document.getElementById('editCategoryDescription').value = description;
            document.getElementById('editCategoryStatus').value = status;
            document.getElementById('editCategoryOrder').value = order;
            document.getElementById('editCategoryModal').style.display = 'block';
        }

        function hideEditCategoryModal() {
            document.getElementById('editCategoryModal').style.display = 'none';
        }

        function showSubcategories(categoryId, categoryName) {
            currentCategoryId = categoryId;
            const category = categories.find(c => c.id === categoryId);
            currentSubcategories = category ? category.subcategories : [];
            
            document.getElementById('subcategoriesTitle').textContent = `Subcategories - ${categoryName}`;
            renderSubcategories();
            document.getElementById('subcategoriesModal').style.display = 'block';
        }

        function hideSubcategoriesModal() {
            document.getElementById('subcategoriesModal').style.display = 'none';
        }

        function showAddSubcategoryModal() {
            document.getElementById('addSubcategoryCategoryId').value = currentCategoryId;
            document.getElementById('addSubcategoryModal').style.display = 'block';
        }

        function hideAddSubcategoryModal() {
            document.getElementById('addSubcategoryModal').style.display = 'none';
        }

        function showEditSubcategoryModal(subcategoryId, name, icon, description, status, order) {
            document.getElementById('editSubcategoryId').value = subcategoryId;
            document.getElementById('editSubcategoryName').value = name;
            document.getElementById('editSubcategoryIcon').value = icon;
            document.getElementById('editSubcategoryDescription').value = description;
            document.getElementById('editSubcategoryStatus').value = status;
            document.getElementById('editSubcategoryOrder').value = order;
            document.getElementById('editSubcategoryModal').style.display = 'block';
        }

        function hideEditSubcategoryModal() {
            document.getElementById('editSubcategoryModal').style.display = 'none';
        }

        function showConfirmModal(title, message, action) {
            document.getElementById('confirmTitle').textContent = title;
            document.getElementById('confirmMessage').textContent = message;
            document.getElementById('confirmActionBtn').onclick = action;
            document.getElementById('confirmModal').style.display = 'block';
        }

        function hideConfirmModal() {
            document.getElementById('confirmModal').style.display = 'none';
        }

        // Action Functions
        function exportCategories() {
            alert('Export functionality would be implemented with server-side processing');
        }

        function showBulkActions() {
            const selectedCategories = Array.from(document.querySelectorAll('.category-checkbox:checked')).map(cb => cb.dataset.categoryId);
            if (selectedCategories.length === 0) {
                alert('Please select at least one category to perform bulk actions.');
                return;
            }
            alert(`Bulk actions would be performed on ${selectedCategories.length} selected categories`);
        }

        function exportSubcategories() {
            alert('Export subcategories functionality would be implemented with server-side processing');
        }

        function showSubcategoryBulkActions() {
            const selectedSubcategories = Array.from(document.querySelectorAll('.subcategory-checkbox:checked')).map(cb => cb.dataset.subcategoryId);
            if (selectedSubcategories.length === 0) {
                alert('Please select at least one subcategory to perform bulk actions.');
                return;
            }
            alert(`Bulk actions would be performed on ${selectedSubcategories.length} selected subcategories`);
        }

        // Form Submissions
        document.getElementById('addCategoryForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            try {
                const response = await fetch("{{ route('admin.categories.store') }}", {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    const newCategory = {
                        ...result.category,
                        ads_count: 0,
                        subcategories_count: 0,
                        subcategories: []
                    };
                    
                    categories.unshift(newCategory);
                    filteredCategories = [...categories];
                    renderCategories();
                    updatePagination();
                    hideAddCategoryModal();
                    this.reset();
                    alert('Category added successfully!');
                } else {
                    alert('Error: ' + (result.message || 'Failed to add category'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred while getting the data.');
            }
        };

        document.getElementById('editCategoryForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const categoryId = formData.get('category_id');
            // We need to support PUT method, sending _method field or using JSON
            formData.append('_method', 'PUT');

            try {
                const response = await fetch(`/admin/categories/${categoryId}`, {
                    method: 'POST', // Using POST with _method=PUT for FormData support
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: formData
                });

                if (response.ok) {
                    // Reflect changes locally
                    const categoryIndex = categories.findIndex(c => c.id == categoryId);
                    if (categoryIndex !== -1) {
                         // We update strictly what was changed or re-fetch. 
                         // For speed, let's update from form data + server response if possible.
                         // But simplistically updating fields:
                        categories[categoryIndex].name = formData.get('name');
                        categories[categoryIndex].slug = formData.get('name').toLowerCase().replace(/\s+/g, '-'); // Approximating slug
                        categories[categoryIndex].icon = formData.get('icon'); 
                        categories[categoryIndex].description = formData.get('description');
                        categories[categoryIndex].status = formData.get('status');
                        categories[categoryIndex].order = parseInt(formData.get('order'));
                        
                        filteredCategories = [...categories];
                        renderCategories();
                        updatePagination();
                        hideEditCategoryModal();
                        alert('Category updated successfully!');
                        // Optional: reload to get fresh data including server-generated slug/icon processing
                        // window.location.reload(); 
                    }
                } else {
                    const result = await response.json();
                    alert('Error: ' + (result.message || 'Failed to update category'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred while updating.');
            }
        };

        document.getElementById('addSubcategoryForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const categoryId = formData.get('category_id');
            
            try {
                const response = await fetch("{{ route('admin.subcategories.store') }}", {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    const category = categories.find(c => c.id == categoryId);
                    if (category) {
                        const newSubcategory = { ...result.subcategory, ads_count: 0 };
                        if (!category.subcategories) category.subcategories = [];
                        category.subcategories.push(newSubcategory);
                        category.subcategories_count++;
                        currentSubcategories = category.subcategories;
                        renderSubcategories(); // Update modal list
                        renderCategories(); // Update count in main list
                    }
                    hideAddSubcategoryModal();
                    this.reset();
                    alert('Subcategory added successfully!');
                } else {
                    alert('Error: ' + (result.message || 'Failed to add subcategory'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred.');
            }
        };

        document.getElementById('editSubcategoryForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const subcategoryId = formData.get('subcategory_id');
            const categoryId = currentCategoryId;

            formData.append('_method', 'PUT');

            try {
                const response = await fetch(`/admin/subcategories/${subcategoryId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: formData
                });

                if (response.ok) {
                    const category = categories.find(c => c.id == categoryId);
                    if (category) {
                        const subcategoryIndex = category.subcategories.findIndex(s => s.id == subcategoryId);
                        if (subcategoryIndex !== -1) {
                            category.subcategories[subcategoryIndex].name = formData.get('name');
                            category.subcategories[subcategoryIndex].icon = formData.get('icon');
                            category.subcategories[subcategoryIndex].description = formData.get('description');
                             category.subcategories[subcategoryIndex].status = formData.get('status');
                            category.subcategories[subcategoryIndex].sort_order = parseInt(formData.get('order'));
                            
                            currentSubcategories = category.subcategories;
                            renderSubcategories();
                        }
                    }
                    hideEditSubcategoryModal();
                    alert('Subcategory updated successfully!');
                } else {
                    const result = await response.json();
                    alert('Error: ' + (result.message || 'Failed to update subcategory'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred.');
            }
        };

        // User Action Functions
        function editCategory(categoryId, name, icon, description, status, order) {
            showEditCategoryModal(categoryId, name, icon, description, status, order);
        }

        function activateCategory(categoryId, categoryName) {
            showConfirmModal(
                'Activate Category',
                `Are you sure you want to activate ${categoryName}?`,
                function() {
                    const categoryIndex = categories.findIndex(c => c.id === categoryId);
                    if (categoryIndex !== -1) {
                        categories[categoryIndex].status = 'active';
                        filteredCategories = [...categories];
                        renderCategories();
                        updatePagination();
                    }
                    hideConfirmModal();
                    alert(`Category ${categoryName} has been activated.`);
                }
            );
        }

        async function deactivateCategory(id, name) {
            if (!confirm(`Are you sure you want to deactivate ${name}?`)) return;
            
            try {
                const response = await fetch(`/admin/categories/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ name: name, status: 'inactive' }) // Minimal update
                });

                if (response.ok) {
                    alert('Category deactivated!');
                    window.location.reload();
                } else {
                    alert('Failed to deactivate');
                }
            } catch (e) {
                console.error(e);
                alert('Error deactivating category');
            }
        }


        function deleteCategory(categoryId, categoryName) {
            showConfirmModal(
                'Delete Category',
                `Are you sure you want to delete ${categoryName}? This action cannot be undone.`,
                async function() {
                    try {
                        const response = await fetch(`/admin/categories/${categoryId}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Accept': 'application/json'
                            }
                        });
                        
                        if (response.ok) {
                            categories = categories.filter(c => c.id !== categoryId);
                            filteredCategories = [...categories];
                            renderCategories();
                            updatePagination();
                            hideConfirmModal();
                            alert(`Category ${categoryName} has been deleted.`);
                        } else {
                            alert('Failed to delete category.');
                        }
                    } catch (e) {
                        console.error(e);
                        alert('Error deleting category');
                    }
                }
            );
        }

        function renderSubcategories() {
            const tbody = document.getElementById('subcategoriesTableBody');
            tbody.innerHTML = '';

            currentSubcategories.forEach(subcategory => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="subcategory-checkbox" data-subcategory-id="${subcategory.id}" style="width: 16px; height: 16px;"></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: #f8fafc; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; border: 1px solid var(--border-color);">
                                ${subcategory.icon || '📁'}
                            </div>
                            <div>
                                <div style="font-weight: 600;">${subcategory.name}</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">${subcategory.description || ''}</div>
                            </div>
                        </div>
                    </td>
                    <td style="color: var(--text-secondary);">${subcategory.slug}</td>
                    <td>${getStatusBadge(subcategory.status)}</td>
                    <td style="font-weight: 600; color: var(--primary-color);">${subcategory.ads_count.toLocaleString()}</td>
                    <td>
                        ${getSubcategoryActionButtons(subcategory)}
                    </td>
                `;
                tbody.appendChild(row);
            });

            // Update select all checkbox
            const checkboxes = document.querySelectorAll('.subcategory-checkbox');
            const selectAll = document.getElementById('selectAllSubcategories');
            selectAll.checked = checkboxes.length > 0 && Array.from(checkboxes).every(cb => cb.checked);
        }

        function getSubcategoryActionButtons(subcategory) {
            let buttons = '';
            
            // Edit button
            buttons += `<button onclick="showEditSubcategoryModal(${subcategory.id}, '${subcategory.name}', '${subcategory.icon}', '${subcategory.description}', '${subcategory.status}', ${subcategory.order})" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Edit</button>`;

            // Status-specific buttons
            if (subcategory.status === 'active') {
                buttons += `<button onclick="deactivateSubcategory(${subcategory.id}, '${subcategory.name}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Deactivate</button>`;
            } else {
                buttons += `<button onclick="activateSubcategory(${subcategory.id}, '${subcategory.name}')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Activate</button>`;
            }

            // Delete button
            buttons += `<button onclick="deleteSubcategory(${subcategory.id}, '${subcategory.name}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Delete</button>`;
            
             // Fields button
            buttons += `<button onclick="showFieldsManager('subcategory', ${subcategory.id}, '${subcategory.name}')" style="padding: 4px 8px; background: #8b5cf6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-left: 4px;">Fields</button>`;

            return `<div style="display: flex; gap: 8px;">${buttons}</div>`;
        }

        function activateSubcategory(subcategoryId, subcategoryName) {
            showConfirmModal(
                'Activate Subcategory',
                `Are you sure you want to activate ${subcategoryName}?`,
                function() {
                    const category = categories.find(c => c.id === currentCategoryId);
                    if (category) {
                        const subcategoryIndex = category.subcategories.findIndex(s => s.id === subcategoryId);
                        if (subcategoryIndex !== -1) {
                            category.subcategories[subcategoryIndex].status = 'active';
                            currentSubcategories = category.subcategories;
                            renderSubcategories();
                        }
                    }
                    hideConfirmModal();
                    alert(`Subcategory ${subcategoryName} has been activated.`);
                }
            );
        }

        function deactivateSubcategory(subcategoryId, subcategoryName) {
            showConfirmModal(
                'Deactivate Subcategory',
                `Are you sure you want to deactivate ${subcategoryName}?`,
                function() {
                    const category = categories.find(c => c.id === currentCategoryId);
                    if (category) {
                        const subcategoryIndex = category.subcategories.findIndex(s => s.id === subcategoryId);
                        if (subcategoryIndex !== -1) {
                            category.subcategories[subcategoryIndex].status = 'inactive';
                            currentSubcategories = category.subcategories;
                            renderSubcategories();
                        }
                    }
                    hideConfirmModal();
                    alert(`Subcategory ${subcategoryName} has been deactivated.`);
                }
            );
        }

        function deleteSubcategory(subcategoryId, subcategoryName) {
            showConfirmModal(
                'Delete Subcategory',
                `Are you sure you want to delete ${subcategoryName}? This action cannot be undone.`,
                async function() {
                    try {
                        const response = await fetch(`/admin/subcategories/${subcategoryId}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Accept': 'application/json'
                            }
                        });
                        
                        if (response.ok) {
                           const category = categories.find(c => c.id === currentCategoryId);
                            if (category) {
                                category.subcategories = category.subcategories.filter(s => s.id !== subcategoryId);
                                category.subcategories_count = category.subcategories.length;
                                currentSubcategories = category.subcategories;
                                renderSubcategories();
                                renderCategories(); // Update count
                            }
                            hideConfirmModal();
                            alert(`Subcategory ${subcategoryName} has been deleted.`);
                        } else {
                            alert('Failed to delete subcategory.');
                        }
                    } catch (e) {
                         console.error(e);
                        alert('Error deleting subcategory');
                    }
                }
            );
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }

        // Image Upload Functions
        function previewIconImage(input) {
            const preview = document.getElementById('iconPreview');
            const previewImg = document.getElementById('iconPreviewImg');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        function previewEditIconImage(input) {
            const preview = document.getElementById('editIconPreview');
            const previewImg = document.getElementById('editIconPreviewImg');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        function removeIconImage() {
            const preview = document.getElementById('iconPreview');
            const previewImg = document.getElementById('iconPreviewImg');
            const fileInput = document.querySelector('input[name="icon_image"]');
            
            previewImg.src = '';
            preview.style.display = 'none';
            fileInput.value = '';
        }

        function removeEditIconImage() {
            const preview = document.getElementById('editIconPreview');
            const previewImg = document.getElementById('editIconPreviewImg');
            const fileInput = document.querySelector('input[name="icon_image"]');
            
            previewImg.src = '';
            preview.style.display = 'none';
            fileInput.value = '';
        }

        // Drag and Drop Functionality
        let draggedItem = null;
        let draggedOverItem = null;

        function initDragAndDrop() {
            const tbody = document.getElementById('categoriesTableBody');
            tbody.addEventListener('dragstart', handleDragStart);
            tbody.addEventListener('dragover', handleDragOver);
            tbody.addEventListener('drop', handleDrop);
            tbody.addEventListener('dragend', handleDragEnd);
        }

        function handleDragStart(e) {
            draggedItem = e.target.closest('tr');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/html', draggedItem.innerHTML);
            draggedItem.style.opacity = '0.4';
        }

        function handleDragOver(e) {
            e.preventDefault();
            draggedOverItem = e.target.closest('tr');
            if (draggedOverItem && draggedOverItem !== draggedItem) {
                const rect = draggedOverItem.getBoundingClientRect();
                const midpoint = rect.top + rect.height / 2;
                if (e.clientY < midpoint) {
                    draggedOverItem.parentNode.insertBefore(draggedItem, draggedOverItem);
                } else {
                    draggedOverItem.parentNode.insertBefore(draggedItem, draggedOverItem.nextSibling);
                }
            }
            e.dataTransfer.dropEffect = 'move';
            return false;
        }

        function handleDrop(e) {
            e.preventDefault();
            if (draggedItem && draggedOverItem) {
                updateCategoryOrder();
            }
            return false;
        }

        function handleDragEnd() {
            if (draggedItem) {
                draggedItem.style.opacity = '1';
            }
            draggedItem = null;
            draggedOverItem = null;
        }

        function updateCategoryOrder() {
            const rows = document.querySelectorAll('#categoriesTableBody tr');
            rows.forEach((row, index) => {
                const categoryId = row.querySelector('.category-checkbox').dataset.categoryId;
                const category = categories.find(c => c.id === parseInt(categoryId));
                if (category) {
                    category.order = index + 1;
                }
            });
            alert('Category order updated successfully!');
        }

        // Subcategory Drag and Drop
        function initSubcategoryDragAndDrop() {
            const tbody = document.getElementById('subcategoriesTableBody');
            tbody.addEventListener('dragstart', handleSubcategoryDragStart);
            tbody.addEventListener('dragover', handleSubcategoryDragOver);
            tbody.addEventListener('drop', handleSubcategoryDrop);
            tbody.addEventListener('dragend', handleSubcategoryDragEnd);
        }

        function handleSubcategoryDragStart(e) {
            draggedItem = e.target.closest('tr');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/html', draggedItem.innerHTML);
            draggedItem.style.opacity = '0.4';
        }

        function handleSubcategoryDragOver(e) {
            e.preventDefault();
            draggedOverItem = e.target.closest('tr');
            if (draggedOverItem && draggedOverItem !== draggedItem) {
                const rect = draggedOverItem.getBoundingClientRect();
                const midpoint = rect.top + rect.height / 2;
                if (e.clientY < midpoint) {
                    draggedOverItem.parentNode.insertBefore(draggedItem, draggedOverItem);
                } else {
                    draggedOverItem.parentNode.insertBefore(draggedItem, draggedOverItem.nextSibling);
                }
            }
            e.dataTransfer.dropEffect = 'move';
            return false;
        }

        function handleSubcategoryDrop(e) {
            e.preventDefault();
            if (draggedItem && draggedOverItem) {
                updateSubcategoryOrder();
            }
            return false;
        }

        function handleSubcategoryDragEnd() {
            if (draggedItem) {
                draggedItem.style.opacity = '1';
            }
            draggedItem = null;
            draggedOverItem = null;
        }

        function updateSubcategoryOrder() {
            const rows = document.querySelectorAll('#subcategoriesTableBody tr');
            rows.forEach((row, index) => {
                const subcategoryId = row.querySelector('.subcategory-checkbox').dataset.subcategoryId;
                const subcategory = currentSubcategories.find(s => s.id === parseInt(subcategoryId));
                if (subcategory) {
                    subcategory.order = index + 1;
                }
            });
            alert('Subcategory order updated successfully!');
        }

        // Nested Category Display
        function renderNestedCategories() {
            const tbody = document.getElementById('categoriesTableBody');
            tbody.innerHTML = '';

            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageCategories = filteredCategories.slice(startIndex, endIndex);

            pageCategories.forEach(category => {
                // Main category row
                const categoryRow = document.createElement('tr');
                categoryRow.draggable = true;
                categoryRow.innerHTML = `
                    <td><input type="checkbox" class="category-checkbox" data-category-id="${category.id}" style="width: 16px; height: 16px;"></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: #f8fafc; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; border: 1px solid var(--border-color);">
                                ${category.icon || '📁'}
                            </div>
                            <div>
                                <div style="font-weight: 600;">${category.name}</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">${category.description || ''}</div>
                            </div>
                        </div>
                    </td>
                    <td style="color: var(--text-secondary);">${category.slug}</td>
                    <td style="font-weight: 600;">${category.subcategories_count}</td>
                    <td>${getStatusBadge(category.status)}</td>
                    <td style="font-weight: 600; color: var(--primary-color);">${category.ads_count.toLocaleString()}</td>
                    <td>
                        ${getCategoryActionButtons(category)}
                    </td>
                `;
                tbody.appendChild(categoryRow);

                // Subcategories rows (collapsed by default)
                if (category.subcategories && category.subcategories.length > 0) {
                    const subcategoryHeaderRow = document.createElement('tr');
                    subcategoryHeaderRow.style.backgroundColor = '#f8fafc';
                    subcategoryHeaderRow.innerHTML = `
                        <td colspan="7" style="padding: 8px; font-weight: 600; color: var(--text-primary);">
                            <span style="margin-right: 8px; cursor: pointer;" onclick="toggleSubcategories(this, ${category.id})">▶</span>
                            Subcategories (${category.subcategories.length})
                        </td>
                        <td style="padding: 8px;">
                            <button onclick="showSubcategories(${category.id}, '${category.name}')" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Manage</button>
                        </td>
                    `;
                    tbody.appendChild(subcategoryHeaderRow);

                    // Individual subcategory rows (hidden initially)
                    category.subcategories.forEach(subcategory => {
                        const subcategoryRow = document.createElement('tr');
                        subcategoryRow.style.display = 'none';
                        subcategoryRow.style.backgroundColor = '#f1f5f9';
                        subcategoryRow.style.paddingLeft = '20px';
                        subcategoryRow.draggable = true;
                        subcategoryRow.innerHTML = `
                            <td></td>
                            <td>
                                <div style="display: flex; align-items: center; gap: 12px; padding-left: 20px;">
                                    <div style="width: 32px; height: 32px; border-radius: 6px; background: #e2e8f0; display: flex; align-items: center; justify-content: center; font-size: 1rem; border: 1px solid var(--border-color);">
                                        ${subcategory.icon || '📁'}
                                    </div>
                                    <div>
                                        <div style="font-weight: 600; font-size: 0.9rem;">${subcategory.name}</div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary);">${subcategory.description}</div>
                                    </div>
                                </div>
                            </td>
                            <td style="color: var(--text-secondary);">${subcategory.slug}</td>
                            <td style="font-weight: 600;">${subcategory.ads_count}</td>
                            <td>${getStatusBadge(subcategory.status)}</td>
                            <td></td>
                            <td>
                                ${getSubcategoryActionButtons(subcategory)}
                            </td>
                        `;
                        tbody.appendChild(subcategoryRow);
                    });
                }
            });

            // Update select all checkbox
            const checkboxes = document.querySelectorAll('.category-checkbox');
            const selectAll = document.getElementById('selectAll');
            selectAll.checked = checkboxes.length > 0 && Array.from(checkboxes).every(cb => cb.checked);
        }

        function toggleSubcategories(button, categoryId) {
            const rows = document.querySelectorAll('#categoriesTableBody tr');
            let foundCategory = false;
            let foundHeader = false;

            rows.forEach(row => {
                // Find the main category row
                if (row.querySelector(`.category-checkbox[data-category-id="${categoryId}"]`)) {
                    foundCategory = true;
                    foundHeader = false;
                    return;
                }

                // Find the subcategory header row for this category
                if (foundCategory && row.querySelector('td[colspan="7"]')) {
                    foundHeader = true;
                    // Toggle the header arrow
                    const arrow = row.querySelector('span');
                    const isCollapsed = arrow.textContent === '▶';
                    
                    if (isCollapsed) {
                        arrow.textContent = '▼';
                        // Show all subcategories for this category
                        showSubcategoriesForCategory(categoryId);
                    } else {
                        arrow.textContent = '▶';
                        // Hide all subcategories for this category
                        hideSubcategoriesForCategory(categoryId);
                    }
                    return;
                }

                // Skip other rows until we find the header for this category
                if (foundCategory && !foundHeader) {
                    return;
                }

                // After processing header, stop looking for this category
                if (foundHeader && row.querySelector('.category-checkbox')) {
                    foundCategory = false;
                    foundHeader = false;
                }
            });
        }

        function showSubcategoriesForCategory(categoryId) {
            const rows = document.querySelectorAll('#categoriesTableBody tr');
            let foundCategory = false;
            let foundHeader = false;

            rows.forEach(row => {
                if (row.querySelector(`.category-checkbox[data-category-id="${categoryId}"]`)) {
                    foundCategory = true;
                    return;
                }

                if (foundCategory && row.querySelector('td[colspan="7"]')) {
                    foundHeader = true;
                    return;
                }

                if (foundCategory && foundHeader && row.querySelector('.subcategory-checkbox')) {
                    row.style.display = '';
                }
            });
        }

        function hideSubcategoriesForCategory(categoryId) {
            const rows = document.querySelectorAll('#categoriesTableBody tr');
            let foundCategory = false;
            let foundHeader = false;

            rows.forEach(row => {
                if (row.querySelector(`.category-checkbox[data-category-id="${categoryId}"]`)) {
                    foundCategory = true;
                    return;
                }

                if (foundCategory && row.querySelector('td[colspan="7"]')) {
                    foundHeader = true;
                    return;
                }

                if (foundCategory && foundHeader && row.querySelector('.subcategory-checkbox')) {
                    row.style.display = 'none';
                }
            });
        }

        // --- Custom Fields Logic ---

        let currentFieldContext = { type: null, id: null, name: null };
        let currentFields = [];

        function showFieldsManager(type, id, name) {
            currentFieldContext = { type, id, name }; // type: 'category' or 'subcategory'
            document.getElementById('fieldsModalTitle').textContent = `Manage Custom Fields - ${name}`;
            document.getElementById('fieldsModal').style.display = 'block';
            loadCustomFields();
        }

        function hideFieldsModal() {
            document.getElementById('fieldsModal').style.display = 'none';
        }
        
        async function loadCustomFields() {
            const tbody = document.getElementById('fieldsTableBody');
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">Loading...</td></tr>';
            
            try {
                let url = `/admin/category-fields?`;
                if (currentFieldContext.type === 'category') {
                    url += `category_id=${currentFieldContext.id}`;
                } else {
                    url += `subcategory_id=${currentFieldContext.id}`;
                }

                const response = await fetch(url);
                const fields = await response.json();
                currentFields = fields;
                renderCustomFields(fields);
            } catch (error) {
                console.error('Error loading fields:', error);
                tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:red;">Error loading fields</td></tr>';
            }
        }

        function renderCustomFields(fields) {
            const tbody = document.getElementById('fieldsTableBody');
            tbody.innerHTML = '';
            
            if (fields.length === 0) {
                 tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">No custom fields found. Add one below!</td></tr>';
                 return;
            }

            fields.forEach(field => {
                let optionsCount = '-';
                if (field.options) {
                    try {
                        // Options coming from DB/JSON usually a string or array
                        if (typeof field.options === 'string') {
                             optionsCount = JSON.parse(field.options).length + ' options';
                        } else if (Array.isArray(field.options)) {
                             optionsCount = field.options.length + ' options';
                        }
                    } catch(e) {}
                }

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            ${field.icon ? (field.icon.length > 5 ? `<img src="/storage/${field.icon}" style="width:24px;height:24px;object-fit:cover;border-radius:4px;">` : `<span>${field.icon}</span>`) : '<span>📄</span>'}
                            <strong>${field.name}</strong>
                        </div>
                    </td>
                    <td><span class="status-badge" style="background: #e0f2fe; color: #0369a1;">${field.type.toUpperCase()}</span></td>
                    <td>${field.is_required ? 'Yes' : 'No'}</td>
                    <td>${optionsCount}</td>
                    <td>
                        <button onclick="editField(${field.id})" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; cursor: pointer;">Edit</button>
                        <button onclick="deleteField(${field.id})" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; cursor: pointer;">Delete</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }
        
        function showAddFieldForm() {
            document.getElementById('fieldFormContainer').style.display = 'block';
            document.getElementById('fieldsListContainer').style.display = 'none';
            document.getElementById('fieldFormTitle').textContent = 'Assign Field from Library';
            document.getElementById('fieldForm').reset();
            document.getElementById('fieldId').value = '';
            
            // Reset UI
            document.getElementById('manualFieldContainer').style.display = 'none';
            document.getElementById('globalFieldSelect').value = '';
            
            loadGlobalFields();
        }
        
        function cancelFieldForm() {
            document.getElementById('fieldFormContainer').style.display = 'none';
            document.getElementById('fieldsListContainer').style.display = 'block';
        }
        
        function toggleFieldOptions() {
            const type = document.getElementById('fieldType').value;
            const container = document.getElementById('fieldOptionsContainer');
            if (['dropdown', 'radio', 'checkbox'].includes(type)) {
                container.style.display = 'block';
            } else {
                container.style.display = 'none';
            }
        }
        
        // This function handles form submission
        // Need to attach separately or just use inline onsubmit
        // Retaining document.getElementById... logic
        
        async function deleteField(id) {
            if(!confirm('Delete this field?')) return;
            
            try {
                 await fetch(`/admin/category-fields/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });
                loadCustomFields();
            } catch (err) {
                alert('Error deleting field');
            }
        }
        
        // Global Fields Management
        let globalFieldsCache = [];
        
        async function loadGlobalFields() {
            const select = document.getElementById('globalFieldSelect');
            if (globalFieldsCache.length > 0) return populateGlobalSelect();

            try {
                // select.innerHTML = '<option>Loading...</option>';
                const res = await fetch("{{ route('admin.global_fields.list') }}");
                globalFieldsCache = await res.json();
                populateGlobalSelect();
            } catch(e) {
                console.error(e);
                select.innerHTML = '<option value="">Error loading library</option>';
            }
        }

        function populateGlobalSelect() {
            const select = document.getElementById('globalFieldSelect');
            select.innerHTML = '<option value="">-- Select from Library --</option>';
            globalFieldsCache.forEach(f => {
                const opt = document.createElement('option');
                opt.value = f.id;
                opt.textContent = `${f.name} (${f.type})`;
                select.appendChild(opt);
            });
        }

        function toggleManualMode(e) {
            if(e) e.preventDefault();
            const container = document.getElementById('manualFieldContainer');
            const library = document.getElementById('librarySelectionContainer');
            const isManual = container.style.display !== 'none';
            
            if (isManual) {
                container.style.display = 'none';
                library.style.opacity = '1';
                library.style.pointerEvents = 'auto';
                // output text to switch back? 
            } else {
                container.style.display = 'block';
                // library.style.opacity = '0.5';
                // library.style.pointerEvents = 'none';
                document.getElementById('globalFieldSelect').value = '';
            }
        }

        function editField(id) {
            const field = currentFields.find(f => f.id === id);
            if (!field) return;

            showAddFieldForm();
            document.getElementById('fieldFormTitle').textContent = 'Edit Field Assignment';
            document.getElementById('fieldId').value = field.id;
            
            // Check if it's a linked field
            if (field.global_field_id) {
                loadGlobalFields().then(() => {
                    document.getElementById('globalFieldSelect').value = field.global_field_id;
                    document.getElementById('manualFieldContainer').style.display = 'none';
                });
            } else {
                // Manual field
                document.getElementById('globalFieldSelect').value = '';
                document.getElementById('manualFieldContainer').style.display = 'block';
                
                // Populate manual fields
                const form = document.getElementById('fieldForm');
                if(form.elements['name']) form.elements['name'].value = field.name;
                if(form.elements['type']) form.elements['type'].value = field.type;
                if(form.elements['icon']) form.elements['icon'].value = field.icon || '';
                
                // Handle options
                if (['dropdown', 'radio', 'checkbox'].includes(field.type)) {
                    document.getElementById('fieldOptionsContainer').style.display = 'block';
                    let optionsVal = '';
                    try {
                        if (Array.isArray(field.options)) {
                            optionsVal = field.options.join(', ');
                        } else if (typeof field.options === 'string') {
                             const parsed = JSON.parse(field.options);
                             if(Array.isArray(parsed)) optionsVal = parsed.join(', ');
                        }
                    } catch(e) {}
                    document.getElementById('fieldOptions').value = optionsVal;
                } else {
                    document.getElementById('fieldOptionsContainer').style.display = 'none';
                }
            }
            
            // Common Settings
            const form = document.getElementById('fieldForm');
            form.elements['is_required'].checked = field.is_required;
            if(form.elements['sort_order']) form.elements['sort_order'].value = field.sort_order || 0;
        }

        // --- End Custom Fields Logic ---

        // Event Listeners
        document.getElementById('fieldForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const fieldId = document.getElementById('fieldId').value;
            
            // Add context
            if (currentFieldContext.type === 'category') {
                formData.append('category_id', currentFieldContext.id);
            } else {
                formData.append('subcategory_id', currentFieldContext.id);
            }
            
            // Handle options
            const type = formData.get('type');
            if (['dropdown', 'radio', 'checkbox'].includes(type)) {
                const optionsText = document.getElementById('fieldOptions').value;
                const options = optionsText.split(',').map(s => s.trim()).filter(s => s);
                options.forEach((opt, index) => formData.append(`options[${index}]`, opt));
            }
            
            const url = fieldId ? `/admin/category-fields/${fieldId}?_method=PUT` : `/admin/category-fields`;
            
            try {
                const res = await fetch(url, {
                    method: 'POST', 
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });
                
                if (res.ok) {
                    cancelFieldForm();
                    loadCustomFields();
                    alert('Field saved successfully!');
                } else {
                    const data = await res.json();
                    alert('Error: ' + (data.message || 'Failed to save field'));
                }
            } catch (err) {
                 console.error(err);
                 alert('Error saving field');
            }
        };

        document.getElementById('searchInput').addEventListener('input', searchCategories);
        document.getElementById('statusFilter').addEventListener('change', searchCategories);
        document.getElementById('pageSize').addEventListener('change', changePageSize);
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.category-checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
        });
        document.getElementById('selectAllSubcategories').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.subcategory-checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
        });

        // Initialize
        document.addEventListener('DOMContentLoaded', initializeCategories);
    </script>

    <style>
        .modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(2px);
        }

        .modal-content {
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border-color);
            max-width: 90vw;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideIn 0.3s ease-out;
            position: relative;
            margin: 0 auto;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-active {
            background: #dcfce7;
            color: #10b981;
        }

        .status-inactive {
            background: #fee2e2;
            color: #ef4444;
        }

        /* Enhanced pagination styles */
        #prevPage:disabled, #nextPage:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .table {
                font-size: 0.875rem;
            }
            .table th, .table td {
                padding: 8px 6px;
            }
            #pageNumbers {
                display: none;
            }
            .modal-content {
                max-width: 95vw;
                margin: 10px;
            }
        }
    </style>
@endsection
