// assets/js/dinar.js
 $(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        theme: 'default',
        width: '100%'
    });
    
    // --- LOGIKA TOGGLE SIDEBAR (UPDATE) ---

    // 1. Cek status localStorage saat load (untuk Desktop)
    // Jika sebelumnya user menutup sidebar, pertahankan tertutup
    if ($(window).width() > 1024) {
        const isCollapsed = localStorage.getItem('sidebarCollapsed');
        if (isCollapsed === 'true') {
            $('body').addClass('sidebar-collapsed');
        }
    }

    // 2. Fungsi Toggle saat Burger diklik
    $('#sidebarToggle').on('click', function() {
        const windowWidth = $(window).width();
        
        if (windowWidth > 1024) {
            // MODE DESKTOP: 
            // Toggle class 'sidebar-collapsed' di body.
            // CSS akan menggeser sidebar ke kiri dan memperbesar konten.
            $('body').toggleClass('sidebar-collapsed');
            
            // Simpan state ke localStorage agar ingat saat refresh
            if ($('body').hasClass('sidebar-collapsed')) {
                localStorage.setItem('sidebarCollapsed', 'true');
            } else {
                localStorage.setItem('sidebarCollapsed', 'false');
            }
        } else {
            // MODE MOBILE: 
            // Toggle class 'active' untuk menampilkan sidebar sebagai overlay.
            $('#sidebar').toggleClass('active');
            $('#sidebarOverlay').toggleClass('active');
        }
    });

    // 3. Tutup sidebar mobile saat klik overlay
    $('#sidebarOverlay').on('click', function() {
        $('#sidebar').removeClass('active');
        $(this).removeClass('active');
    });

    // --- AKHIR LOGIKA TOGGLE ---

    // Initialize DataTables
    if ($('.data-table').length) {
        $('.data-table').DataTable({
            responsive: true,
            pageLength: 10,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            language: {
                search: "",
                searchPlaceholder: "Search...",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty: "No entries available",
                infoFiltered: "(filtered from _MAX_ total entries)",
                paginate: {
                    first: '<i class="mdi mdi-chevron-double-left"></i>',
                    last: '<i class="mdi mdi-chevron-double-right"></i>',
                    next: '<i class="mdi mdi-chevron-right"></i>',
                    previous: '<i class="mdi mdi-chevron-left"></i>'
                },
                zeroRecords: "No matching records found"
            },
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        });
    }
    
    // Delete confirmation with SweetAlert2
    $('.btn-delete').on('click', function(e) {
        e.preventDefault();
        const form = $(this).closest('form');
        const itemName = $(this).data('name') || 'this item';
        
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to delete "${itemName}". This action cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel',
            customClass: {
                confirmButton: 'btn btn-danger me-2',
                cancelButton: 'btn btn-secondary'
            },
            buttonsStyling: false
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
    });
    
    // Toast notification
    window.showToast = function(message, type = 'success') {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer);
                toast.addEventListener('mouseleave', Swal.resumeTimer);
            }
        });
        
        Toast.fire({
            icon: type,
            title: message
        });
    };
    
    // Check for flash messages
    const flashMessage = localStorage.getItem('flashMessage');
    if (flashMessage) {
        const msg = JSON.parse(flashMessage);
        showToast(msg.text, msg.type);
        localStorage.removeItem('flashMessage');
    }
    
    // Form validation styling
    $('form').on('submit', function() {
        $(this).find('button[type="submit"]').addClass('loading').prop('disabled', true);
    });
    
    // Tooltip initialization
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltipTriggerList.forEach(el => new bootstrap.Tooltip(el));
    
    // Animate cards on scroll
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);
    
    document.querySelectorAll('.card, .stat-card').forEach(el => {
        observer.observe(el);
    });
});