/**
 * SalonPro X - Main Initialization
 * Core app setup, global event handlers, UI interactions
 */

const SalonPro = {
    config: {
        baseUrl: $('meta[name="base-url"]').attr('content') || '/SalonPro_X_2.0',
        csrfToken: $('meta[name="csrf-token"]').attr('content') || '',
        debug: true
    },

    /**
     * Initialize the application
     */
    init: function() {
        this.initSidebar();
        this.initTooltips();
        this.initGlobalSearch();
        this.initNotifications();
        this.initAutoDismissAlerts();
        this.initConfirmDeletes();
        this.initSelect2();
        this.initDatepickers();
        this.log('SalonPro X initialized');
    },

    /**
     * Log helper for debugging
     */
    log: function(message, data) {
        if (this.config.debug && console) {
            if (data) {
                console.log('[SalonProX]', message, data);
            } else {
                console.log('[SalonProX]', message);
            }
        }
    },

    /**
     * Sidebar toggle functionality
     */
    initSidebar: function() {
        const $sidebar = $('#sidebar');
        const $toggle = $('.sidebar-toggle');
        const $overlay = $('<div class="sidebar-overlay"></div>');

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

        $toggle.on('click', function(e) {
            e.stopPropagation();
            $sidebar.toggleClass('show');
            $overlay.toggleClass('show');
        });

        $overlay.on('click', function() {
            $sidebar.removeClass('show');
            $overlay.removeClass('show');
        });

        // Submenu toggle
        $('.submenu-toggle').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).closest('.sidebar-item').toggleClass('show');
        });

        // Close sidebar on route change (mobile)
        $(document).on('click', '.sidebar .sidebar-link:not(.submenu-toggle)', function() {
            if ($(window).width() < 992) {
                $sidebar.removeClass('show');
                $overlay.removeClass('show');
            }
        });
    },

    /**
     * Initialize Bootstrap tooltips
     */
    initTooltips: function() {
        const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        if (tooltips.length) {
            tooltips.forEach(el => new bootstrap.Tooltip(el));
        }
    },

    /**
     * Global search functionality
     */
    initGlobalSearch: function() {
        let searchTimeout;
        const $searchInput = $('#globalSearch');

        $searchInput.on('input', function() {
            clearTimeout(searchTimeout);
            const query = $(this).val().trim();

            if (query.length < 2) {
                return;
            }

            searchTimeout = setTimeout(function() {
                SalonPro.log('Global search:', query);
                // AJAX search implementation
                $.ajax({
                    url: SalonPro.config.baseUrl + '/api/customers/search',
                    method: 'GET',
                    data: { q: query },
                    success: function(response) {
                        SalonPro.log('Search results:', response);
                    },
                    error: function(xhr) {
                        SalonPro.log('Search error:', xhr);
                    }
                });
            }, 500);
        });
    },

    /**
     * Load and display notifications
     */
    initNotifications: function() {
        const $list = $('#notificationList');
        if (!$list.length) return;

        $.ajax({
            url: SalonPro.config.baseUrl + '/notifications',
            method: 'GET',
            data: { limit: 5, format: 'json' },
            success: function(response) {
                if (response.success && response.data) {
                    SalonPro.renderNotifications($list, response.data);
                }
            }
        });
    },

    /**
     * Render notification items
     */
    renderNotifications: function($container, notifications) {
        if (!notifications.length) {
            $container.html('<div class="text-center py-3 text-muted">No notifications</div>');
            return;
        }

        let html = '';
        notifications.forEach(function(notif) {
            const iconMap = {
                info: 'fa-info-circle text-info',
                success: 'fa-check-circle text-success',
                warning: 'fa-exclamation-triangle text-warning',
                danger: 'fa-times-circle text-danger'
            };
            const icon = iconMap[notif.type] || 'fa-bell text-muted';
            html += '<a class="dropdown-item notification-item" href="javascript:;">';
            html += '<i class="fas ' + icon + '"></i>';
            html += '<div class="notification-text">';
            html += '<strong>' + SalonPro.escape(notif.title) + '</strong>';
            html += '<p>' + SalonPro.escape(notif.message) + '</p>';
            html += '<small>' + SalonPro.timeAgo(notif.created_at) + '</small>';
            html += '</div></a>';
        });
        $container.html(html);
    },

    /**
     * Auto-dismiss alerts after 5 seconds
     */
    initAutoDismissAlerts: function() {
        $('.alert-dismissible').each(function() {
            const $alert = $(this);
            setTimeout(function() {
                $alert.fadeOut(300, function() { $(this).remove(); });
            }, 5000);
        });
    },

    /**
     * Confirm delete actions
     */
    initConfirmDeletes: function() {
        $(document).on('click', '[data-confirm]', function(e) {
            if (!confirm($(this).data('confirm') || 'Are you sure?')) {
                e.preventDefault();
            }
        });
    },

    /**
     * Initialize select2 dropdowns
     */
    initSelect2: function() {
        if ($.fn.select2) {
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
        }
    },

    /**
     * Initialize datepickers
     */
    initDatepickers: function() {
        $('.datepicker').each(function() {
            const $el = $(this);
            // Use native date input for now; enhance later
            if ($el.attr('type') !== 'date') {
                $el.attr('type', 'date');
            }
        });
    },

    /**
     * Show loading overlay
     */
    showLoading: function(message) {
        const $overlay = $('#loading-overlay');
        $overlay.find('.spinner-text').text(message || 'Loading...');
        $overlay.fadeIn(200);
    },

    /**
     * Hide loading overlay
     */
    hideLoading: function() {
        $('#loading-overlay').fadeOut(200);
    },

    /**
     * AJAX helper with CSRF token
     */
    ajax: function(options) {
        const defaults = {
            headers: {
                'X-CSRF-TOKEN': this.config.csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            error: function(xhr) {
                SalonPro.log('AJAX Error:', xhr);
                if (xhr.status === 403) {
                    alert('Session expired. Please login again.');
                    window.location.href = SalonPro.config.baseUrl + '/login';
                }
            }
        };
        return $.ajax($.extend({}, defaults, options));
    },

    /**
     * Simple HTML escaping
     */
    escape: function(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },

    /**
     * Time ago formatter
     */
    timeAgo: function(dateString) {
        if (!dateString) return '';
        const now = new Date();
        const date = new Date(dateString.replace(' ', 'T'));
        const diff = Math.floor((now - date) / 1000);

        if (diff < 60) return 'Just now';
        if (diff < 3600) return Math.floor(diff / 60) + ' min ago';
        if (diff < 86400) return Math.floor(diff / 3600) + ' hours ago';
        if (diff < 604800) return Math.floor(diff / 86400) + ' days ago';
        return date.toLocaleDateString();
    },

    /**
     * Format currency
     */
    formatCurrency: function(amount) {
        return 'Rs. ' + parseFloat(amount || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },

    /**
     * Format date
     */
    formatDate: function(dateString, format) {
        if (!dateString) return '-';
        const date = new Date(dateString.replace(' ', 'T'));
        const options = { year: 'numeric', month: 'short', day: 'numeric' };
        if (format === 'datetime') {
            options.hour = '2-digit';
            options.minute = '2-digit';
        }
        return date.toLocaleDateString('en-US', options);
    }
};

// Global confirm delete function
function confirmDelete(url) {
    if (confirm('Are you sure you want to delete this record?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = url;
        const csrf = document.createElement('input');
        csrf.type = 'hidden';
        csrf.name = '_csrf_token';
        csrf.value = SalonPro.config.csrfToken;
        form.appendChild(csrf);
        document.body.appendChild(form);
        form.submit();
    }
}

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