<?php
/**
 * StyleScore System JavaScript includes
 * Centralized JavaScript management to ensure consistency across all pages
 * 
 * Usage: Include this file before the closing </body> tag
 * Example: <?php include_once __DIR__ . '/includes/scripts.php'; ?>
 */

// Prevent duplicate includes
if (defined('STYLESCORE_SCRIPTS_LOADED')) {
    return;
}
define('STYLESCORE_SCRIPTS_LOADED', true);


?>
<?php include_once 'country_codes.php'; ?>
<!-- StyleScore System JavaScript -->


<script>
// StyleScore Popper.js Configuration and Utilities
window.StyleScorePopper = {
    // Default configuration for all StyleScore popovers and tooltips
    defaultConfig: {
        placement: 'auto',
        strategy: 'absolute',
        modifiers: [
            {
                name: 'offset',
                options: {
                    offset: [0, 8],
                },
            },
            {
                name: 'preventOverflow',
                options: {
                    boundary: 'viewport',
                    padding: 8,
                },
            },
            {
                name: 'flip',
                options: {
                    fallbackPlacements: ['top', 'right', 'bottom', 'left'],
                    boundary: 'viewport',
                },
            },
            {
                name: 'arrow',
                options: {
                    padding: 8,
                },
            },
        ],
    },
    
    // Create custom popper instance with StyleScore defaults
    createPopper: function(reference, popper, options = {}) {
        const config = {
            ...this.defaultConfig,
            ...options,
            modifiers: [
                ...this.defaultConfig.modifiers,
                ...(options.modifiers || [])
            ]
        };
        
        return Popper.createPopper(reference, popper, config);
    },
    
    // Create tooltip with custom styling
    createTooltip: function(element, content, options = {}) {
        const tooltip = document.createElement('div');
        tooltip.className = 'ss-tooltip';
        tooltip.innerHTML = `
            <div class="ss-tooltip-content">${content}</div>
            <div class="ss-tooltip-arrow" data-popper-arrow></div>
        `;
        tooltip.style.cssText = `
            background: rgba(33, 37, 41, 0.95);
            color: white;
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1070;
            max-width: 300px;
            word-wrap: break-word;
        `;
        
        document.body.appendChild(tooltip);
        
        const popperInstance = this.createPopper(element, tooltip, {
            placement: options.placement || 'top',
            modifiers: [
                {
                    name: 'arrow',
                    options: {
                        element: tooltip.querySelector('.ss-tooltip-arrow'),
                    },
                },
                ...(options.modifiers || [])
            ]
        });
        
        // Arrow styling
        const arrow = tooltip.querySelector('.ss-tooltip-arrow');
        arrow.style.cssText = `
            position: absolute;
            width: 8px;
            height: 8px;
            background: inherit;
            transform: rotate(45deg);
        `;
        
        return {
            tooltip,
            popper: popperInstance,
            show: () => {
                tooltip.style.display = 'block';
                popperInstance.update();
            },
            hide: () => {
                tooltip.style.display = 'none';
            },
            destroy: () => {
                popperInstance.destroy();
                if (tooltip.parentNode) {
                    tooltip.parentNode.removeChild(tooltip);
                }
            }
        };
    },
    
    // Create dropdown with custom positioning
    createDropdown: function(trigger, menu, options = {}) {
        const dropdownConfig = {
            placement: options.placement || 'bottom-start',
            modifiers: [
                {
                    name: 'offset',
                    options: {
                        offset: [0, 4],
                    },
                },
                {
                    name: 'preventOverflow',
                    options: {
                        boundary: options.boundary || 'viewport',
                        padding: 8,
                    },
                },
                {
                    name: 'flip',
                    options: {
                        fallbackPlacements: ['bottom-end', 'top-start', 'top-end'],
                    },
                },
                ...(options.modifiers || [])
            ]
        };
        
        const popperInstance = this.createPopper(trigger, menu, dropdownConfig);
        
        return {
            popper: popperInstance,
            show: () => {
                menu.style.display = 'block';
                menu.setAttribute('data-show', '');
                popperInstance.update();
            },
            hide: () => {
                menu.style.display = 'none';
                menu.removeAttribute('data-show');
            },
            toggle: () => {
                if (menu.hasAttribute('data-show')) {
                    this.hide();
                } else {
                    this.show();
                }
            },
            destroy: () => {
                popperInstance.destroy();
            }
        };
    },
    
    // Quick search dropdown positioning
    createSearchDropdown: function(input, results, options = {}) {
        return this.createDropdown(input, results, {
            placement: 'bottom-start',
            modifiers: [
                {
                    name: 'sameWidth',
                    enabled: true,
                    phase: 'beforeWrite',
                    requires: ['computeStyles'],
                    fn: ({ state }) => {
                        state.styles.popper.width = `${state.rects.reference.width}px`;
                    },
                    effect: ({ state }) => {
                        state.elements.popper.style.width = `${state.elements.reference.offsetWidth}px`;
                    }
                },
                ...((options.modifiers || []))
            ],
            ...options
        });
    },
    
    // Auto-initialize tooltips and popovers
    autoInit: function() {
        // Initialize tooltips
        document.querySelectorAll('[data-ss-tooltip]').forEach(element => {
            const content = element.getAttribute('data-ss-tooltip');
            const placement = element.getAttribute('data-ss-placement') || 'top';
            
            let tooltipInstance = null;
            
            element.addEventListener('mouseenter', () => {
                if (!tooltipInstance) {
                    tooltipInstance = this.createTooltip(element, content, { placement });
                }
                tooltipInstance.show();
            });
            
            element.addEventListener('mouseleave', () => {
                if (tooltipInstance) {
                    tooltipInstance.hide();
                }
            });
            
            // Cleanup on element removal
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    mutation.removedNodes.forEach((node) => {
                        if (node === element && tooltipInstance) {
                            tooltipInstance.destroy();
                        }
                    });
                });
            });
            observer.observe(document.body, { childList: true, subtree: true });
        });
        
        // Initialize custom dropdowns
        document.querySelectorAll('[data-ss-dropdown]').forEach(trigger => {
            const targetSelector = trigger.getAttribute('data-ss-dropdown');
            const target = document.querySelector(targetSelector);
            if (target) {
                const dropdown = this.createDropdown(trigger, target);
                
                trigger.addEventListener('click', (e) => {
                    e.preventDefault();
                    dropdown.toggle();
                });
                
                // Close on outside click
                document.addEventListener('click', (e) => {
                    if (!trigger.contains(e.target) && !target.contains(e.target)) {
                        dropdown.hide();
                    }
                });
            }
        });
    }
};
</script>

<!-- StyleScore Global JavaScript -->
<script>
// Global StyleScore utilities
window.StyleScore = window.StyleScore || {
    // Utility function to safely call functions
    safeCall: function(fn, ...args) {
        if (typeof fn === 'function') {
            try {
                return fn.apply(this, args);
            } catch (e) {
                console.warn('StyleScore: Function call failed:', e);
                return null;
            }
        }
        return null;
    },
    
    // Utility to show loading states
    showLoading: function(element) {
        if (element) {
            element.classList.add('loading');
            element.setAttribute('disabled', 'disabled');
        }
    },
    
    hideLoading: function(element) {
        if (element) {
            element.classList.remove('loading');
            element.removeAttribute('disabled');
        }
    },
    
    // Utility for notifications
    notify: function(message, type = 'info') {
        // Integration point for existing notification system
        if (typeof window.showNotification === 'function') {
            window.showNotification(message, type);
        } else {
            // Fallback to console
            console.log(`StyleScore Notification [${type}]:`, message);
        }
    },
    
    // Utility for consistent error handling
    handleError: function(error, context = 'Unknown') {
        console.error(`StyleScore Error [${context}]:`, error);
        this.notify(`An error occurred: ${error.message || error}`, 'error');
    }
};

// Global keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl+Shift+D - Quick Dashboard
    if (e.ctrlKey && e.shiftKey && e.key === 'D') {
        e.preventDefault();
        window.location.href = '/v2/dashboard.php';
    }
    
    // Ctrl+Shift+H - Help
    if (e.ctrlKey && e.shiftKey && e.key === 'H') {
        e.preventDefault();
        window.open('/v2/help.html', '_blank');
    }
});

// Initialize StyleScore components
document.addEventListener('DOMContentLoaded', function() {
    // Auto-initialize any data-ss-* components
    document.querySelectorAll('[data-ss-component]').forEach(function(element) {
        const componentType = element.getAttribute('data-ss-component');
        const initFunction = window.StyleScore[`init${componentType}`];
        if (typeof initFunction === 'function') {
            initFunction(element);
        }
    });
});
</script>
<!-- Popper.js Advanced Configuration -->
<!-- Popper.js v2 with advanced configuration -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>


<!-- Bootstrap Bundle (requires Popper.js) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>

