<?php
/**
 * Essential StyleScore System JavaScript and CSS includes
 * This file contains the core notification system and essential utilities
 * needed for public-facing dashboards and standalone pages
 * 
 * Usage: Include this file before the closing </body> tag on public pages
 * Example: <?php include_once __DIR__ . '/includes/essential_scripts.php'; ?>
 */

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

// Include notification configuration
require_once __DIR__ . '/notifications_config.php';
?>

<!-- Essential StyleScore System Styles -->
<style>
/* Notification Toast Styling 
.toast-container {
    z-index: 9999 !important;
}

.toast {
    min-width: 300px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.125);
}

.toast-header {
    border-bottom: 1px solid rgba(255, 255, 255, 0.125);
    backdrop-filter: blur(10px);
}

.toast.border-success {
    border-color: rgba(25, 135, 84, 0.5) !important;
}

.toast.border-danger {
    border-color: rgba(220, 53, 69, 0.5) !important;
}

.toast.border-warning {
    border-color: rgba(255, 193, 7, 0.5) !important;
}

.toast.border-info {
    border-color: rgba(13, 202, 240, 0.5) !important;
}
*/
/* Dashboard specific styling 
.dashboard-loading {
    position: relative;
}

.dashboard-loading::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10;
}

/* Essential button styling 
.btn-test-notifications {
    position: relative;
    overflow: hidden;
}

.btn-test-notifications:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* Notification system specific styles 
.notification-scroll-bar {
    max-height: 300px;
    overflow-y: auto;
}

.notification-item {
    transition: all 0.3s ease;
}

.notification-item:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

/* Hide admin controls on public dashboard 
.public-dashboard .notification-controls,
.public-dashboard .notification-admin-only {
    display: none !important;
}*/
</style>
<!-- Alpine Plugins -->
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/morph@3.x.x/dist/cdn.min.js"></script>
 
<!-- Alpine Core -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<!-- Essential JavaScript Libraries -->
<!-- Popper.js for tooltips and dropdowns -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>

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

<!-- MorphDOM for smooth DOM updates -->
<script src="https://cdn.jsdelivr.net/npm/morphdom@2.7.0/dist/morphdom-umd.min.js" crossorigin="anonymous"></script>

<!-- StyleScore Notification Manager -->
<script src="assets/js/notification_manager.js"></script>

<!-- Essential StyleScore Utilities -->
<script>
// Essential StyleScore utilities for public dashboard
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('dashboard-loading');
            if (element.tagName === 'BUTTON') {
                element.setAttribute('disabled', 'disabled');
            }
        }
    },
    
    hideLoading: function(element) {
        if (element) {
            element.classList.remove('dashboard-loading');
            if (element.tagName === 'BUTTON') {
                element.removeAttribute('disabled');
            }
        }
    },
    
    // Utility for notifications (integration with notification system)
    notify: function(message, type = 'info') {
        const notifyFunctions = {
            'success': window.notifySuccess,
            'error': window.notifyError,
            'warning': window.notifyWarning,
            'info': window.notifyInfo
        };
        
        const notifyFn = notifyFunctions[type] || notifyFunctions['info'];
        if (typeof notifyFn === 'function') {
            notifyFn('Notification', message);
        } else {
            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');
    },
    
    // Public dashboard utilities
    dashboard: {
        // Test notification system
        testNotifications: function() {
            if (window.notifySuccess) {
                window.notifySuccess('Test Success', 'Notification system is working!');
                
                setTimeout(() => {
                    if (window.notifyInfo) {
                        window.notifyInfo('Test Info', 'Information notifications are working');
                    }
                }, 1000);
                
                setTimeout(() => {
                    if (window.notifyWarning) {
                        window.notifyWarning('Test Warning', 'Warning notifications are working');
                    }
                }, 2000);
                
                setTimeout(() => {
                    if (window.notifyError) {
                        window.notifyError('Test Error', 'Error notifications are working');
                    }
                }, 3000);
                
                console.log('Notification test completed');
            } else {
                console.error('Notification functions not available');
                alert('Notification system not loaded properly');
            }
        },
        
        // Initialize public dashboard components
        init: function() {
            console.log('StyleScore Dashboard: Initializing essential components...');
            
            // Mark body as public dashboard for CSS targeting
            document.body.classList.add('public-dashboard');
            
            // Initialize notification system for public use
            this.initPublicNotificationSystem();
            
            console.log('StyleScore Dashboard: Essential components initialized');
        },
        
        // Initialize notification system specifically for public dashboard
        initPublicNotificationSystem: function() {
            // Override notification manager creation for public dashboard
            if (typeof window.createNotificationManager === 'function') {
                const originalCreateManager = window.createNotificationManager;
                window.createNotificationManager = function(eventId, userId, userRole) {
                    try {
                        window.globalNotificationManager = new NotificationManager(eventId, userId);
                        
                        // Configure for public dashboard
                        window.globalNotificationManager.localMode = false;
                        window.globalNotificationManager.apiAvailable = true;
                        window.globalNotificationManager.pollingRate = 10000; // 10 seconds
                        
                        console.log('Public notification system initialized with API access');
                        
                        // Start polling for notifications
                        window.globalNotificationManager.startPolling();
                        
                        return window.globalNotificationManager;
                        
                    } catch (error) {
                        console.error("Error initializing public notification manager:", error);
                        
                        // Fallback to local-only mode if API fails
                        this.initLocalNotificationSystem();
                        return null;
                    }
                };
            }
            
            // Hide admin notification controls after load
            setTimeout(() => {
                this.hideAdminNotificationControls();
            }, 1000);
        },
        
        // Hide admin UI elements for public dashboard
        hideAdminNotificationControls: function() {
            const elementsToHide = [
                'notificationScrollBar',
                'notificationControls', 
                'notificationCount',
                'liveStatusIndicator',
                'notificationStatus'
            ];
            
            elementsToHide.forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.style.display = 'none';
                }
            });
            
            // Hide any notification control buttons
            const controlButtons = document.querySelectorAll('.notification-scroll-toggle, .notification-filter-btn, .notification-admin-only');
            controlButtons.forEach(btn => {
                btn.style.display = 'none';
            });
            
            console.log('Admin notification controls hidden for public dashboard');
        },
        
        // Fallback local notification system
        initLocalNotificationSystem: function() {
            console.log('Falling back to local notification system');
            
            // Create minimal toast container if not exists
            if (!document.getElementById('toast-container')) {
                const toastContainer = document.createElement('div');
                toastContainer.id = 'toast-container';
                toastContainer.className = 'position-fixed top-0 end-0 p-3';
                toastContainer.style.zIndex = '9999';
                document.body.appendChild(toastContainer);
            }
            
            // Define global notification functions for public use
            window.notifySuccess = function(title, message = '') {
                StyleScore.dashboard.showPublicToast('success', title, message);
            };
            
            window.notifyError = function(title, message = '') {
                StyleScore.dashboard.showPublicToast('danger', title, message);
            };
            
            window.notifyWarning = function(title, message = '') {
                StyleScore.dashboard.showPublicToast('warning', title, message);
            };
            
            window.notifyInfo = function(title, message = '') {
                StyleScore.dashboard.showPublicToast('info', title, message);
            };
        },
        
        // Show toast notification for public dashboard
        showPublicToast: function(type, title, message = '') {
            const container = document.getElementById('toast-container');
            if (!container) return;
            
            const toast = document.createElement('div');
            toast.className = `toast show border-${type} mb-2`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            const iconMap = {
                'success': 'fa-check-circle',
                'danger': 'fa-exclamation-circle', 
                'warning': 'fa-exclamation-triangle',
                'info': 'fa-info-circle'
            };
            
            const colorMap = {
                'success': 'success',
                'danger': 'danger',
                'warning': 'warning', 
                'info': 'info'
            };
            
            const time = new Date().toLocaleTimeString();
            
            toast.innerHTML = `
                <div class="toast-header bg-${colorMap[type]} bg-opacity-50 border-0">
                    <i class="fas ${iconMap[type]} text-${colorMap[type]} me-2"></i>
                    <strong class="me-auto">${this.escapeHtml(title)}</strong>
                    <small class="opacity-75">${time}</small>
                    <button type="button" class="btn-close btn-close-black ms-2" aria-label="Close"></button>
                </div>
                ${message ? `<div class="toast-body border-top border-light border-opacity-25">${this.escapeHtml(message)}</div>` : ''}
            `;
            
            // Add close functionality
            const closeBtn = toast.querySelector('.btn-close');
            closeBtn.addEventListener('click', () => {
                toast.remove();
            });
            
            container.appendChild(toast);
            
            // Auto-remove after duration
            const duration = type === 'danger' ? 8000 : 5000;
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.remove();
                }
            }, duration);
        },
        
        // HTML escape utility
        escapeHtml: function(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    }
};

// Global keyboard shortcuts for public dashboard
document.addEventListener('keydown', function(e) {
    // Ctrl+Shift+T - Test notifications
    if (e.ctrlKey && e.shiftKey && e.key === 'T') {
        e.preventDefault();
        if (typeof StyleScore.dashboard.testNotifications === 'function') {
            StyleScore.dashboard.testNotifications();
        }
    }
    
    // Ctrl+Shift+R - Refresh page
    if (e.ctrlKey && e.shiftKey && e.key === 'R') {
        e.preventDefault();
        window.location.reload();
    }
});

// Initialize essential components when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    StyleScore.dashboard.init();
});
</script>

<?php
// Render notification system UI components for public dashboard
if (function_exists('render_notification_system')) {
    echo "<!-- StyleScore Notification System -->\n";
    render_notification_system();
    echo "<!-- End StyleScore Notification System -->\n";
} else {
    echo "<!-- Warning: Notification system not available -->\n";
}
?>
