/**
 * SLM Framework - Custom Application JavaScript
 *
 * This file contains custom JavaScript for your application.
 * Add your project-specific JS here.
 */

(function() {
    'use strict';

    /**
     * Initialize application when DOM is ready
     */
    document.addEventListener('DOMContentLoaded', function() {
        initSidebar();
        initTooltips();
        initFeatherIcons();
        initFormValidation();
    });

    /**
     * Sidebar toggle functionality
     */
    function initSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const sidebarToggle = document.querySelector('[data-toggle="sidebar"]');

        if (sidebarToggle && sidebar) {
            sidebarToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');

                // Store preference in localStorage
                const isCollapsed = sidebar.classList.contains('collapsed');
                localStorage.setItem('sidebarCollapsed', isCollapsed);
            });

            // Restore preference on page load
            const savedState = localStorage.getItem('sidebarCollapsed');
            if (savedState === 'true') {
                sidebar.classList.add('collapsed');
            }
        }

        // Mobile sidebar toggle
        const mobileToggle = document.querySelector('[data-toggle="sidebar-mobile"]');
        if (mobileToggle && sidebar) {
            mobileToggle.addEventListener('click', function() {
                sidebar.classList.toggle('show');
            });
        }
    }

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

    /**
     * Initialize Feather icons
     */
    function initFeatherIcons() {
        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }

    /**
     * Initialize form validation
     */
    function initFormValidation() {
        // Fetch all forms that need custom validation
        const forms = document.querySelectorAll('.needs-validation');

        forms.forEach(function(form) {
            form.addEventListener('submit', function(event) {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }

    /**
     * Format currency values
     * @param {number} value - The value to format
     * @param {string} currency - Currency code (default: USD)
     * @returns {string} Formatted currency string
     */
    window.formatCurrency = function(value, currency = 'USD') {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(value);
    };

    /**
     * Format date values
     * @param {string|Date} date - The date to format
     * @param {object} options - Intl.DateTimeFormat options
     * @returns {string} Formatted date string
     */
    window.formatDate = function(date, options = {}) {
        const defaultOptions = {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        };

        const finalOptions = { ...defaultOptions, ...options };
        const dateObj = date instanceof Date ? date : new Date(date);

        return new Intl.DateTimeFormat('en-US', finalOptions).format(dateObj);
    };

    /**
     * Format timestamp from Elasticsearch (milliseconds)
     * @param {number} timestamp - Timestamp in milliseconds
     * @returns {string} Formatted date string
     */
    window.formatTimestamp = function(timestamp) {
        if (!timestamp) return '-';
        return formatDate(new Date(timestamp));
    };

    /**
     * Debounce function for performance optimization
     * @param {Function} func - Function to debounce
     * @param {number} wait - Wait time in milliseconds
     * @returns {Function} Debounced function
     */
    window.debounce = function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    /**
     * Escape HTML to prevent XSS
     * @param {string} text - Text to escape
     * @returns {string} Escaped text
     */
    window.escapeHtml = function(text) {
        if (text === null || text === undefined) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    /**
     * Copy text to clipboard
     * @param {string} text - Text to copy
     * @returns {Promise} Promise that resolves when text is copied
     */
    window.copyToClipboard = function(text) {
        if (navigator.clipboard && window.isSecureContext) {
            return navigator.clipboard.writeText(text);
        } else {
            // Fallback for older browsers
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            return new Promise((resolve, reject) => {
                document.execCommand('copy') ? resolve() : reject();
                textArea.remove();
            });
        }
    };

    /**
     * Get URL parameter
     * @param {string} name - Parameter name
     * @returns {string|null} Parameter value or null
     */
    window.getUrlParam = function(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    };

    /**
     * Set URL parameter without page reload
     * @param {string} name - Parameter name
     * @param {string} value - Parameter value
     */
    window.setUrlParam = function(name, value) {
        const url = new URL(window.location);
        url.searchParams.set(name, value);
        window.history.replaceState({}, '', url);
    };

    /**
     * Remove URL parameter without page reload
     * @param {string} name - Parameter name
     */
    window.removeUrlParam = function(name) {
        const url = new URL(window.location);
        url.searchParams.delete(name);
        window.history.replaceState({}, '', url);
    };

    /**
     * DataTables default configuration
     */
    if (typeof $.fn.DataTable !== 'undefined') {
        $.extend(true, $.fn.dataTable.defaults, {
            processing: true,
            serverSide: true,
            responsive: true,
            language: {
                processing: '<div class="loading-spinner"></div>',
                emptyTable: 'No records found',
                zeroRecords: 'No matching records found',
                info: 'Showing _START_ to _END_ of _TOTAL_ entries',
                infoEmpty: 'Showing 0 to 0 of 0 entries',
                infoFiltered: '(filtered from _MAX_ total entries)',
                lengthMenu: 'Show _MENU_ entries',
                search: 'Search:',
                paginate: {
                    first: '<i data-feather="chevrons-left"></i>',
                    last: '<i data-feather="chevrons-right"></i>',
                    next: '<i data-feather="chevron-right"></i>',
                    previous: '<i data-feather="chevron-left"></i>'
                }
            },
            drawCallback: function() {
                // Re-initialize Feather icons after table draw
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
                // Re-initialize tooltips
                const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
                tooltips.forEach(el => new bootstrap.Tooltip(el));
            }
        });
    }

    /**
     * Select2 default configuration
     */
    if (typeof $.fn.select2 !== 'undefined') {
        $.fn.select2.defaults.set('theme', 'bootstrap-5');
        $.fn.select2.defaults.set('allowClear', true);
        $.fn.select2.defaults.set('width', '100%');
    }

})();
