// Mobile Enhancements untuk Sistem Informasi Anggota PKS

$(document).ready(function() {
    // Mobile sidebar functionality
    function initMobileSidebar() {
        const sidebar = $('.sidebar');
        const overlay = $('.sidebar-overlay');
        const toggle = $('#sidebarToggle');
        const body = $('body');
        
        // Toggle sidebar
        toggle.on('click', function(e) {
            e.preventDefault();
            sidebar.toggleClass('show');
            overlay.toggleClass('show');
            body.toggleClass('sidebar-open');
        });
        
        // Close sidebar when clicking overlay
        overlay.on('click', function() {
            sidebar.removeClass('show');
            overlay.removeClass('show');
            body.removeClass('sidebar-open');
        });
        
        // Close sidebar when clicking outside on mobile
        $(document).on('click', function(e) {
            if ($(window).width() <= 768) {
                if (!$(e.target).closest('.sidebar, #sidebarToggle').length) {
                    sidebar.removeClass('show');
                    overlay.removeClass('show');
                    body.removeClass('sidebar-open');
                }
            }
        });
        
        // Handle window resize
        $(window).on('resize', function() {
            if ($(window).width() > 768) {
                sidebar.removeClass('show');
                overlay.removeClass('show');
                body.removeClass('sidebar-open');
            }
        });
    }
    
    // Mobile table enhancements
    function initMobileTable() {
        if ($(window).width() <= 768) {
            // Add horizontal scroll indicator
            $('.table-responsive').each(function() {
                const $this = $(this);
                const table = $this.find('table');
                
                if (table[0].scrollWidth > $this[0].clientWidth) {
                    $this.addClass('has-scroll');
                }
            });
            
            // Add touch scrolling
            $('.table-responsive').on('touchstart', function() {
                $(this).addClass('scrolling');
            });
            
            $('.table-responsive').on('touchend', function() {
                const $this = $(this);
                setTimeout(() => {
                    $this.removeClass('scrolling');
                }, 150);
            });
        }
    }
    
    // Mobile form enhancements
    function initMobileForms() {
        // Prevent zoom on input focus (iOS)
        $('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], textarea, select').on('focus', function() {
            if ($(window).width() <= 768) {
                $('meta[name="viewport"]').attr('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
            }
        });
        
        $('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], textarea, select').on('blur', function() {
            if ($(window).width() <= 768) {
                $('meta[name="viewport"]').attr('content', 'width=device-width, initial-scale=1.0');
            }
        });
        
        // Improve select2 mobile experience
        if ($(window).width() <= 768) {
            $('.select2').select2({
                theme: 'bootstrap-5',
                placeholder: 'Pilih...',
                dropdownParent: $('body'),
                width: '100%'
            });
        }
    }
    
    // Mobile button enhancements
    function initMobileButtons() {
        // Add ripple effect to buttons
        $('.btn').on('touchstart', function(e) {
            const $this = $(this);
            const ripple = $('<span class="ripple"></span>');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.originalEvent.touches[0].clientX - rect.left - size / 2;
            const y = e.originalEvent.touches[0].clientY - rect.top - size / 2;
            
            ripple.css({
                width: size,
                height: size,
                left: x,
                top: y
            });
            
            $this.append(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    }
    
    // Mobile card enhancements
    function initMobileCards() {
        // Add touch feedback to cards
        $('.card').on('touchstart', function() {
            $(this).addClass('touch-active');
        });
        
        $('.card').on('touchend touchcancel', function() {
            const $this = $(this);
            setTimeout(() => {
                $this.removeClass('touch-active');
            }, 150);
        });
    }
    
    // Mobile navigation enhancements
    function initMobileNavigation() {
        // Smooth scroll for anchor links
        $('a[href^="#"]').on('click', function(e) {
            e.preventDefault();
            const target = $(this.getAttribute('href'));
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top - 70
                }, 500);
            }
        });
        
        // Close mobile menu when clicking on links
        $('.sidebar .nav-link').on('click', function() {
            if ($(window).width() <= 768) {
                $('.sidebar').removeClass('show');
                $('.sidebar-overlay').removeClass('show');
                $('body').removeClass('sidebar-open');
            }
        });
    }
    
    // Mobile performance optimizations
    function initMobilePerformance() {
        // Lazy load images
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.classList.remove('lazy');
                        imageObserver.unobserve(img);
                    }
                });
            });
            
            $('.lazy').each(function() {
                imageObserver.observe(this);
            });
        }
        
        // Debounce resize events
        let resizeTimer;
        $(window).on('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(() => {
                initMobileTable();
                initMobileForms();
            }, 250);
        });
    }
    
    // Mobile accessibility enhancements
    function initMobileAccessibility() {
        // Add ARIA labels for mobile
        $('.navbar-toggler').attr('aria-label', 'Toggle navigation menu');
        $('.sidebar').attr('aria-label', 'Navigation menu');
        
        // Improve focus management
        $('.sidebar .nav-link').on('focus', function() {
            if ($(window).width() <= 768) {
                $('.sidebar').addClass('show');
                $('.sidebar-overlay').addClass('show');
                $('body').addClass('sidebar-open');
            }
        });
        
        // Keyboard navigation for mobile menu
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('.sidebar').hasClass('show')) {
                $('.sidebar').removeClass('show');
                $('.sidebar-overlay').removeClass('show');
                $('body').removeClass('sidebar-open');
            }
        });
    }
    
    // Initialize all mobile enhancements
    function initMobileEnhancements() {
        initMobileSidebar();
        initMobileTable();
        initMobileForms();
        initMobileButtons();
        initMobileCards();
        initMobileNavigation();
        initMobilePerformance();
        initMobileAccessibility();
    }
    
    // Run initialization
    initMobileEnhancements();
    
    // Re-initialize on page load (for AJAX content)
    $(document).on('DOMNodeInserted', function() {
        initMobileTable();
        initMobileForms();
        initMobileButtons();
        initMobileCards();
    });
});

// Add CSS for mobile enhancements
const mobileStyles = `
<style>
/* Ripple effect for buttons */
.btn {
    position: relative;
    overflow: hidden;
}

.ripple {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0);
    animation: ripple-animation 0.6s linear;
    pointer-events: none;
}

@keyframes ripple-animation {
    to {
        transform: scale(4);
        opacity: 0;
    }
}

/* Touch feedback for cards */
.card.touch-active {
    transform: scale(0.98);
    transition: transform 0.1s ease;
}

/* Mobile table scroll indicator */
.table-responsive.has-scroll::after {
    content: "← Scroll untuk melihat lebih banyak →";
    display: block;
    text-align: center;
    font-size: 0.75rem;
    color: #6c757d;
    padding: 0.5rem;
    background: #f8f9fa;
    border-top: 1px solid #dee2e6;
    position: sticky;
    bottom: 0;
    z-index: 10;
}

.table-responsive.scrolling::after {
    opacity: 0.7;
}

/* Lazy loading images */
.lazy {
    opacity: 0;
    transition: opacity 0.3s;
}

.lazy.loaded {
    opacity: 1;
}

/* Mobile sidebar improvements */
@media (max-width: 768px) {
    .sidebar {
        transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    .sidebar-overlay {
        transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    .sidebar.show {
        box-shadow: 2px 0 20px rgba(0, 0, 0, 0.3);
    }
}

/* Mobile form improvements */
@media (max-width: 768px) {
    .form-control:focus,
    .form-select:focus {
        transform: scale(1.02);
        transition: transform 0.2s ease;
    }
    
    .btn:active {
        transform: scale(0.95);
        transition: transform 0.1s ease;
    }
}
</style>
`;

// Inject mobile styles
$('head').append(mobileStyles);
