/**
 * Table Search/Filter Functionality
 * Provides client-side search across all table columns
 */

(function() {
    'use strict';
    
    document.addEventListener('DOMContentLoaded', function() {
        // Find all tables in index pages
        const tables = document.querySelectorAll('table');
        
        tables.forEach(function(table) {
            // Only add filter to tables with tbody
            const tbody = table.querySelector('tbody');
            const thead = table.querySelector('thead');
            
            if (!tbody || !thead) return;
            
            // Check if filter row already exists
            if (thead.querySelector('.filter-row')) return;
            
            // Get all header cells
            const headerRow = thead.querySelector('tr');
            if (!headerRow) return;
            
            const headers = Array.from(headerRow.querySelectorAll('th'));
            
            // Create filter row
            const filterRow = document.createElement('tr');
            filterRow.className = 'filter-row';
            
            headers.forEach(function(header, index) {
                const th = document.createElement('th');
                
                // Don't add input to Actions column
                if (header.classList.contains('actions') || header.textContent.trim() === 'Actions') {
                    const clearBtn = document.createElement('button');
                    clearBtn.type = 'button';
                    clearBtn.className = 'btn-clear-filter';
                    clearBtn.innerHTML = '<i class="fas fa-times"></i>';
                    clearBtn.title = 'Clear All Filters';
                    clearBtn.onclick = function() {
                        clearAllFilters(table);
                    };
                    th.appendChild(clearBtn);
                } else {
                    // Add search input
                    const input = document.createElement('input');
                    input.type = 'text';
                    // Find longest text in this column for better placeholder
                    var longestText = '';
                    var maxLength = 0;
                    var rows = tbody.querySelectorAll('tr');
                    rows.forEach(function(row) {
                        var cells = row.querySelectorAll('td');
                        if (cells[index]) {
                            var text = cells[index].textContent.trim();
                            if (text.length > maxLength && text.length <= 30) {
                                maxLength = text.length;
                                longestText = text;
                            }
                        }
                    });
                    input.placeholder = longestText || 'Filter...';
                    
                    // Set input width based on longest text
                    if (longestText) {
                        // Create temporary span to measure text width
                        var tempSpan = document.createElement('span');
                        tempSpan.style.visibility = 'hidden';
                        tempSpan.style.position = 'absolute';
                        tempSpan.style.whiteSpace = 'nowrap';
                        tempSpan.style.font = window.getComputedStyle(input).font;
                        tempSpan.textContent = longestText;
                        document.body.appendChild(tempSpan);
                        var textWidth = tempSpan.offsetWidth;
                        document.body.removeChild(tempSpan);
                        
                        // Set input width (add padding for comfort)
                        input.style.width = (textWidth + 30) + 'px';
                        input.style.minWidth = '80px';
                        input.style.maxWidth = '300px';
                    }
                    input.className = 'table-filter-input';
                    input.dataset.columnIndex = index;
                    
                    // Real-time filtering
                    input.addEventListener('keyup', function() {
                        filterTable(table);
                    });
                    
                    th.appendChild(input);
                }
                
                filterRow.appendChild(th);
            });
            
            // Insert filter row after header row
            thead.insertBefore(filterRow, headerRow.nextSibling);
        });
    });
    
    function filterTable(table) {
        const filterInputs = table.querySelectorAll('.table-filter-input');
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        
        // Get all filter values
        const filters = Array.from(filterInputs).map(function(input) {
            return {
                index: parseInt(input.dataset.columnIndex),
                value: input.value.toLowerCase().trim()
            };
        });
        
        // Filter rows
        rows.forEach(function(row) {
            let show = true;
            const cells = Array.from(row.querySelectorAll('td'));
            
            filters.forEach(function(filter) {
                if (filter.value && cells[filter.index]) {
                    const cellText = cells[filter.index].textContent.toLowerCase().trim();
                    if (cellText.indexOf(filter.value) === -1) {
                        show = false;
                    }
                }
            });
            
            row.style.display = show ? '' : 'none';
        });
        
        // Update row count message
        updateRowCount(table);
    }
    
    function clearAllFilters(table) {
        const filterInputs = table.querySelectorAll('.table-filter-input');
        filterInputs.forEach(function(input) {
            input.value = '';
        });
        filterTable(table);
    }
    
    function updateRowCount(table) {
        const tbody = table.querySelector('tbody');
        const allRows = tbody.querySelectorAll('tr');
        const visibleRows = Array.from(allRows).filter(function(row) {
            return row.style.display !== 'none';
        });
        
        // Create or update count message
        let countMsg = table.parentElement.querySelector('.filter-count-message');
        if (!countMsg) {
            countMsg = document.createElement('div');
            countMsg.className = 'filter-count-message';
            table.parentElement.insertBefore(countMsg, table);
        }
        
        if (visibleRows.length < allRows.length) {
            countMsg.textContent = 'Showing ' + visibleRows.length + ' of ' + allRows.length + ' records';
            countMsg.style.display = 'block';
        } else {
            countMsg.style.display = 'none';
        }
    }
})();

/* Fix for actions sidebar menu */
.actions-sidebar {
    position: fixed !important;
    top: 120px;
    right: 20px;
    width: 60px;
    z-index: 1000;
    display: block !important;
}

.actions-sidebar .side-nav {
    display: none !important;
    list-style: none !important;
    padding: 0;
    margin: 0;
    position: fixed;
    top: 120px;
    right: 90px;
    width: 280px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.15);
}

.actions-sidebar.active .side-nav {
    display: block !important;
}

.actions-sidebar .side-nav li {
    display: list-item !important;
    list-style: none !important;
    margin: 0;
    padding: 0;
    border-bottom: 1px solid #f0f0f0;
}

.actions-sidebar .side-nav li.heading {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 15px 20px;
    font-weight: bold;
    font-size: 14px;
    border-radius: 12px 12px 0 0;
    border-bottom: none;
}

.actions-sidebar .side-nav li a {
    display: block;
    padding: 12px 20px;
    color: #333;
    text-decoration: none;
    transition: all 0.3s ease;
}

.actions-sidebar .side-nav li a:hover {
    background: #f8f9ff;
    color: #667eea;
    padding-left: 25px;
}

.actions-sidebar .menu-toggle {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    transition: all 0.3s ease;
}

.actions-sidebar .menu-toggle:hover {
    transform: scale(1.1) rotate(90deg);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.actions-sidebar.active .menu-toggle {
    background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.actions-sidebar.active .menu-toggle i {
    transform: rotate(180deg);
}


/* ===== FIX: Actions Sidebar Dropdown ===== */
nav.actions-sidebar ul.side-nav {
    display: none !important;
    position: fixed;
    top: 180px;
    right: 20px;
    width: 280px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.15);
    list-style: none !important;
    padding: 0 !important;
    margin: 0 !important;
    z-index: 999;
    opacity: 0;
    visibility: hidden;
    transform: translateX(20px);
    transition: all 0.3s ease;
}

nav.actions-sidebar.active ul.side-nav {
    display: block !important;
    opacity: 1;
    visibility: visible;
    transform: translateX(0);
}

nav.actions-sidebar ul.side-nav li {
    display: block !important;
    list-style: none !important;
    margin: 0 !important;
    padding: 0 !important;
}

/* ===== Right-Click Context Menu ===== */
.context-menu {
    position: fixed;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
    padding: 8px 0;
    z-index: 10000;
    min-width: 180px;
    display: none;
}

.context-menu.active {
    display: block;
}

.context-menu-item {
    padding: 10px 20px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #333;
    text-decoration: none;
}

.context-menu-item:hover {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.context-menu-item i {
    width: 20px;
    text-align: center;
}

.context-menu-divider {
    height: 1px;
    background: #e0e0e0;
    margin: 5px 0;
}

/* Row highlighting on hover */
table tbody tr:hover {
    background-color: #f8f9ff !important;
    cursor: pointer;
}

table tbody tr.context-active {
    background-color: #e8ecff !important;
}


/* ===== Drag to Scroll ===== */
.table-responsive,
.index.content {
    cursor: grab;
    user-select: none;
}

.table-responsive.dragging,
.index.content.dragging {
    cursor: grabbing !important;
    user-select: none !important;
}

.table-responsive.dragging *,
.index.content.dragging * {
    cursor: grabbing !important;
    user-select: none !important;
}

/* Prevent text selection during drag */
.table-responsive.dragging a,
.table-responsive.dragging button {
    pointer-events: none;
}

.elegant-menu {
    cursor: grab;
    user-select: none;
}

.elegant-menu.dragging {
    cursor: grabbing !important;
    user-select: none !important;
}


/* ===================================
   PAGINATION STYLES
   =================================== */

/* Pagination Container */
.paginator {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 15px;
    padding: 20px;
    margin: 20px 0;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

/* Pagination List */
.paginator ul.pagination {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 6px;
    list-style: none;
    margin: 0;
    padding: 0;
}

/* Pagination Items */
.paginator ul.pagination li {
    margin: 0;
    list-style: none;
}

/* Pagination Links */
.paginator ul.pagination li a,
.paginator ul.pagination li span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 40px;
    height: 40px;
    padding: 8px 12px;
    font-size: 14px;
    font-weight: 500;
    color: #495057;
    background: #fff;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    text-decoration: none;
    transition: all 0.3s ease;
    cursor: pointer;
    user-select: none;
}

/* Hover Effect */
.paginator ul.pagination li a:hover {
    color: #fff;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* Active Page */
.paginator ul.pagination li.active a,
.paginator ul.pagination li.active span {
    color: #fff;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* Disabled State */
.paginator ul.pagination li.disabled a,
.paginator ul.pagination li.disabled span {
    color: #adb5bd;
    background: #f8f9fa;
    border-color: #e9ecef;
    cursor: not-allowed;
    opacity: 0.6;
}

.paginator ul.pagination li.disabled a:hover {
    transform: none;
    box-shadow: none;
    background: #f8f9fa;
    border-color: #e9ecef;
    color: #adb5bd;
}

/* First/Last Page Buttons */
.paginator ul.pagination li:first-child a,
.paginator ul.pagination li:last-child a {
    min-width: 45px;
    font-weight: 600;
}

/* Prev/Next Buttons */
.paginator ul.pagination li a i {
    font-size: 12px;
}

/* Pagination Info Text */
.paginator .pagination-info {
    margin: 0;
    padding: 8px 16px;
    font-size: 14px;
    color: #6c757d;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 20px;
    text-align: center;
    font-weight: 500;
}

/* Desktop Enhancements */
@media (min-width: 768px) {
    .paginator {
        flex-direction: row;
        justify-content: space-between;
        padding: 25px 30px;
    }
    
    .paginator ul.pagination {
        flex-wrap: nowrap;
        gap: 8px;
    }
    
    .paginator ul.pagination li a,
    .paginator ul.pagination li span {
        min-width: 44px;
        height: 44px;
        font-size: 15px;
    }
    
    .paginator .pagination-info {
        font-size: 15px;
        padding: 10px 20px;
    }
}

/* Mobile Optimizations */
@media (max-width: 767px) {
    .paginator {
        padding: 15px 10px;
        gap: 12px;
        margin: 15px 0;
    }
    
    .paginator ul.pagination {
        gap: 4px;
        max-width: 100%;
    }
    
    .paginator ul.pagination li a,
    .paginator ul.pagination li span {
        min-width: 36px;
        height: 36px;
        padding: 6px 10px;
        font-size: 13px;
    }
    
    /* Hide text on mobile, show icons only for prev/next */
    .paginator ul.pagination li a {
        white-space: nowrap;
    }
    
    /* Smaller info text on mobile */
    .paginator .pagination-info {
        font-size: 12px;
        padding: 6px 12px;
        max-width: 100%;
        word-break: break-word;
    }
    
    /* Stack on very small screens */
    @media (max-width: 480px) {
        .paginator ul.pagination li a,
        .paginator ul.pagination li span {
            min-width: 32px;
            height: 32px;
            padding: 5px 8px;
            font-size: 12px;
        }
        
        .paginator .pagination-info {
            font-size: 11px;
        }
    }
}

/* Touch Device Improvements */
@media (hover: none) and (pointer: coarse) {
    .paginator ul.pagination li a,
    .paginator ul.pagination li span {
        min-width: 44px;
        height: 44px;
        /* Larger touch targets for mobile */
    }
    
    .paginator ul.pagination li a:active {
        transform: scale(0.95);
        box-shadow: 0 2px 6px rgba(102, 126, 234, 0.2);
    }
}

/* Smooth Scrolling Animation */
.paginator ul.pagination li a {
    position: relative;
    overflow: hidden;
}

.paginator ul.pagination li a::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.3);
    transform: translate(-50%, -50%);
    transition: width 0.6s, height 0.6s;
}

.paginator ul.pagination li a:active::before {
    width: 100px;
    height: 100px;
}

/* ===================================
   TABLE HEADER (TH) STYLES
   =================================== */

/* Base Table Header Styles */
.index.content table thead {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    position: sticky;
    top: 0;
    z-index: 10;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.index.content table thead th {
    padding: 16px 12px;
    font-size: 14px;
    font-weight: 600;
    color: #ffffff;
    text-align: left;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
    border: none;
    border-bottom: 3px solid rgba(255, 255, 255, 0.3);
    position: relative;
    user-select: none;
}

/* Sortable Column Headers */
.index.content table thead th a {
    color: #ffffff;
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
}

.index.content table thead th a:hover {
    color: #ffd700;
    transform: translateX(2px);
}

/* Sort Icons */
.index.content table thead th a::after {
    content: '';
    font-size: 12px;
    opacity: 0.5;
    transition: opacity 0.3s ease;
}

.index.content table thead th a:hover::after {
    opacity: 1;
}

/* Active Sort Indicator */
.index.content table thead th.sorted-asc a::after {
    content: '';
    opacity: 1;
    color: #ffd700;
}

.index.content table thead th.sorted-desc a::after {
    content: '';
    opacity: 1;
    color: #ffd700;
}

/* Actions Column Header */
.index.content table thead th.actions {
    text-align: center;
    min-width: 160px;
    background: rgba(0, 0, 0, 0.1);
}

/* Column Separators */
.index.content table thead th:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 20%;
    height: 60%;
    width: 1px;
    background: rgba(255, 255, 255, 0.2);
}

/* Hover Effect on Headers */
.index.content table thead th:hover {
    background: rgba(255, 255, 255, 0.1);
}

/* Desktop Enhancements */
@media (min-width: 768px) {
    .index.content table thead th {
        padding: 18px 16px;
        font-size: 15px;
    }
    
    .index.content table thead th a {
        gap: 10px;
    }
}

/* Tablet Styles */
@media (max-width: 767px) and (min-width: 481px) {
    .index.content table thead th {
        padding: 14px 10px;
        font-size: 13px;
        letter-spacing: 0.3px;
    }
    
    .index.content table thead th.actions {
        min-width: 140px;
    }
}

/* Mobile Optimizations */
@media (max-width: 480px) {
    .index.content table thead {
        position: sticky;
        top: 0;
    }
    
    .index.content table thead th {
        padding: 12px 8px;
        font-size: 11px;
        letter-spacing: 0.2px;
        white-space: normal;
        word-break: break-word;
        min-width: 80px;
    }
    
    /* Smaller sort icons on mobile */
    .index.content table thead th a::after {
        font-size: 10px;
    }
    
    /* Compact actions header */
    .index.content table thead th.actions {
        min-width: 100px;
        font-size: 10px;
        padding: 10px 5px;
    }
    
    /* Remove column separators on very small screens */
    .index.content table thead th:not(:last-child)::after {
        display: none;
    }
}

/* Very Small Screens */
@media (max-width: 360px) {
    .index.content table thead th {
        padding: 10px 5px;
        font-size: 10px;
        min-width: 60px;
    }
    
    .index.content table thead th.actions {
        min-width: 80px;
    }
}

/* Touch Device Improvements */
@media (hover: none) and (pointer: coarse) {
    .index.content table thead th {
        padding: 16px 12px;
        /* Larger touch targets */
    }
    
    .index.content table thead th a {
        min-height: 44px;
        display: flex;
        align-items: center;
    }
}

/* Filter Row (if exists) */
.index.content table thead .filter-row th {
    padding: 8px;
    background: rgba(255, 255, 255, 0.95);
    border-bottom: 2px solid #dee2e6;
}

.index.content table thead .filter-row input {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    font-size: 13px;
    transition: all 0.3s ease;
}

.index.content table thead .filter-row input:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* Zebra Striping for Table Body */
.index.content table tbody tr:nth-child(even) {
    background: #f8f9fa;
}

.index.content table tbody tr:nth-child(odd) {
    background: #ffffff;
}

/* Row Hover Effect */
.index.content table tbody tr:hover {
    background: linear-gradient(90deg, #f0f4ff 0%, #e8f0ff 100%);
    transform: scale(1.01);
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
    transition: all 0.2s ease;
}

/* Table Cell Styles */
.index.content table tbody td {
    padding: 12px;
    font-size: 14px;
    color: #495057;
    border-bottom: 1px solid #e9ecef;
    vertical-align: middle;
}

@media (max-width: 767px) {
    .index.content table tbody td {
        padding: 10px 8px;
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .index.content table tbody td {
        padding: 8px 5px;
        font-size: 12px;
    }
}

/* Actions Column Cells */
.index.content table tbody td.actions {
    text-align: center;
    white-space: nowrap;
}

/* Smooth Scrolling for Sticky Header */
.index.content {
    scroll-behavior: smooth;
}

/* Loading State (optional) */
.index.content table.loading {
    opacity: 0.6;
    pointer-events: none;
}

/* Print Styles */
@media print {
    .index.content table thead {
        background: #667eea !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    
    .index.content table thead th {
        color: #ffffff !important;
        border-bottom: 2px solid #333 !important;
    }
}

/* ===================================
   THUMBNAIL COLUMN STYLES
   =================================== */

/* Thumbnail Column Header */
th:has(+ th):first-child + th,
.index.content table thead th:nth-child(2) {
    width: 80px;
    text-align: center;
}

/* Empty Filter Cell for Thumbnail */
.filter-thumbnail {
    background: transparent !important;
    border: none !important;
    width: 80px;
}

/* Thumbnail Cell in Table */
.thumbnail-cell {
    width: 80px;
    text-align: center;
    vertical-align: middle;
    padding: 8px !important;
}

/* Thumbnail Image */
.table-thumbnail {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 6px;
    border: 2px solid #dee2e6;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
    cursor: pointer;
}

.table-thumbnail:hover {
    transform: scale(2.5);
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 1000;
    position: relative;
}

/* No Thumbnail Placeholder */
.no-thumbnail {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 50px;
    height: 50px;
    background: #f8f9fa;
    border: 2px dashed #dee2e6;
    border-radius: 6px;
    color: #adb5bd;
    font-size: 20px;
}

/* Mobile Adjustments */
@media (max-width: 767px) {
    .thumbnail-cell {
        width: 60px;
        padding: 5px !important;
    }
    
    .table-thumbnail {
        width: 40px;
        height: 40px;
    }
    
    .table-thumbnail:hover {
        transform: scale(2);
    }
    
    .no-thumbnail {
        width: 40px;
        height: 40px;
        font-size: 16px;
    }
}

@media (max-width: 480px) {
    .thumbnail-cell {
        width: 50px;
        padding: 3px !important;
    }
    
    .table-thumbnail {
        width: 35px;
        height: 35px;
    }
    
    .no-thumbnail {
        width: 35px;
        height: 35px;
        font-size: 14px;
    }
}

/* ===================================
   ADDRESS SELECT STYLES
   =================================== */

/* Address Card */
.card.bg-light .card-title {
    color: #495057;
    font-weight: 600;
    margin-bottom: 8px;
}

.card.bg-light .text-muted.small {
    font-size: 12px;
    color: #6c757d !important;
}

/* Address Select Fields */
.address-select {
    border: 2px solid #dee2e6;
    transition: all 0.3s ease;
}

.address-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.address-select:disabled {
    background-color: #e9ecef;
    cursor: not-allowed;
}

/* Required Field Indicator */
.form-label.required span.text-danger {
    font-size: 14px;
    margin-left: 2px;
}

/* Address Loading Indicator */
.address-loading {
    text-align: center;
    padding: 10px;
    color: #667eea;
    font-size: 14px;
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% {
        opacity: 1;
    }
    50% {
        opacity: 0.5;
    }
}

.address-loading .fa-spinner {
    margin-right: 8px;
}

/* Mobile Responsive */
@media (max-width: 767px) {
    .col-md-3.mb-2 {
        flex: 0 0 100%;
        max-width: 100%;
    }
    
    .card.bg-light .card-title {
        font-size: 16px;
    }
}
