/**
 * Viartas Admin Theme - Main JavaScript
 * Modern Admin Panel using jQuery and Bootstrap 5
 */

// Import dependencies
import $ from 'jquery';
import * as bootstrap from 'bootstrap';
import PerfectScrollbar from 'perfect-scrollbar';

// Make jQuery globally available
window.$ = window.jQuery = $;
window.bootstrap = bootstrap;

/**
 * Viartas Admin Theme Core
 */
const ViartasTheme = (function() {
    'use strict';

    // Configuration
    const config = {
        sidebarCollapsedKey: 'viartas_sidebar_collapsed',
        themeKey: 'viartas_theme',
        animationDuration: 250
    };

    // Cache DOM elements
    let $sidebar;
    let $sidebarBackdrop;
    let $main;
    let $header;
    let $sidebarToggle;
    let sidebarScrollbar;

    /**
     * Initialize the theme
     */
    function init() {
        cacheElements();
        bindEvents();
        initSidebar();
        initHeader();
        initDropdowns();
        initTooltips();
        initSearchShortcut();
        initPerfectScrollbar();
        restoreState();
    }

    /**
     * Cache DOM elements
     */
    function cacheElements() {
        $sidebar = $('.vt-sidebar');
        $sidebarBackdrop = $('.vt-sidebar-backdrop');
        $main = $('.vt-main');
        $header = $('.vt-header');
        $sidebarToggle = $('[data-vt-toggle="sidebar"]');
    }

    /**
     * Bind event handlers
     */
    function bindEvents() {
        // Sidebar toggle
        $sidebarToggle.on('click', toggleSidebar);

        // Mobile backdrop click
        $sidebarBackdrop.on('click', closeMobileSidebar);

        // Submenu toggle
        $('.vt-menu-item.has-submenu > .vt-menu-link').on('click', toggleSubmenu);

        // Window resize
        $(window).on('resize', handleResize);

        // Escape key to close modals/sidebar
        $(document).on('keydown', handleEscapeKey);
    }

    /**
     * Initialize sidebar
     */
    function initSidebar() {
        // Set active menu item based on current URL
        const currentPath = window.location.pathname;

        $('.vt-menu-link').each(function() {
            const $link = $(this);
            const href = $link.attr('href');

            if (href && currentPath.includes(href) && href !== '#') {
                $link.addClass('active');

                // Open parent submenu if exists
                const $parentMenu = $link.closest('.vt-submenu');
                if ($parentMenu.length) {
                    $parentMenu.closest('.vt-menu-item').addClass('open');
                }
            }
        });
    }

    /**
     * Initialize header
     */
    function initHeader() {
        // Header scroll effect
        $(window).on('scroll', function() {
            if ($(window).scrollTop() > 10) {
                $header.addClass('scrolled');
            } else {
                $header.removeClass('scrolled');
            }
        });
    }

    /**
     * Toggle sidebar collapsed state
     */
    function toggleSidebar(e) {
        e.preventDefault();

        if ($(window).width() < 1200) {
            // Mobile: Show/hide sidebar
            $sidebar.toggleClass('show');
            $sidebarBackdrop.toggleClass('show');
            $('body').toggleClass('sidebar-open');
        } else {
            // Desktop: Collapse/expand sidebar
            const isCollapsed = $sidebar.hasClass('collapsed');

            $sidebar.toggleClass('collapsed');
            $main.toggleClass('sidebar-collapsed');
            $header.toggleClass('sidebar-collapsed');

            // Save state
            localStorage.setItem(config.sidebarCollapsedKey, !isCollapsed);

            // Update scrollbar
            if (sidebarScrollbar) {
                setTimeout(() => sidebarScrollbar.update(), config.animationDuration);
            }
        }
    }

    /**
     * Close mobile sidebar
     */
    function closeMobileSidebar() {
        $sidebar.removeClass('show');
        $sidebarBackdrop.removeClass('show');
        $('body').removeClass('sidebar-open');
    }

    /**
     * Toggle submenu
     */
    function toggleSubmenu(e) {
        const $link = $(this);
        const $menuItem = $link.closest('.vt-menu-item');

        // Only toggle if has submenu
        if (!$menuItem.hasClass('has-submenu')) return;

        e.preventDefault();

        // Close other open submenus (accordion behavior)
        const $siblings = $menuItem.siblings('.vt-menu-item.open');
        $siblings.removeClass('open').find('.vt-submenu').slideUp(config.animationDuration);

        // Toggle current submenu
        $menuItem.toggleClass('open');
        $menuItem.find('> .vt-submenu').slideToggle(config.animationDuration);
    }

    /**
     * Initialize dropdowns
     */
    function initDropdowns() {
        // Custom dropdown handling
        $('[data-vt-toggle="dropdown"]').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const $dropdown = $(this).closest('.vt-dropdown');
            const isOpen = $dropdown.hasClass('show');

            // Close all dropdowns
            $('.vt-dropdown').removeClass('show');

            // Toggle current
            if (!isOpen) {
                $dropdown.addClass('show');
            }
        });

        // Close dropdowns on outside click
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.vt-dropdown').length) {
                $('.vt-dropdown').removeClass('show');
            }
        });
    }

    /**
     * Initialize Bootstrap tooltips
     */
    function initTooltips() {
        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
    }

    /**
     * Initialize search shortcut (Cmd/Ctrl + K)
     */
    function initSearchShortcut() {
        $(document).on('keydown', function(e) {
            if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                e.preventDefault();
                $('.vt-header-search-input').focus();
            }
        });
    }

    /**
     * Initialize Perfect Scrollbar for sidebar
     */
    function initPerfectScrollbar() {
        const sidebarMenu = document.querySelector('.vt-sidebar-menu');
        if (sidebarMenu) {
            sidebarScrollbar = new PerfectScrollbar(sidebarMenu, {
                wheelSpeed: 0.5,
                wheelPropagation: false,
                minScrollbarLength: 40
            });
        }
    }

    /**
     * Handle window resize
     */
    function handleResize() {
        if ($(window).width() >= 1200) {
            closeMobileSidebar();
        }

        // Update scrollbar
        if (sidebarScrollbar) {
            sidebarScrollbar.update();
        }
    }

    /**
     * Handle Escape key
     */
    function handleEscapeKey(e) {
        if (e.key === 'Escape') {
            closeMobileSidebar();
            $('.vt-dropdown').removeClass('show');
        }
    }

    /**
     * Restore saved state
     */
    function restoreState() {
        // Restore sidebar state
        const sidebarCollapsed = localStorage.getItem(config.sidebarCollapsedKey) === 'true';

        if (sidebarCollapsed && $(window).width() >= 1200) {
            $sidebar.addClass('collapsed');
            $main.addClass('sidebar-collapsed');
            $header.addClass('sidebar-collapsed');
        }

        // Restore theme
        const savedTheme = localStorage.getItem(config.themeKey);
        if (savedTheme) {
            setTheme(savedTheme);
        }
    }

    /**
     * Set theme (light/dark)
     */
    function setTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem(config.themeKey, theme);
    }

    /**
     * Toggle theme
     */
    function toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        setTheme(currentTheme === 'dark' ? 'light' : 'dark');
    }

    /**
     * Show toast notification
     */
    function showToast(options) {
        const defaults = {
            title: 'Notification',
            message: '',
            type: 'info',
            duration: 5000
        };

        const settings = { ...defaults, ...options };

        const icons = {
            success: '<i class="bi bi-check-circle-fill text-success"></i>',
            danger: '<i class="bi bi-x-circle-fill text-danger"></i>',
            warning: '<i class="bi bi-exclamation-circle-fill text-warning"></i>',
            info: '<i class="bi bi-info-circle-fill text-primary"></i>'
        };

        const $toast = $(`
            <div class="vt-toast ${settings.type}">
                <div class="vt-toast-icon">${icons[settings.type]}</div>
                <div class="vt-toast-content">
                    <div class="vt-toast-title">${settings.title}</div>
                    ${settings.message ? `<div class="vt-toast-message">${settings.message}</div>` : ''}
                </div>
                <button class="vt-toast-close">&times;</button>
            </div>
        `);

        let $container = $('.vt-toast-container');
        if (!$container.length) {
            $container = $('<div class="vt-toast-container"></div>');
            $('body').append($container);
        }

        $container.append($toast);

        // Close button
        $toast.find('.vt-toast-close').on('click', function() {
            removeToast($toast);
        });

        // Auto remove
        if (settings.duration > 0) {
            setTimeout(() => removeToast($toast), settings.duration);
        }

        return $toast;
    }

    /**
     * Remove toast notification
     */
    function removeToast($toast) {
        $toast.css({
            opacity: 0,
            transform: 'translateX(100%)'
        });

        setTimeout(() => $toast.remove(), 300);
    }

    /**
     * Show confirmation dialog
     */
    function confirm(options) {
        const defaults = {
            title: 'Are you sure?',
            message: '',
            confirmText: 'Confirm',
            cancelText: 'Cancel',
            confirmClass: 'vt-btn-primary',
            onConfirm: () => {},
            onCancel: () => {}
        };

        const settings = { ...defaults, ...options };

        return new Promise((resolve) => {
            const $modal = $(`
                <div class="modal fade" tabindex="-1">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content" style="border-radius: var(--vt-radius-lg); border: none;">
                            <div class="modal-header border-0 pb-0">
                                <h5 class="modal-title fw-semibold">${settings.title}</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body py-4">
                                <p class="mb-0 text-muted">${settings.message}</p>
                            </div>
                            <div class="modal-footer border-0 pt-0">
                                <button type="button" class="vt-btn vt-btn-secondary" data-bs-dismiss="modal">${settings.cancelText}</button>
                                <button type="button" class="vt-btn ${settings.confirmClass}" data-confirm="true">${settings.confirmText}</button>
                            </div>
                        </div>
                    </div>
                </div>
            `);

            $('body').append($modal);

            const modal = new bootstrap.Modal($modal[0]);

            $modal.find('[data-confirm="true"]').on('click', function() {
                modal.hide();
                settings.onConfirm();
                resolve(true);
            });

            $modal.on('hidden.bs.modal', function() {
                $modal.remove();
                resolve(false);
            });

            modal.show();
        });
    }

    // Public API
    return {
        init,
        toggleSidebar,
        toggleTheme,
        setTheme,
        showToast,
        confirm
    };
})();

/**
 * DataTable Wrapper for consistent styling
 */
const ViartasDataTable = (function() {
    'use strict';

    function init(selector, options = {}) {
        const defaults = {
            pageLength: 10,
            responsive: true,
            dom: '<"vt-datatable-header"<"vt-datatable-search"f><"vt-datatable-actions">>rt<"vt-datatable-footer"<"vt-datatable-info"i><"vt-datatable-pagination"p>>',
            language: {
                search: '',
                searchPlaceholder: 'Search...',
                paginate: {
                    previous: '<i class="bi bi-chevron-left"></i>',
                    next: '<i class="bi bi-chevron-right"></i>'
                }
            }
        };

        const settings = { ...defaults, ...options };

        // Initialize DataTable if available
        if ($.fn.DataTable) {
            return $(selector).DataTable(settings);
        }

        return null;
    }

    return { init };
})();

/**
 * Chart helpers
 */
const ViartasCharts = (function() {
    'use strict';

    const defaultColors = {
        primary: '#6366f1',
        secondary: '#64748b',
        success: '#10b981',
        danger: '#ef4444',
        warning: '#f59e0b',
        info: '#06b6d4'
    };

    const defaultOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        }
    };

    function getColors() {
        return defaultColors;
    }

    function getDefaultOptions() {
        return defaultOptions;
    }

    return {
        getColors,
        getDefaultOptions
    };
})();

// Initialize on document ready
$(document).ready(function() {
    ViartasTheme.init();
});

// Export for external use
window.ViartasTheme = ViartasTheme;
window.ViartasDataTable = ViartasDataTable;
window.ViartasCharts = ViartasCharts;

export { ViartasTheme, ViartasDataTable, ViartasCharts };
