<?php
// Notification system configuration (PHP logic only - no HTML output)
// This file is safe to include in db.php as it doesn't output anything

// Get the current event ID from session, URL, or form data
$notification_event_id = null;

// Try to get event ID from various sources
if (isset($_SESSION['current_event_id'])) {
    $notification_event_id = $_SESSION['current_event_id'];
} elseif (isset($_GET['event_id'])) {
    $notification_event_id = $_GET['event_id'];
} elseif (isset($_POST['event_id'])) {
    $notification_event_id = $_POST['event_id'];
}

// Special case: If user is a judge, get event_id from judge_assignments
if (!$notification_event_id && isset($pdo)) {
    $judge_id = null;
    
    // Try to get judge ID from various session variables
    if (isset($_SESSION['judge_id'])) {
        $judge_id = $_SESSION['judge_id'];
    } elseif (isset($_SESSION['user_id']) && (isset($_SESSION['judge_logged_in']) && $_SESSION['judge_logged_in'])) {
        $judge_id = $_SESSION['user_id'];
    } elseif (isset($_SESSION['user_id']) && (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'judge')) {
        $judge_id = $_SESSION['user_id'];
    }
    
    // If we have a judge ID, look up their event assignment
    if ($judge_id) {
        try {
            $stmt = $pdo->prepare("
                SELECT DISTINCT event_id 
                FROM judge_assignments 
                WHERE judge_id = ? 
                ORDER BY event_id DESC 
                LIMIT 1
            ");
            $stmt->execute([$judge_id]);
            $judge_assignment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($judge_assignment) {
                $notification_event_id = $judge_assignment['event_id'];
            }
        } catch (Exception $e) {
            // Ignore database errors, continue with other methods
        }
    }
}

// If still no event ID found, try to get the most recent event from database
if (!$notification_event_id && isset($pdo)) {
    try {
        $stmt = $pdo->query("SELECT id FROM events ORDER BY created_at DESC LIMIT 1");
        $recent_event = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($recent_event) {
            $notification_event_id = $recent_event['id'];
        }
    } catch (Exception $e) {
        // Ignore database errors
    }
}

// Get current user ID for notifications
$notification_user_id = 'anonymous';

// Prioritize judge_id for judges, then fall back to other user identifiers
if (isset($_SESSION['judge_id'])) {
    $notification_user_id = 'judge_' . $_SESSION['judge_id'];
} elseif (isset($_SESSION['user_id'])) {
    $notification_user_id = $_SESSION['user_id'];
} elseif (isset($_SESSION['username'])) {
    $notification_user_id = $_SESSION['username'];
} elseif (isset($_SESSION['user'])) {
    $notification_user_id = $_SESSION['user'];
}

// Determine user role for notification filtering
$notification_user_role = 'viewer';
if (isset($_SESSION['user_type'])) {
    $notification_user_role = $_SESSION['user_type'];
} elseif (isset($_SESSION['role'])) {
    $notification_user_role = $_SESSION['role'];
} elseif (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in']) {
    $notification_user_role = 'admin';
} elseif (isset($_SESSION['judge_logged_in']) && $_SESSION['judge_logged_in']) {
    $notification_user_role = 'judge';
}

// Function to render notification UI components (call this in HTML section)
function render_notification_system() {
    global $notification_event_id, $notification_user_id, $notification_user_role;
    
    // Only render once per page
    if (defined('NOTIFICATIONS_UI_RENDERED')) {
        return;
    }
    define('NOTIFICATIONS_UI_RENDERED', true);
    
    // Determine script path based on current location
    $current_path = $_SERVER['REQUEST_URI'];
    $script_path = 'assets/js/notification_manager.js';
    if (strpos($current_path, '/admin/') !== false) {
        $script_path = '../assets/js/notification_manager.js';
    } elseif (strpos($current_path, '/judge/') !== false) {
        $script_path = '../assets/js/notification_manager.js';
    }
    
    ?>
    <style>
    /* Notification System Styles */
    .notification-toast-container {
        max-height: 90vh;
        overflow-y: auto;
        z-index: 9999;
    }
    
    .notification-toast {
        transition: all 0.3s ease;
        transform: translateX(100%);
        opacity: 0;
        max-width: 400px;
        word-wrap: break-word;
    }
    
    .notification-toast.show {
        transform: translateX(0);
        opacity: 1;
    }
    
    /* Custom notification styles */
    .css-bib {
        font-weight: bold !important;
        font-size: 0.9em !important;
        padding: 0.3em 0.6em !important;
        margin: 0 0.2em !important;
    }
    
    .judge_score {
        font-weight: bold !important;
        font-size: 0.85em !important;
        padding: 0.25em 0.5em !important;
        margin: 0 0.1em !important;
    }
    
    .judge_score.approved {
        background-color: #28a745 !important;
        border-color: #28a745 !important;
    }
    
    /* Scrolling notification bar at bottom */
    .notification-scroll-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 40px;
        background: white;
        border-top: 1px solid #dee2e6;
        z-index: 50;
        display: flex;
        align-items: center;
        overflow: hidden;
        box-shadow: 0 -2px 4px rgba(0,0,0,0.1);
        --scroll-duration: 30s;
        --scroll-speed: 100px;
    }
    
    .notification-scroll-bar.hidden {
        transform: translateY(100%);
        transition: transform 0.3s ease;
    }
    
    .notification-scroll-content {
        display: flex;
        align-items: center;
        height: 100%;
        padding-left: 100%;
        animation: scrollNotifications linear infinite;
        animation-duration: var(--scroll-duration);
    }
    
    .notification-scroll-content:hover {
        animation-play-state: paused;
    }
    
    .notification-scroll-item {
        padding: 0 20px;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        height: 100%;
        border-right: 1px solid #dee2e6;
        cursor: pointer;
        transition: background-color 0.2s ease;
        flex-shrink: 0;
        position: relative;
        color: #333;
    }
    
    .notification-scroll-item:hover {
        background-color: #f8f9fa;
    }
    
    .notification-scroll-item .icon {
        margin-right: 8px;
        font-size: 14px;
    }
    
    .notification-scroll-item .notification-content {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 0.3em;
    }
    
    .notification-scroll-item .notification-content .css-bib {
        font-size: 0.75em !important;
        padding: 0.2em 0.4em !important;
    }
    
    .notification-scroll-item .notification-content .judge_score,
    .notification-scroll-item .notification-content .badge {
        font-size: 0.7em !important;
        padding: 0.15em 0.3em !important;
        margin: 0 0.1em !important;
    }
    
    .notification-scroll-item .close-btn {
        margin-left: 10px;
        background: none;
        border: none;
        color: #6c757d;
        font-size: 12px;
        cursor: pointer;
        padding: 2px 4px;
        border-radius: 3px;
        opacity: 0;
        transition: opacity 0.2s ease;
    }
    
    .notification-scroll-item:hover .close-btn {
        opacity: 1;
    }
    
    .notification-scroll-item .close-btn:hover {
        background-color: #dc3545;
        color: white;
    }
    
    /* Category-specific text colors */
    .notification-scroll-item.category-general { color: #17a2b8; }
    .notification-scroll-item.category-competition { color: #007bff; }
    .notification-scroll-item.category-participant { color: #28a745; }
    .notification-scroll-item.category-judge { color: #ffc107; }
    .notification-scroll-item.category-heat { color: #dc3545; }
    .notification-scroll-item.category-scoring { color: #6f42c1; }
    .notification-scroll-item.category-system { color: #6c757d; }
    .notification-scroll-item.category-technical { color: #343a40; }
    
    /* Type-specific text colors */
    .notification-scroll-item.type-success { color: #28a745; }
    .notification-scroll-item.type-danger { color: #dc3545; }
    .notification-scroll-item.type-warning { color: #ffc107; }
    .notification-scroll-item.type-info { color: #17a2b8; }
    
    .notification-scroll-toggle {
        position: fixed;
        bottom: 10px;
        right: 20px;
        z-index: 51;
        background: rgba(0,0,0,0.7);
        border: none;
        color: white;
        border-radius: 15px;
        padding: 4px 10px;
        font-size: 11px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 5px;
        transition: all 0.3s ease;
    }
    
    .notification-scroll-toggle:hover {
        background: rgba(0,0,0,0.9);
        transform: scale(1.05);
    }
    
    .notification-count-badge {
        background: #dc3545;
        color: white;
        border-radius: 8px;
        padding: 1px 4px;
        font-size: 9px;
        font-weight: bold;
        min-width: 14px;
        text-align: center;
    }
    
    @keyframes scrollNotifications {
        0% { transform: translateX(0); }
        100% { transform: translateX(-100%); }
    }
    
    /* Add padding to body when notification bar is active */
    body.notification-bar-active {
        padding-bottom: 40px;
    }
    
    .notification-controls {
        position: fixed;
        bottom: 50px;
        right: 20px;
        z-index: 9998;
        display: none;
    }
    
    .notification-controls.show {
        display: block;
    }
    
    .notification-filter-btn {
        margin: 2px;
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
    
    .live-pulse {
        animation: livePulse 2s infinite;
    }
    
    @keyframes livePulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.7; }
    }
    
    /* Notification status indicator */
    .notification-status {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 9997;
        background: rgba(0,0,0,0.8);
        color: white;
        padding: 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        display: none;
    }
    
    .notification-status.show {
        display: block;
    }
    </style>
    
    <!-- Scrolling Notification Bar (to be placed in container) -->
    <div class="notification-scroll-bar hidden" id="notificationScrollBar">
        <div class="notification-scroll-content" id="notificationScrollContent">
            <!-- Notifications will be dynamically added here -->
        </div>
    </div>
    
    <!-- Always Visible Toggle Button -->
    <button class="notification-scroll-toggle" onclick="toggleNotificationControls()" title="Notification Settings">
        <i class="fas fa-bell"></i>
        <span class="notification-count-badge" id="notificationCount">0</span>
    </button>
    
    <!-- Notification Controls -->
    <div class="notification-controls" id="notificationControls">
        <div class="border-0 shadow-none card">
            <div class="border-0 shadow-none card-header py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <small class="fw-bold"><i class="fas fa-bell me-1"></i>Notifications</small>
                    <button class="btn btn-sm btn-outline-secondary" onclick="toggleNotificationControls()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="border-0 shadow-none card-body py-2">
                <div class="mb-2">
                    <small class="text-muted">Filter by category:</small>
                    <div class="d-flex flex-wrap">
                        <button class="btn btn-outline-primary notification-filter-btn" data-category="all" onclick="setNotificationFilter('all')">All</button>
                        <button class="btn btn-outline-info notification-filter-btn" data-category="general" onclick="setNotificationFilter('general')">General</button>
                        <button class="btn btn-outline-primary notification-filter-btn" data-category="competition" onclick="setNotificationFilter('competition')">Competition</button>
                        <button class="btn btn-outline-success notification-filter-btn" data-category="participant" onclick="setNotificationFilter('participant')">Participants</button>
                        <button class="btn btn-outline-warning notification-filter-btn" data-category="judge" onclick="setNotificationFilter('judge')">Judges</button>
                        <button class="btn btn-outline-danger notification-filter-btn" data-category="heat" onclick="setNotificationFilter('heat')">Heats</button>
                        <button class="btn btn-outline-info notification-filter-btn" data-category="scoring" onclick="setNotificationFilter('scoring')">Scoring</button>
                        <button class="btn btn-outline-secondary notification-filter-btn" data-category="system" onclick="setNotificationFilter('system')">System</button>
                        <button class="btn btn-outline-dark notification-filter-btn" data-category="technical" onclick="setNotificationFilter('technical')">Technical</button>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <small class="text-muted">Status: <span id="liveStatusIndicator" class="badge bg-secondary">Connecting...</span></small>
                    <div class="d-flex gap-2">
                        <button class="btn btn-sm btn-outline-warning" onclick="toggleScrollingBar()" title="Toggle scrolling bar">
                            <i class="fas fa-scroll"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="clearAllNotifications()" title="Clear all notifications">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Notification Status Indicator -->
    <div class="notification-status" id="notificationStatus">
        <i class="fas fa-bell me-1"></i>
        <span id="notificationStatusText">Notifications ready</span>
    </div>
    
    <script>
    // Global notification system variables
    let globalNotificationManager = null;
    let notificationCount = 0;
    let currentNotificationFilter = "all";
    let unreadNotifications = [];
    let scrollingBarVisible = false;
    
    // Initialize notification system when DOM is ready
    document.addEventListener("DOMContentLoaded", function() {
        initializeNotificationSystem();
    });
    
    function initializeNotificationSystem() {
        const eventId = "<?php echo htmlspecialchars($notification_event_id ?? '', ENT_QUOTES); ?>";
        const userId = "<?php echo htmlspecialchars($notification_user_id, ENT_QUOTES); ?>";
        const userRole = "<?php echo htmlspecialchars($notification_user_role, ENT_QUOTES); ?>";
        
        if (!eventId) {
            console.warn("No event ID available for notifications");
            updateNotificationStatus("No event selected", "warning");
            return;
        }
        
        // Load notification manager if not already loaded
        if (typeof NotificationManager === "undefined") {
            const script = document.createElement("script");
            script.src = "<?php echo $script_path; ?>";
            script.onload = function() {
                createNotificationManager(eventId, userId, userRole);
            };
            script.onerror = function() {
                console.warn("Could not load notification manager");
                updateNotificationStatus("Notification system unavailable", "danger");
            };
            document.head.appendChild(script);
        } else {
            createNotificationManager(eventId, userId, userRole);
        }
    }
    
    function createNotificationManager(eventId, userId, userRole) {
        try {
            globalNotificationManager = new NotificationManager(eventId, userId);
            
            // Set up role-based filters
            setupRoleBasedFilters(userRole);
            
            // Override the original showToast to update our counter and scrolling bar
            const originalShowToast = globalNotificationManager.showToast.bind(globalNotificationManager);
            globalNotificationManager.showToast = function(notification) {
                originalShowToast(notification);
                addToScrollingBar(notification);
                updateNotificationCount();
            };
            
            updateNotificationStatus("Connected to live notifications", "success");
            
            // Set default filter based on user role
            setInitialFilterForRole(userRole);
            
            // Show scrolling bar initially if there are notifications
            setTimeout(() => {
                showScrollingBar();
            }, 1000);
            
        } catch (error) {
            console.error("Error initializing notification manager:", error);
            updateNotificationStatus("Notification system error", "danger");
        }
    }
    
    function addToScrollingBar(notification) {
        unreadNotifications.push(notification);
        updateScrollingBarContent();
        showScrollingBar();
        
        // Auto-remove from scrolling bar after 30 seconds
        setTimeout(() => {
            removeFromScrollingBar(notification);
        }, 30000);
    }
    
    function removeFromScrollingBar(notification) {
        const index = unreadNotifications.findIndex(n => n.id === notification.id);
        if (index > -1) {
            unreadNotifications.splice(index, 1);
            updateScrollingBarContent();
            
            // Hide scrolling bar if no more notifications
            if (unreadNotifications.length === 0) {
                hideScrollingBar();
            }
        }
    }
    
    function updateScrollingBarContent() {
        const scrollContent = document.getElementById('notificationScrollContent');
        if (!scrollContent) return;
        
        if (unreadNotifications.length === 0) {
            scrollContent.innerHTML = '';
            return;
        }
        
        let html = '';
        unreadNotifications.forEach(notification => {
            const icon = getNotificationIcon(notification.type, notification.category);
            
            // Use text_message if available (for styled notifications), otherwise fallback to title + message
            let displayText;
            if (notification.data && notification.data.text_message) {
                displayText = notification.data.text_message;
            } else {
                displayText = `${notification.title}${notification.message ? ': ' + notification.message : ''}`;
            }
            
            // Add CSS classes based on content
            let styledText = displayText;
            
            // Style bib numbers
            styledText = styledText.replace(/#(\d+)/g, '<span class="css-bib badge bg-primary">#$1</span>');
            
            // Style scores (numbers followed by common score indicators)
            styledText = styledText.replace(/Score:\s*([0-9.]+)/g, 'Score: <span class="judge_score badge bg-success">$1</span>');
            styledText = styledText.replace(/Result:\s*([0-9.]+)/g, 'Result: <span class="badge bg-warning">$1</span>');
            styledText = styledText.replace(/Final:\s*([0-9.]+)/g, 'Final: <span class="badge bg-warning">$1</span>');
            
            // Style ranks
            styledText = styledText.replace(/Rank:\s*#(\d+)/g, 'Rank: <span class="badge bg-info">#$1</span>');
            
            // Style progress indicators
            styledText = styledText.replace(/(\d+)\/(\d+)\s*scores?\s*approved/g, '<span class="badge bg-success">$1/$2</span> scores approved');
            styledText = styledText.replace(/All\s*(\d+)\s*scores?\s*approved/g, '<span class="badge bg-success">All $1</span> scores approved');
            
            const categoryClass = notification.category ? `category-${notification.category}` : '';
            const typeClass = notification.type ? `type-${notification.type}` : '';
            
            html += `
                <div class="notification-scroll-item ${categoryClass} ${typeClass}" 
                     onclick="showNotificationToast('${notification.id}')" 
                     data-notification-id="${notification.id}">
                    <span class="icon">${icon}</span>
                    <span class="notification-content">${styledText}</span>
                    <button class="close-btn" onclick="event.stopPropagation(); dismissScrollingNotification('${notification.id}')" title="Mark as read">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `;
        });
        
        scrollContent.innerHTML = html;
        
        // Calculate dynamic scroll duration based on content width for consistent speed
        setTimeout(() => {
            const contentWidth = scrollContent.scrollWidth;
            const containerWidth = scrollContent.parentElement.offsetWidth;
            const totalWidth = contentWidth + containerWidth; // Content + padding-left: 100%
            
            // Set scroll speed: 100 pixels per second (adjustable)
            const scrollSpeed = 200; // pixels per second
            const duration = totalWidth / scrollSpeed;
            
            // Update CSS custom property for animation duration
            scrollContent.style.setProperty('--scroll-duration', `${duration}s`);
            
            // Restart animation with new duration
            scrollContent.style.animation = 'none';
            scrollContent.offsetHeight; // Trigger reflow
            scrollContent.style.animation = `scrollNotifications ${duration}s linear infinite`;
        }, 50); // Small delay to ensure content is rendered
    }
    
    function showNotificationToast(notificationId) {
        const notification = unreadNotifications.find(n => n.id === notificationId);
        if (notification && globalNotificationManager) {
            // Show the full toast for this notification
            globalNotificationManager.showToast(notification);
        }
    }
    
    function getNotificationIcon(type, category) {
        const icons = {
            'success': '✅',
            'danger': '❌',
            'warning': '⚠️',
            'info': 'ℹ️',
            'general': '📢',
            'competition': '🏆',
            'participant': '👤',
            'judge': '⚖️',
            'heat': '🔥',
            'scoring': '📊',
            'system': '🔧',
            'technical': '⚙️'
        };
        return icons[type] || icons[category] || '📢';
    }
    
    function showScrollingBar() {
        const scrollBar = document.getElementById('notificationScrollBar');
        if (scrollBar) {
            scrollBar.classList.remove('hidden');
            document.body.classList.add('notification-bar-active');
            scrollingBarVisible = true;
        }
    }
    
    function hideScrollingBar() {
        const scrollBar = document.getElementById('notificationScrollBar');
        if (scrollBar) {
            scrollBar.classList.add('hidden');
            document.body.classList.remove('notification-bar-active');
            scrollingBarVisible = false;
        }
    }
    
    function toggleScrollingBar() {
        if (scrollingBarVisible) {
            hideScrollingBar();
        } else {
            showScrollingBar();
        }
    }
    
    function setupRoleBasedFilters(userRole) {
        // Show different categories based on user role
        const roleFilters = {
            "admin": [], // Admins see everything
            "judge": ["judge", "scoring", "participant", "heat"],
            "staff": ["competition", "participant", "heat", "general"],
            "viewer": ["general", "competition"]
        };
        
        if (roleFilters[userRole]) {
            // Note: Empty array means show all for admins
            if (roleFilters[userRole].length > 0) {
                globalNotificationManager.setCategoryFilters(roleFilters[userRole]);
            }
        }
    }
    
    function setInitialFilterForRole(userRole) {
        // Set initial active filter button based on role
        const initialFilters = {
            "admin": "all",
            "judge": "judge", 
            "staff": "competition",
            "viewer": "general"
        };
        
        const filter = initialFilters[userRole] || "all";
        setNotificationFilter(filter);
    }
    
    function toggleNotificationControls() {
        const controls = document.getElementById("notificationControls");
        controls.classList.toggle("show");
    }
    
    function setNotificationFilter(category) {
        currentNotificationFilter = category;
        
        if (!globalNotificationManager) return;
        
        // Update filter buttons
        document.querySelectorAll(".notification-filter-btn").forEach(btn => {
            btn.classList.remove("btn-primary");
            btn.classList.add("btn-outline-primary");
            if (btn.dataset.category !== "all") {
                const btnCategory = btn.dataset.category;
                btn.classList.remove("btn-outline-primary");
                btn.classList.add("btn-outline-" + getCategoryColor(btnCategory));
            }
        });
        
        const activeBtn = document.querySelector(`[data-category="${category}"]`);
        if (activeBtn) {
            activeBtn.classList.remove("btn-outline-primary", "btn-outline-info", "btn-outline-success", "btn-outline-warning", "btn-outline-danger", "btn-outline-secondary", "btn-outline-dark");
            activeBtn.classList.add("btn-primary");
        }
        
        // Apply filter
        if (category === "all") {
            globalNotificationManager.clearCategoryFilters();
        } else {
            globalNotificationManager.setCategoryFilters([category]);
        }
        
        updateNotificationStatus(`Showing ${category} notifications`, "info");
    }
    
    function getCategoryColor(category) {
        const colors = {
            "general": "info",
            "competition": "primary", 
            "participant": "success",
            "judge": "warning",
            "heat": "danger",
            "scoring": "info",
            "system": "secondary",
            "technical": "dark"
        };
        return colors[category] || "secondary";
    }
    
    function updateNotificationCount() {
        notificationCount++;
        const counter = document.getElementById("notificationCount");
        if (counter) {
            counter.textContent = notificationCount;
            if (notificationCount > 0) {
                counter.classList.add("live-pulse");
            }
        }
    }
    
    function updateNotificationStatus(message, type = "info") {
        const status = document.getElementById("notificationStatus");
        const statusText = document.getElementById("notificationStatusText");
        
        if (status && statusText) {
            statusText.textContent = message;
            status.className = `notification-status show bg-${type}`;
            
            // Auto-hide after 3 seconds for non-error messages
            if (type !== "danger") {
                setTimeout(() => {
                    status.classList.remove("show");
                }, 3000);
            }
        }
    }
    
    function clearAllNotifications() {
        if (globalNotificationManager && confirm("Clear all notifications for this event?")) {
            globalNotificationManager.clearAllNotifications().then(() => {
                notificationCount = 0;
                unreadNotifications = [];
                updateNotificationCount();
                updateScrollingBarContent();
                hideScrollingBar();
                updateNotificationStatus("All notifications cleared", "success");
            }).catch(error => {
                console.error("Error clearing notifications:", error);
                updateNotificationStatus("Error clearing notifications", "danger");
            });
        }
    }
    
    function dismissScrollingNotification(notificationId) {
        const notification = unreadNotifications.find(n => n.id === notificationId);
        if (notification) {
            removeFromScrollingBar(notification);
            updateNotificationStatus("Notification marked as read", "success");
        }
    }
    
    // Expose functions globally for easy access
    window.sendNotification = function(type, title, message = "", category = "general") {
        if (globalNotificationManager) {
            return globalNotificationManager.sendNotification(type, title, message, {}, category);
        } else {
            console.warn("Notification manager not initialized");
            return Promise.resolve({success: false, error: "Not initialized"});
        }
    };
    
    // Quick notification functions
    window.notifySuccess = (title, message = "") => sendNotification("success", title, message, "general");
    window.notifyError = (title, message = "") => sendNotification("danger", title, message, "system");
    window.notifyWarning = (title, message = "") => sendNotification("warning", title, message, "system");
    window.notifyInfo = (title, message = "") => sendNotification("info", title, message, "general");
    
    // Competition-specific notifications (if notification manager is loaded)
    window.notifyParticipant = function(action, bibNumber, participantName) {
        if (globalNotificationManager) {
            switch(action) {
                case "on_start":
                    return globalNotificationManager.notifyParticipantOnStart(bibNumber, participantName);
                case "started":
                    return globalNotificationManager.notifyParticipantStarted(bibNumber, participantName);
                case "completed":
                    return globalNotificationManager.notifyParticipantCompleted(bibNumber, participantName);
                case "next":
                    return globalNotificationManager.notifyNextParticipant(bibNumber, participantName);
            }
        }
    };
    
    window.notifyHeat = function(action, heatNumber, runNumber = null) {
        if (globalNotificationManager) {
            switch(action) {
                case "activated":
                    return globalNotificationManager.notifyHeatActivated(heatNumber, runNumber);
                case "deactivated":
                    return globalNotificationManager.notifyHeatDeactivated(heatNumber);
            }
        }
    };
    
    window.notifyJudge = (action, details) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyJudgeAction(action, details);
        }
    };
    
    window.notifyScore = (participantBib, score, judge) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyScoreUpdate(participantBib, score, judge);
        }
    };
    
    window.notifyScoreApproval = (participantBib, participantName, score, judge, heat, run, additionalData = {}) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyScoreApproval(participantBib, participantName, score, judge, heat, run, additionalData);
        }
    };
    
    window.notifyBulkScoreApproval = (participantBib, participantName, scoreCount, heat, run, additionalData = {}) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyBulkScoreApproval(participantBib, participantName, scoreCount, heat, run, additionalData);
        }
    };
    
    window.notifyEmergencyStop = () => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyEmergencyStop();
        }
    };
    </script>
    <?php
}
?>
