/**
 * Admin Dashboard JavaScript Bundle
 *
 * This file bundles all common JavaScript modules for the admin dashboard.
 * It provides a global `App` object for use in inline scripts during
 * the transition period from inline scripts to modules.
 *
 * Usage in Blade templates:
 *
 *   // Initialize DataTable
 *   const table = App.initDataTable('#customerTable');
 *
 *   // Delete with confirmation
 *   App.ajaxDelete('/admin/customers/1', {
 *       onSuccess: () => table.row('#row-1').remove().draw()
 *   });
 *
 *   // Show notification
 *   App.showSuccess('Item saved!');
 *
 *   // Validate form
 *   const errors = App.validateForm('#myForm', {
 *       email: ['required', 'email']
 *   });
 */

// Import modules
import {
    initDataTable,
    initServerSideDataTable,
    reloadDataTable,
    destroyDataTable
} from './modules/datatable-init';

import {
    ajaxGet,
    ajaxPost,
    ajaxPut,
    ajaxDelete,
    ajaxSubmitForm
} from './modules/ajax-handler';

import {
    initToastr,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    showLoading,
    clearAll as clearToasts,
    showFromResponse,
    showFlashMessages
} from './modules/toast-notifications';

import {
    validators,
    addCustomValidator,
    validateForm,
    showFormErrors,
    clearFormErrors,
    setupRealtimeValidation
} from './modules/form-validation';

// Create global App object
window.App = {
    // DataTable functions
    initDataTable,
    initServerSideDataTable,
    reloadDataTable,
    destroyDataTable,

    // AJAX functions
    ajaxGet,
    ajaxPost,
    ajaxPut,
    ajaxDelete,
    ajaxSubmitForm,

    // Toast notifications
    initToastr,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    showLoading,
    clearToasts,
    showFromResponse,
    showFlashMessages,

    // Form validation
    validators,
    addCustomValidator,
    validateForm,
    showFormErrors,
    clearFormErrors,
    setupRealtimeValidation,

    // Utility functions
    getCsrfToken: () => document.querySelector('meta[name="csrf-token"]')?.content,

    // Format currency (Indian Rupees)
    formatCurrency: (amount, decimals = 2) => {
        return new Intl.NumberFormat('en-IN', {
            style: 'currency',
            currency: 'INR',
            minimumFractionDigits: decimals
        }).format(amount);
    },

    // Format number with Indian comma system
    formatNumber: (num) => {
        return new Intl.NumberFormat('en-IN').format(num);
    },

    // Format date
    formatDate: (date, format = 'dd/mm/yyyy') => {
        const d = new Date(date);
        const pad = (n) => n.toString().padStart(2, '0');
        const tokens = {
            dd: pad(d.getDate()),
            mm: pad(d.getMonth() + 1),
            yyyy: d.getFullYear(),
            yy: d.getFullYear().toString().slice(-2)
        };
        return format.replace(/dd|mm|yyyy|yy/g, match => tokens[match]);
    },

    // Confirm action with SweetAlert
    confirmAction: async (options = {}) => {
        const defaults = {
            title: 'Are you sure?',
            text: '',
            icon: 'warning',
            confirmButtonText: 'Yes',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#6c757d',
            showCancelButton: true
        };
        const config = { ...defaults, ...options };

        if (window.Swal) {
            const result = await Swal.fire(config);
            return result.isConfirmed;
        } else {
            return confirm(config.title + (config.text ? '\n' + config.text : ''));
        }
    },

    // Debounce function
    debounce: (func, wait = 300) => {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // Throttle function
    throttle: (func, limit = 300) => {
        let inThrottle;
        return function executedFunction(...args) {
            if (!inThrottle) {
                func(...args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', () => {
    // Initialize Toastr
    initToastr();

    // Show flash messages from session
    showFlashMessages();

    // Log that App is ready (dev only)
    if (process.env.NODE_ENV === 'development') {
        console.log('App initialized. Available methods:', Object.keys(window.App));
    }
});

// Export for ES module usage
export {
    initDataTable,
    initServerSideDataTable,
    ajaxGet,
    ajaxPost,
    ajaxDelete,
    showSuccess,
    showError,
    validateForm
};

export default window.App;
