<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        const version = new Date().getTime();
        
        function addVersion(url) {
            return `${url}?v=${version}`;
        }

        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('script[src], link[rel="stylesheet"]').forEach(element => {
                if (element.src) {
                    element.src = addVersion(element.src);
                } else if (element.href) {
                    element.href = addVersion(element.href);
                }
            });
        });
    </script>

    <script>
        // Disable right-click
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        });

        // Disable F12 key and other keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Block F12
            if (e.key === 'F12') {
                e.preventDefault();
                return false;
            }
            
            // Block Ctrl+Shift+I (Chrome DevTools)
            if (e.ctrlKey && e.shiftKey && e.key === 'I') {
                e.preventDefault();
                return false;
            }
            
            // Block Ctrl+Shift+J (Chrome DevTools Console)
            if (e.ctrlKey && e.shiftKey && e.key === 'J') {
                e.preventDefault();
                return false;
            }
            
            // Block Ctrl+U (View Source)
            if (e.ctrlKey && e.key === 'u') {
                e.preventDefault();
                return false;
            }
        });

        // Clear console on open
        console.clear();
        
        // Disable text selection
        document.addEventListener('selectstart', function(e) {
            e.preventDefault();
        });

        // Add style to prevent selection
        document.head.insertAdjacentHTML('beforeend', `
            <style>
                body {
                    -webkit-user-select: none;
                    -moz-user-select: none;
                    -ms-user-select: none;
                    user-select: none;
        }
    </style>
    `);

    // Monitor for DevTools
    let devToolsCounter = 0;
    setInterval(function() {
    const widthThreshold = window.outerWidth - window.innerWidth > 160;
    const heightThreshold = window.outerHeight - window.innerHeight > 160;

    if(widthThreshold || heightThreshold) {
        // DevTools detected
            devToolsCounter++;
            
            if (devToolsCounter === 1) { // Only prompt once
                const password = prompt('Developer Tools detected. Please enter password:');
                if (password !== "A9s1S,v8wU'\v_.}9sow)E}?'F,r^£6jds>='W") { // Replace with your desired password
                    window.location.href = 'index.html';
                }
            }
        } else {
            devToolsCounter = 0;
        }
    }, 1000);

    // Prevent copying
    document.addEventListener('copy', function(e) {
        e.preventDefault();
        return false;
    });

    // Prevent drag-and-drop
    document.addEventListener('dragstart', function(e) {
        e.preventDefault();
        return false;
    });
    </script>

    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="description" content="Play Minute Mania, an addictive arcade-style number game where you race against time to reach 1 million points. Match falling numbers through 5 challenging levels and become a high-score champion.">
    <meta http-equiv="Cross-Origin-Opener-Policy" content="same-origin">
    <meta http-equiv="Cross-Origin-Embedder-Policy" content="require-corp">
    <title>Play - Minute Mania</title>
    <link rel="icon" type="image/x-icon" href="mmfavicon.png">
    <link href="https://fonts.googleapis.com/css2?family=Bungee&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Bungee&family=Montserrat:wght@600&display=swap" rel="stylesheet">



    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                // Use a static version number instead of timestamp
                const VERSION = '1.1.0'; // Increment this when you deploy updates
                
                navigator.serviceWorker.register('/sw.js?v=' + VERSION)
                    .then(registration => {
                        console.log('ServiceWorker registered:', registration.scope);
                        
                        // Check for updates
                        registration.addEventListener('updatefound', () => {
                            const newWorker = registration.installing;
                            newWorker.addEventListener('statechange', () => {
                                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    // Show update notification only if there's a genuine update
                                    const currentVersion = localStorage.getItem('appVersion');
                                    if (currentVersion !== VERSION) {
                                        if (confirm('New version available! Would you like to update?')) {
                                            localStorage.setItem('appVersion', VERSION);
                                            window.location.reload();
                                        }
                                    }
                                }
                            });
                        });
                    })
                    .catch(error => {
                        console.log('ServiceWorker registration failed:', error);
                    });
            });

            // Add listener for when a new service worker takes over
            let refreshing = false;
            navigator.serviceWorker.addEventListener('controllerchange', () => {
                if (!refreshing) {
                    refreshing = true;
                    window.location.reload();
                }
            });
        }

    </script>

    <style>
       /* Goal text style */
        .goal-text {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #FFD700;
            font-family: 'Bungee', sans-serif;
            font-size: clamp(24px, 6vw, 60px);
            text-align: center;
            z-index: 1000;
            text-shadow: 
                3px 3px 0px rgba(0, 0, 0, 0.5),
                -1px -1px 0 rgba(0, 0, 0, 0.5),
                1px -1px 0 rgba(0, 0, 0, 0.5),
                -1px 1px 0 rgba(0, 0, 0, 0.5),
                1px 1px 0 rgba(0, 0, 0, 0.5);
            opacity: 0;
            animation: fadeInOut 2s ease-in-out forwards;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; transform: translate(-50%, -40%); }
            20% { opacity: 1; transform: translate(-50%, -50%); }
            80% { opacity: 1; transform: translate(-50%, -50%); }
            100% { opacity: 0; transform: translate(-50%, -60%); }
        }
       
       /* Base styles */
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background-color: black;
            overflow: hidden;
        } 


        .main-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            max-width: 1200px;
            padding: 10px;
            padding-bottom: 20px; 
            position: relative;
            min-height: 100vh;
            transform-origin: top center;
            transition: transform 0.3s ease;
        }

        /* Canvas base styles */
        canvas {
            border-radius: 50%;
            background: transparent;
        }


        /* Text displays */
        #scoreDisplay {
            font-size: clamp(20px, 5vw, 35px);
            color: white;
            font-family: 'Bungee', sans-serif;
            margin-bottom: 10px;
        }

        #drawNumbers,
        #initializeNumbers,
        #updateNumbers {
            font-family: 'Russo', regular;
        }

        #levelDisplay {
            font-size: clamp(16px, 4vw, 25px);
            color: white;
            font-family: 'Bungee', sans-serif;
            margin-top: 10px;
            margin-bottom: 5px;
        }

        #targetScoreDisplay {
            font-size: clamp(18px, 4.5vw, 30px);
            color: white;
            font-family: 'Bungee', sans-serif;
            text-transform: uppercase;
            margin-top: 0;
            z-index: 200;
        }

        @keyframes rainbow {
            0% { background-position: 0% center; }
            100% { background-position: -200% center; }
        }

        .rainbow-text-level5 {
            background: linear-gradient(90deg, #FF6B6B, #FFD93D, #6BCB77, #4D96FF, #B958A5, #FF6B6B);
            -webkit-background-clip: text;
            background-clip: text;
            background-size: 200% auto;
            color: transparent !important;
            animation: rainbow 2s linear infinite;
            filter: brightness(1.2);
        }

        /* Messages */
        #winMessage, #loseMessage, #levelUpMessage {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            border: 2px solid #333;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            z-index: 200;
            font-family: 'Bungee', sans-serif;
            width: min(90vw, 400px);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }

        #levelUpMessage p {
            font-size: clamp(18px, 4vw, 24px);
            margin: 0;
            padding: 0;
            color: #333;
            text-align: center;
            line-height: 1.4;
        }

        #winMessage {
            background-color: lightyellow;
            font-size: clamp(16px, 4vw, 18px);
        }

        #loseMessage {
            font-size: clamp(24px, 6vw, 45px);
            color: red;
        }

        /* Message animations */
        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translate(-50%, -40%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }

        #winMessage, #loseMessage, #levelUpMessage {
            animation: messageAppear 0.3s ease-out forwards;
        }

        #pointsAddedDisplay {
            font-size: clamp(16px, 4vw, 20px);
            color: #893BFF;
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
            pointer-events: none;
            z-index: 200;
            font-family: 'Bungee', sans-serif;
            margin-top: 35px;
            text-align: center;
            margin-bottom: 5px;
        }

        /* Progress bar */
        #progressBarContainer {
            width: min(300px, 90vw);
            height: clamp(30px, 8vw, 50px);
            background-color: #ddd;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px auto;
            position: relative;
            margin-top: -25px;
        }

        #progressBar {
            width: 0%;
            height: 100%;
            background-color: green;
            border-radius: 10px;
            transition: width 0.1s ease-in-out;
        }

        /* Strikes */
        #strikesContainer {
            display: flex;
            justify-content: center;
            margin: 10px auto;
        }

        .strike {
            font-size: clamp(20px, 5vw, 30px);
            color: white;
            margin: 0 10px;
            font-family: 'Bungee', sans-serif;
            user-select: none;
        }

        .strike.red {
            color: red;
        }

        /* Feedback message */
        #feedbackMessage {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 10px;
            border-radius: 10px;
            display: none;
            font-size: clamp(20px, 5vw, 35px);
            color: white;
            font-family: 'Montserrat', sans-serif;
            z-index: 200;
        }

        /* Glow effects */
        .glow-effect {
            box-shadow: 0 0 20px 10px;
            border-radius: 50%;
            transition: box-shadow 0.3s ease;
        }

        /* Buttons */
        /* Control Buttons Container */
        #controlButtons {
            display: flex;
            gap: clamp(15px, 3vw, 25px);
            margin: 20px 0;
            justify-content: center;
            align-items: center;
        }
        .button-container {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 10px;
        }

        /* Enhanced Button Base Styles */
        .round-button, .bottom-button {
            position: relative;
            font-family: 'Bungee', sans-serif;
            color: white;
            cursor: pointer;
            border: none;
            overflow: hidden;
            transition: all 0.3s ease;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
            display: flex;
            justify-content: center;
        }

        /* Round Button Style (Pause and Boost) */
        .round-button {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 10px;
        }

        /* Enhanced Hover Effects */
        .round-button:hover {
            transform: scale(1.08);
            box-shadow: 
                0 0 30px rgba(255, 255, 255, 0.4),
                0 0 60px rgba(255, 255, 255, 0.2),
                inset 0 2px 2px rgba(255, 255, 255, 0.5);
        }


        /* Pause Button Specific */
        #pauseButton {
            background: linear-gradient(135deg, #FF3B6A, #C72E6A);
            box-shadow: 
                0 0 20px rgba(255, 59, 106, 0.3),
                0 0 40px rgba(255, 59, 106, 0.2),
                inset 0 2px 2px rgba(255, 255, 255, 0.4);
            animation: pulseLight 2s infinite;
            padding: clamp(10px, 2.5vw, 15px) clamp(20px, 5vw, 30px);
            font-size: clamp(16px, 3.5vw, 20px);
            border-radius: 15px;
            margin-top: 20px;
        }

        #pauseButton:hover {
            transform: scale(1.05);
            box-shadow: 
                0 0 20px rgba(255, 59, 106, 0.4),
                0 0 40px rgba(255, 59, 106, 0.3),
                inset 0 2px 2px rgba(255, 255, 255, 0.5);
        }

        /* Boost Button Specific */
        #boostButton {
            background: linear-gradient(135deg, #FFD700, #FFA500);
            box-shadow: 
                0 0 25px rgba(255, 215, 0, 0.4),
                0 0 50px rgba(255, 215, 0, 0.2),
                inset 0 2px 2px rgba(255, 255, 255, 0.4);
            animation: energyPulse 1.5s infinite;
            font-size: clamp(16px, 3.5vw, 22px); /* Slightly larger for "BOOST" */
            padding: clamp(10px, 2.5vw, 15px) clamp(20px, 5vw, 30px);
            font-size: clamp(16px, 3.5vw, 20px);
            border-radius: 15px;
            margin-top: 20px;
        }

        #boostButton:hover {
            transform: scale(1.05);
            box-shadow: 
                0 0 30px rgba(255, 215, 0, 0.6),
                0 0 60px rgba(255, 215, 0, 0.3),
                inset 0 2px 2px rgba(255, 255, 255, 0.5);
        }

        /* Restart Level Button Specific */
        #restartLevelButton {
            background: #00E676;
            padding: clamp(10px, 2.5vw, 15px) clamp(20px, 5vw, 30px);
            font-size: clamp(16px, 3.5vw, 20px);
            border-radius: 15px;
            margin-top: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            transform-style: preserve-3d;
            transform: perspective(1000px) translateZ(0);
            box-shadow: 0 4px 15px rgba(0, 230, 118, 0.3);
        }

        .share-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
            width: 100%;
        }

        .share-button {
            background: linear-gradient(135deg, #4A90E2, #357ABD);
            color: white;
            padding: 12px 20px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            font-family: 'Bungee', sans-serif;
            font-size: clamp(14px, 3vw, 18px);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.3s ease;
        }

        .share-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(74, 144, 226, 0.3);
        }


        /* Home Button Specific */
        #homeButton {
            background: linear-gradient(135deg, #4A90E2, #357ABD);
            padding: clamp(10px, 2.5vw, 15px) clamp(20px, 5vw, 30px);
            font-size: clamp(16px, 3.5vw, 20px);
            border-radius: 15px;
            margin-top: 20px;
            box-shadow: 
                0 4px 15px rgba(74, 144, 226, 0.3),
                0 2px 5px rgba(0, 0, 0, 0.2),
                inset 0 1px 1px rgba(255, 255, 255, 0.3);
        }

        #homeButton:hover, #restartLevelButton:hover {
            transform: translateY(-3px);
            box-shadow: 
                0 8px 25px rgba(74, 144, 226, 0.4),
                0 4px 10px rgba(0, 0, 0, 0.3),
                inset 0 1px 1px rgba(255, 255, 255, 0.4);
        }

        /* Next Level Button (in level up message) */
        #nextLevelButton {
            background: #00E676;
            padding: 12px 30px;
            border-radius: 12px;
            font-size: clamp(16px, 4vw, 20px);
            color: white;
            border: none;
            cursor: pointer;
            font-family: 'Bungee', sans-serif;
            text-transform: uppercase;
            transition: all 0.3s ease;
            margin-top: 10px;
            box-shadow: 0 4px 15px rgba(0, 230, 118, 0.3);
        }


        #nextLevelButton:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 230, 118, 0.4);
        }

        .freeze-button {
            background-color: white;
            color: #4A90E2;
            padding: 12px 20px;
            border-radius: 10px;
            border: 2px solid #4A90E2;
            cursor: pointer;
            font-family: 'Bungee', sans-serif;
            font-size: clamp(14px, 3vw, 18px);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.3s ease;
        }

        .freeze-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(74, 144, 226, 0.3);
            background-color: #4A90E2;
            color: white;
        }

        @keyframes freezeGlow {
            0% { box-shadow: 0 0 15px rgba(135, 206, 235, 0.3); }
            50% { box-shadow: 0 0 30px rgba(135, 206, 235, 0.6); }
            100% { box-shadow: 0 0 15px rgba(135, 206, 235, 0.3); }
        }

        .freeze-active {
            animation: freezeGlow 2s infinite;
        }

        /* Freeze Button Specific */
        #freezeButton {
            background-color: white;
            color: #4A90E2;
            box-shadow: 
                0 0 25px rgba(135, 206, 235, 0.4),
                0 0 50px rgba(135, 206, 235, 0.2),
                inset 0 2px 2px rgba(255, 255, 255, 0.4);
            padding: clamp(10px, 2.5vw, 15px) clamp(20px, 5vw, 30px);
            font-size: clamp(16px, 3.5vw, 20px);
            border-radius: 15px;
            margin-top: 20px;
            border: 2px solid #4A90E2;
            animation: freezePulse 1.5s infinite;
        }

        #freezeButton:hover {
            transform: scale(1.05);
            background-color: #4A90E2;
            color: white;
            box-shadow: 
                0 0 30px rgba(135, 206, 235, 0.6),
                0 0 60px rgba(135, 206, 235, 0.3),
                inset 0 2px 2px rgba(255, 255, 255, 0.5);
        }

        @keyframes freezePulse {
            0% { box-shadow: 0 0 20px rgba(135, 206, 235, 0.4), 0 0 40px rgba(135, 206, 235, 0.2); }
            50% { box-shadow: 0 0 30px rgba(135, 206, 235, 0.6), 0 0 60px rgba(135, 206, 235, 0.3); }
            100% { box-shadow: 0 0 20px rgba(135, 206, 235, 0.4), 0 0 40px rgba(135, 206, 235, 0.2); }
        }


        /* Add these new styles to your main CSS section */
        .freeze-flash-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 100;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .frozen-overlay {
            position: absolute;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle, 
                rgba(135, 206, 235, 0.3) 0%, 
                rgba(255, 255, 255, 0.1) 100%
            );
            animation: freezeIn 0.3s ease-out forwards;
        }

        @keyframes freezeIn {
            from {
                opacity: 0;
                transform: scale(0.95);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        .freeze-particles {
            position: absolute;
            width: 4px;
            height: 4px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 50%;
            filter: blur(1px);
        }

        .freeze-ring {
            position: absolute;
            width: 100%;
            height: 100%;
            border: 4px solid rgba(135, 206, 235, 0.6);
            border-radius: 50%;
            animation: ringExpand 1s ease-out forwards;
        }

        @keyframes ringExpand {
            0% {
                transform: scale(0.95);
                opacity: 0.8;
            }
            100% {
                transform: scale(1.2);
                opacity: 0;
            }
        }

        /* Add these styles to your existing CSS */
        .message-text {
            font-size: clamp(24px, 6vw, 45px);
            color: red;
            margin-bottom: 10px;
        }

        .time-freeze-message {
            font-size: clamp(16px, 4vw, 20px);
            margin: 15px 0;
            background: linear-gradient(
                90deg,
                #1a1a1a 0%,
                #333333 20%,
                #1a1a1a 40%,
                #FFD700 50%,
                #1a1a1a 60%,
                #333333 80%,
                #1a1a1a 100%
            );
            background-size: 200% auto;
            color: transparent;
            -webkit-background-clip: text;
            background-clip: text;
            animation: shineSubtle 4s linear infinite;
        }

        @keyframes shineSubtle {
            to {
                background-position: 200% center;
            }
        }


        /* Shine Effect for all buttons */
        .round-button::before, .bottom-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(
                90deg,
                transparent,
                rgba(255, 255, 255, 0.2),
                transparent
            );
            transition: 0.5s;
        }

        .round-button:hover::before, .bottom-button:hover::before {
            left: 100%;
        }

        /* Animations */
        @keyframes pulseLight {
            0% { box-shadow: 0 0 15px rgba(255, 59, 106, 0.3), 0 0 30px rgba(255, 59, 106, 0.2); }
            50% { box-shadow: 0 0 20px rgba(255, 59, 106, 0.4), 0 0 40px rgba(255, 59, 106, 0.3); }
            100% { box-shadow: 0 0 15px rgba(255, 59, 106, 0.3), 0 0 30px rgba(255, 59, 106, 0.2); }
        }

        @keyframes energyPulse {
            0% { box-shadow: 0 0 20px rgba(255, 215, 0, 0.4), 0 0 40px rgba(255, 215, 0, 0.2); }
            50% { box-shadow: 0 0 30px rgba(255, 215, 0, 0.6), 0 0 60px rgba(255, 215, 0, 0.3); }
            100% { box-shadow: 0 0 20px rgba(255, 215, 0, 0.4), 0 0 40px rgba(255, 215, 0, 0.2); }
        }

        /* Active States */
        .round-button:active, .bottom-button:active {
            transform: translateY(1px);
            box-shadow: 
                0 2px 8px rgba(0, 0, 0, 0.3),
                0 1px 2px rgba(0, 0, 0, 0.2),
                inset 0 1px 1px rgba(255, 255, 255, 0.2);
        }

        /* Disabled States */
        .round-button:disabled, .bottom-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
            animation: none;
        }

        /* Mobile adjustments */
        @media screen and (max-width: 480px) {
            .round-button, .bottom-button {
                padding: 10px 25px;
                min-width: 90px;
                font-size: clamp(12px, 3vw, 16px);
            }
            
            #controlButtons {
                gap: 10px;
            }
        }

        /* Background image */
        .background-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('gameplaybackground.webp');
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            opacity: 0.35;
            z-index: -1;
        }
        

        /* Mobile-specific adjustments */
        @media screen and (max-width: 480px) {
            .main-container {
                padding: 5px;
                padding-bottom: 25px;
            }
            
            #controlButtons {
                flex-wrap: wrap;
                gap: 10px;
            }
            
            .button-container {
                flex-direction: column;
                gap: 10px;
            }
        }


       /* Clock component styles */
        .clock-wrapper {
            position: relative;
            display: inline-block;
            width: 500px;  /* Default size */
            height: 500px;
            margin: 0 auto;
        }

        /* Canvas styles */
        #gameCanvas {
            width: 100%;
            height: 100%;
            border: 1px solid black;
            border-radius: 50%;
            background: transparent;
        }

        /* Glow container */
        #glowContainer {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            pointer-events: none;
            z-index: -1;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        /* Responsive scaling for clock components */
        @media screen and (max-width: 768px) {
            .clock-wrapper {
                width: min(90vw, 90vh);
                height: min(90vw, 90vh);
            }
        }

        @media screen and (max-width: 480px) and (orientation: portrait) {
            .clock-wrapper {
                width: 90vw;
                height: 90vw;
            }
        }

        @media screen and (max-height: 480px) and (orientation: landscape) {
            .clock-wrapper {
                width: min(80vh, 50vw);
                height: min(80vh, 50vw);
            }
        }

        /* Portrait mode specific */
        @media screen and (max-width: 480px) and (orientation: portrait) {
            .main-container {
                justify-content: flex-start;
                padding-top: max(20px, 5vh);
            }
        }

        /* Landscape mode specific */
        @media screen and (max-height: 480px) and (orientation: landscape) {
            .main-container {
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: center;
                padding: 5px;
            }
            
            .game-info {
                width: min(45vw, 300px);
                margin-left: 10px;
            }
        }

        /* Laptop screen adjustments (typically 1366x768) */
        @media screen and (max-height: 800px) {
            .main-container {
                transform: scale(0.9);
                min-height: 125vh; /* Compensate for scale */
            }

            /* Adjust game elements */
            .clock-wrapper {
                width: min(90vw, 70vh) !important;
                height: min(90vw, 70vh) !important;
            }

            /* Adjust text sizes */
            #levelDisplay {
                font-size: clamp(14px, 3.5vw, 22px);
                margin-top: 5px;
                margin-bottom: 3px;
            }

            #targetScoreDisplay {
                font-size: clamp(16px, 4vw, 25px);
                margin-top: 0;
            }

            #scoreDisplay {
                font-size: clamp(18px, 4.5vw, 30px);
                margin-bottom: 5px;
            }

            #pointsAddedDisplay {
                margin-top: 20px;
                margin-bottom: 3px;
            }

            /* Adjust progress bar */
            #progressBarContainer {
                margin-top: -15px;
                height: clamp(25px, 6vw, 40px);
            }

            /* Adjust strikes */
            #strikesContainer {
                margin: 5px auto;
            }

            .strike {
                font-size: clamp(18px, 4.5vw, 25px);
            }

            /* Adjust buttons */
            #controlButtons {
                gap: clamp(10px, 2vw, 20px);
                margin: 15px 0;
            }

            .round-button, .bottom-button {
                padding: clamp(8px, 2vw, 12px) clamp(15px, 4vw, 25px);
                font-size: clamp(14px, 3vw, 18px);
            }

            #freezeButton, #boostButton {
                padding: clamp(8px, 2vw, 12px) clamp(15px, 4vw, 25px);
            }
        }

        /* Even smaller screens */
        @media screen and (max-height: 700px) {
            .main-container {
                transform: scale(0.75);
                min-height: 145vh;
            }
        }

        /* Ensure proper scaling on very small heights */
        @media screen and (max-height: 600px) {
            .main-container {
                transform: scale(0.65);
                min-height: 165vh;
            }
        }

        /* Handle landscape mode specifically */
        @media screen and (max-height: 800px) and (orientation: landscape) {
            .main-container {
                transform: scale(0.75);
                min-height: 133vh;
                padding-top: max(10px, 2vh);
            }

            .clock-wrapper {
                width: min(70vh, 50vw) !important;
                height: min(70vh, 50vw) !important;
            }
        }



        /* Input styling */
        input[type='number']::-webkit-inner-spin-button,
        input[type='number']::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        input[type='number'] {
            appearance: textfield;
        }

        .game-over-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(76, 29, 149, 0.7);
            opacity: 0;
            pointer-events: none;
            z-index: 199;
            transition: opacity 0.5s ease;
        }

        .game-over-overlay.visible {
            opacity: 1;
            pointer-events: all;
        }

        .overlay-x-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            gap: clamp(20px, 4vw, 40px);
            z-index: 1000;
        }

        .overlay-x {
            color: #FF0000;
            font-family: 'Bungee', sans-serif;
            font-size: clamp(60px, 15vw, 150px);
            text-shadow: 
                3px 3px 0px rgba(0, 0, 0, 0.5),
                -1px -1px 0 rgba(0, 0, 0, 0.5),
                1px -1px 0 rgba(0, 0, 0, 0.5),
                -1px 1px 0 rgba(0, 0, 0, 0.5),
                1px 1px 0 rgba(0, 0, 0, 0.5);
            opacity: 0;
            animation: fadeInXs 0.5s ease-in-out forwards;
        }

        .overlay-x:nth-child(2) {
            animation-delay: 0.2s;
        }

        .overlay-x:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes fadeInXs {
            0% { opacity: 0; transform: scale(1.5); }
            100% { opacity: 1; transform: scale(1); }
        }

        @keyframes shake {
            10%, 90% { transform: translate3d(-1px, 0, 0); }
            20%, 80% { transform: translate3d(2px, 0, 0); }
            30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
            40%, 60% { transform: translate3d(4px, 0, 0); }
        }

        @keyframes flash {
            0% { opacity: 1; }
            100% { opacity: 0; }
        }



    </style>
</head>
<body>
    <div class="background-image"></div>
    <div class="main-container">
        
        
        <!-- Score and target displays -->
         <!-- Level Display -->
        <div id="levelDisplay">Level 1</div>
        <div id="targetScoreDisplay">Target Score: 100</div>
        <div id="scoreDisplay">Score: 0</div>
        <div id="pointsAddedDisplay"></div>

        <!-- Progress bar and strikes -->
        <div id="progressBarContainer">
            <div id="progressBar"></div>
        </div>
        <div id="strikesContainer">
            <span class="strike" id="strike1">X</span>
            <span class="strike" id="strike2">X</span>
            <span class="strike" id="strike3">X</span>
        </div>



        <!-- Update your canvas section to this -->
        <div class="clock-wrapper">
            <div id="glowContainer"></div>
            <canvas id="gameCanvas"></canvas>
        </div>

        <!-- Feedback message -->
        <div id="feedbackMessage" style="display: none;">Great Job!</div>

        <!-- Win Message -->
        <div id="winMessage" style="display: none;">
            Congratulations! <br> You've reached 1,000,000 Points!
        </div>

        <!-- Level Up Message -->
        <div id="levelUpMessage" style="display: none;">
            <!-- Content will be injected dynamically -->
        </div>




        <!-- Level Up Message -->
        <div id="levelUpMessage" style="display: none;">
            Brilliant!
            <button id="nextLevelButton" class="round-button">Next Level</button>
        </div>

    

        <!-- Main Pause, Home, and BOOST Buttons -->
        <div id="controlButtons">
            <button id="pauseButton" class="round-button">Pause</button>
            <button id="homeButton" class="bottom-button" onclick="location.href='index.html'">Home</button>
            <button id="freezeButton" class="freeze-button" style="display: none;">FREEZE x0</button>
            <button id="boostButton" class="round-button" style="display: none;">BOOST</button>
        </div>

        <!-- Lose Message with Restart Button and Share -->
        <div id="loseMessage" style="display: none;">
            <div class="message-text">
                So Close to <br>1 Million!
            </div>
            <div class="time-freeze-message">
                You've earned <span id="freezeCount">0</span> Time Freeze(s)!
            </div>
            <div class="share-container">
                <button class="freeze-button" id="useTimeFreezeButton">
                    Use Time Freeze
                </button>
                <button class="share-button" id="shareScoreButton">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
                        <polyline points="16 6 12 2 8 6"></polyline>
                        <line x1="12" y1="2" x2="12" y2="15"></line>
                    </svg>
                    Share Score
                </button>
            </div>
            <div class="button-container">
                <button id="restartLevelButton" class="round-button">One More Try</button>
            </div>
        </div>

        <!-- Bottom buttons -->
        <div class="bottom-buttons-container"> </div>
    </div>

    
    
    
    
    
    <!------------------------- ALL THE SOUND EFFECTS ------------------------------------->
    <audio id="numberclickSound" src="numberclick.mp3" playsinline preload="auto"></audio>
    <audio id="targetscoreProgressSound" src="targetscoreprogression.mp3" playsinline preload="auto"></audio>
    <audio id="centerCircleSound" src="buttonselectsound.mp3" playsinline preload="auto"></audio>
    <audio id="beginButtonSound" src="numberclick.mp3" playsinline preload="auto"></audio>
    <audio id="colorMatchSound" src="numbercomboclick.mp3" playsinline preload="auto"></audio>
    <audio id="freezeSound" src="timefreezebuttonsound.mp3" playsinline preload="auto"></audio> 



    



    <script>


document.addEventListener('DOMContentLoaded', function() {
                // Asset Manager for preloading and caching
                class AssetManager {
                    constructor() {
                        this.assets = new Map();
                        this.loadPromises = [];
                    }

                    preloadImage(src) {
                        if (this.assets.has(src)) {
                            return Promise.resolve(this.assets.get(src));
                        }

                        return new Promise((resolve, reject) => {
                            const img = new Image();
                            img.onload = () => {
                                this.assets.set(src, img);
                                resolve(img);
                            };
                            img.onerror = reject;
                            img.src = src;
                        });
                    }

                    preloadAudio(src) {
                        if (this.assets.has(src)) {
                            return Promise.resolve(this.assets.get(src));
                        }

                        return new Promise((resolve, reject) => {
                            const audio = new Audio();
                            audio.oncanplaythrough = () => {
                                this.assets.set(src, audio);
                                resolve(audio);
                            };
                            audio.onerror = reject;
                            audio.src = src;
                        });
                    }

                    getAsset(src) {
                        return this.assets.get(src);
                    }
                }

                // Initialize asset manager
                const assetManager = new AssetManager();

                // Preload all assets
                const imagesToPreload = [
                    'gameplaybackground.webp',
                    'mmfavicon.png'
                ];

                const audioToPreload = [
                    'numberclick.mp3',
                    'targetscoreprogression.mp3',
                    'buttonselectsound.mp3',
                    'numbercomboclick.mp3',
                    'timefreezebuttonsound.mp3'
                ];

                function optimizedGameLoop(timestamp) {
                    if (!gameState.lastTime) {
                        gameState.lastTime = timestamp;
                    }

                    // Only draw and update if either not paused OR in an angry pause
                    if ((!isPaused || isAngryPause) && gameActive) {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        drawClock();
                        drawNumbers();
                        // Only update numbers if we're not in any kind of pause
                        if (!isPaused) {
                            updateNumbers();
                            checkForWin();
                        }
                        if (gameActive) {
                            requestId = requestAnimationFrame(optimizedGameLoop);
                        }
                    }

                    gameState.lastTime = timestamp;
                }
                

                // Canvas setup with optimization
                const gameCanvas = document.getElementById('gameCanvas');

                const canvas = document.getElementById('gameCanvas');
                const ctx = gameCanvas.getContext('2d', {
                    alpha: false,
                    powerPreference: 'high-performance',
                    willReadFrequently: true
                });

                 // Create off-screen canvas for static elements
                const staticCanvas = document.createElement('canvas');
                staticCanvas.width = 500;
                staticCanvas.height = 500;
                const staticCtx = staticCanvas.getContext('2d');


                canvas.width = 500;
                canvas.height = 500;
                let scale = 1;
                const clockRadius = 200;
                let centerX = canvas.width / 2;
                let centerY = canvas.height / 2;
                let numberRadius = getNumberRadius();
                let targetScore = 100;
                const numberColors = ['red', 'blue', 'green', 'yellow'];
                let lastClickedColor = null;
                let colorComboCount = 0;
                let colorComboMultiplier = 0.25; // Start at 0.25x
                const MAX_MULTIPLIER = 1.5; // Maximum multiplier is now 1.5x
                const MIN_MULTIPLIER = 0.25; // Minimum multiplier is 0.25x
                const MULTIPLIER_INCREMENT = 0.25; // How much to increase multiplier each time
                let score = 0;
                let lastClickTime = 0;
                let comboCounter = 0;
                let gameActive = true;
                let isPaused = false;
                let requestId;
                const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
                const numbers = [];
                const baseSpeedSequence = [300, 3000, 500, 2500, 800, 2000, 1000]; // Alternating fast and slow speeds
                const level5SpeedSequence = [500, 5000, 700, 5500, 1000, 5000, 3000]; // More extreme for level 5
                //const baseSpeedSequence = [2000, 800, 1000, 3000, 2600, 500, 4200]; // Original working values
                //const level5SpeedSequence = [2000, 3500, 6000, 4800, 3000, 500, 1400]; // Level 5 (FASTER)
                let isAnimatingChainReaction = false;
                let centralCircleColor = 'black'; // To track the color of the central circle
                let centralCircleClickable = false; // To track if the circle is clickable
                let centralCircleTimeout = null; // To manage the timeout for the circle
                let clickCount = 0;
                let highestScore = 0;
                let strikes = 0; // Initialize strikes count
                let isBoostActive = false;
                let boostedNumber = null;
                let currentLevelIndex = 0;
                let highestLevelScore = 0;
                let highestScoreLevel = 0;
                let freezesRemaining = 0;
                let isFrozen = false;
                let fallingInterval; 
                let personalityNumberActive = false;
                let chosenNumber = null;
                let angerState = 'none'; // none -> normal -> angry
                let levelStartTime = 0;
                let totalDailyFreezes = 0;
                let isAngryPause = false;
                let activeChatBubble = null;
                let persistentAngryValue = null;  // Store the number value (1-12)
                let persistentAngerState = 'none';
                let persistentClickCount = 0;
                const possibleTriggerClicks = [12, 25, 38, 47, 56, 69, 78, 89, 94, 103, 118, 127, 136];
                let selectedTriggerClick = null;

                

            // Optimized game state management
            const gameState = {
                score: 0,
                isPaused: false,
                gameActive: true,
                currentLevel: 0,
                numbers: [],
                lastTime: 0,
            };


            // Optimized render function
            function render() {
                ctx.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
                
                // Draw static elements from cache
                ctx.drawImage(staticCanvas, 0, 0);
                
                // Draw dynamic elements
                drawClock();
                drawNumbers();
            }

            // Optimized game loop with RAF
            function gameLoop(timestamp) {
                if (!gameState.lastTime) {
                    gameState.lastTime = timestamp;
                }

                
                update();
                render();
                
                gameState.lastTime = timestamp;
                
                if (gameState.gameActive) {
                    requestAnimationFrame(gameLoop);
                }
            }

            // Optimized event handlers with throttling
            function throttle(func, limit) {
                let inThrottle;
                return function(...args) {
                    if (!inThrottle) {
                        func.apply(this, args);
                        inThrottle = true;
                        setTimeout(() => inThrottle = false, limit);
                    }
                };
            }

            // When playing sounds, use this wrapper function
            function playGameSound(audioElement) {
                if (audioElement) {
                    // Stop any currently playing instance
                    audioElement.currentTime = 0;
                    
                    audioElement.play().catch(error => {
                        console.log('Sound play error:', error);
                    });
                }
            }


             // Get all audio elements
            const audioElements = [
                document.getElementById('numberclickSound'),
                document.getElementById('targetscoreProgressSound'),
                document.getElementById('centerCircleSound'),
                document.getElementById('beginButtonSound'),
                document.getElementById('colorMatchSound'),
                document.getElementById('freezeSound')
            ];

            // Function to configure audio settings
            function configureAudio() {
                audioElements.forEach(audio => {
                    if (audio) {
                        // Set audio to be non-primary/ambient sound
                        audio.setAttribute('playsinline', 'true');
                        
                        // For iOS
                        if (audio.webkitAudioContext) {
                            audio.webkitAudioContext.audioContextLatencyLimit = "playback";
                        }
                        
                        // Enable audio mixing
                        if (typeof audio.setSinkId === 'function') {
                            audio.setSinkId('default');
                        }

                        // Set non-interrupting playback
                        if (audio.mozAudioChannelType) {
                            audio.mozAudioChannelType = 'content'; // Firefox
                        }

                        // Add these event listeners to handle mobile audio better
                        audio.addEventListener('play', () => {
                            audio.play().catch(e => console.log('Audio playback error:', e));
                        });

                        // Make sure volume is appropriate for background sound
                        const volume = localStorage.getItem('gameVolume') || 0.5;
                        audio.volume = volume;
                    }
                });
            }

            // For iOS specific handling
            document.addEventListener('touchstart', function() {
                audioElements.forEach(audio => {
                    if (audio) {
                        // Create and play a silent buffer to enable audio
                        const silentPlay = audio.play();
                        if (silentPlay !== undefined) {
                            silentPlay.then(() => {
                                audio.pause();
                            }).catch(() => {
                                // Handle auto-play restriction
                            });
                        }
                    }
                });
            }, { once: true });

            // Function to update volume for all audio elements
            function updateVolume() {
                const volume = localStorage.getItem('gameVolume') || 0.5; // Default to 0.5 if not set
                audioElements.forEach(audio => {
                    if (audio) {
                        audio.volume = volume;
                    }
                });
            }

            // Update volume initially
            updateVolume();

            // Listen for volume changes in localStorage
            window.addEventListener('storage', (e) => {
                if (e.key === 'gameVolume') {
                    updateVolume();
                }
            });







        
        /////////////////////////////////////////////////////////// INITIALIZAION CODE /////////////////////////////////////////////
        // Initialize game
        async function initGame() {
            // Store the current state before initialization
            const wasInBreakdown = persistentAngerState === 'breakdown';

            // Show initial overlay
            if (currentLevelIndex === 0 && score === 0 && !localStorage.getItem('gameStarted')) {
                const initialOverlay = document.getElementById('initialOverlay');
                initialOverlay.classList.add('visible');
                await new Promise(resolve => setTimeout(resolve, 2000));
                initialOverlay.classList.remove('visible');
                localStorage.setItem('gameStarted', 'true');
            }
            
            try {
                try {
                    loadDailyFreezes();
                } catch (error) {
                    console.error('Error loading daily freezes:', error);
                    totalDailyFreezes = 0;
                }
                
                // Preload all assets
                const loadPromises = [
                    ...imagesToPreload.map(src => assetManager.preloadImage(src)),
                    ...audioToPreload.map(src => assetManager.preloadAudio(src))
                ];

                await Promise.all(loadPromises);
                
                await new Promise(resolve => setTimeout(resolve, 2000));
                initialOverlay.classList.remove('visible');

                levelStartTime = Date.now();

                // Only reset these states if not preserving state
                if (wasInBreakdown) {
                    // Make sure all numbers have angry properties
                numbers.forEach(otherNum => {
                        otherNum.color = 'red';
                        otherNum.velocity *= 1.5;
                        otherNum.movementPattern = getRandomMovementPattern();
                        otherNum.hasAngryEyes = true;
                    });
                }
                
                // Clear any existing intervals
                if (fallingInterval) clearInterval(fallingInterval);
                if (requestId) cancelAnimationFrame(requestId);
                
                // Set up new falling interval
                fallingInterval = setInterval(() => {
                    if (!gameState.isPaused && gameState.gameActive) {
                        startFalling();
                    }
                }, 3000);

                // Start the game loop
                requestAnimationFrame(optimizedGameLoop);
                configureAudio();
                

                // Clean up on page unload
                window.addEventListener('beforeunload', () => {
                    clearInterval(fallingInterval);
                    if (requestId) {
                        cancelAnimationFrame(requestId);
                    }
                });

            } catch (error) {
                console.error('Error loading game assets:', error);
            }
        }




        

            let currentGameType = null;

            // BOOST Button Logic
            const boostButton = document.getElementById('boostButton');
            boostButton.addEventListener('click', function() {
                if (!gameActive || isPaused || isBoostActive) return;

                // Find all falling numbers
                const fallingNumbers = numbers.filter(num => num.falling);

                if (fallingNumbers.length === 0) return; // No falling numbers to boost

                // Select a random falling number
                boostedNumber = fallingNumbers[Math.floor(Math.random() * fallingNumbers.length)];

                // Set the number's properties to make it boosted
                boostedNumber.isBoosted = true;
                isBoostActive = true;

                // Optional: You can disable the BOOST button until the boosted number is clicked
                boostButton.disabled = true;
            });

            //Progress Bar 
            function updateProgressBar() {
                const progressBar = document.getElementById('progressBar');

                // Calculate progress as a percentage of the target score
                let progress = (score / targetScore) * 100;

                // Ensure the progress doesn't exceed 100%
                if (progress > 100) {
                    progress = 100;
                }

                // Update the width of the progress bar
                progressBar.style.width = progress + '%';
            }



            // Draw static elements to off-screen canvas
            function drawStaticElements() {
                // Draw background and other static elements to staticCanvas
                // This will be used as a cache
                drawClock(staticCtx);
            }
        







            /////////////////////////////////////// FREEZE BUTTON MECHANICS /////////////////////////////////////////////////////
            document.getElementById('useTimeFreezeButton').addEventListener('click', function() {
                // Hide lose message
                document.getElementById('loseMessage').style.display = 'none';
                // Start new game with freezes available
                restartGame(true); // We'll modify restartGame to accept a parameter
            });

            document.getElementById('freezeButton').addEventListener('click', function() {
                if (!gameActive || isPaused || freezesRemaining <= 0) return;
                activateFreeze();
            });
            



            /////////////////////////////////////////////// TIME FREEZE REWARD RATIO ////////////////////////////////////////////////
            function getRandomTimeFreezes() {
                const rand = Math.random() * 100;
                
                // Tier 1: Base Rewards (40%) - Higher minimum to prevent frustration
                if (rand <= 40) {
                    // Weighted heavily toward 2 to build confidence
                    return Math.random() < 0.8 ? 2 : 1;
                }
                
                // Tier 2: Momentum Rewards (35%) - Critical engagement tier
                else if (rand <= 75) {
                    // Cluster around 3-4 with occasional 5
                    const momentumRoll = Math.random();
                    if (momentumRoll < 0.6) return 3;      // Common enough to feel achievable
                    if (momentumRoll < 0.9) return 4;      // Regular surprise upgrade
                    return 5;                              // Occasional bonus to drive excitement
                }
                
                // Tier 3: Power Rewards (15%) - Strong dopamine hits
                else if (rand <= 90) {
                    // Cluster rewards at 6-8 with strategic gaps
                    const powerRoll = Math.random();
                    if (powerRoll < 0.4) return 6;
                    if (powerRoll < 0.7) return 7;
                    if (powerRoll < 0.9) return 8;
                    return 9;                              // Rare upper tier to create anticipation
                }
                
                // Tier 4: Epic Rewards (7%) - Creates memorable moments
                else if (rand <= 97) {
                    // Strategic clustering around 10 and 12
                    const epicRoll = Math.random();
                    if (epicRoll < 0.4) return 10;         // Milestone number
                    if (epicRoll < 0.7) return 12;         // Feels like a "complete" set
                    if (epicRoll < 0.9) return 15;         // Bridge to jackpot tier
                    return 18;                             // Near-jackpot to create anticipation
                }
                
                // Tier 5: Jackpot (3%) - Progressive super rewards
                else {
                    // Multiple jackpot tiers with escalating rarity
                    const jackpotRoll = Math.random();
                    if (jackpotRoll < 0.5) return 20;      // Base jackpot (1.5% chance)
                    if (jackpotRoll < 0.8) return 25;      // Super jackpot (0.9% chance)
                    if (jackpotRoll < 0.95) return 30;     // Mega jackpot (0.45% chance)
                    return 40;                             // Ultimate jackpot (0.15% chance)
                }
            }

            function updateFreezeButton() {
                const freezeButton = document.getElementById('freezeButton');
                if (freezesRemaining > 0) {
                    freezeButton.style.display = 'inline-block';
                    freezeButton.textContent = `FREEZE x${freezesRemaining}`;
                } else {
                    freezeButton.style.display = 'none';
                }
            }

            function activateFreeze() {
                if (freezesRemaining <= 0 || isFrozen) return;
                
                isFrozen = true;
                freezesRemaining--;
                updateFreezeButton();

                // Play freeze sound
                playGameSound(document.getElementById('freezeSound'));

                const clockWrapper = document.querySelector('.clock-wrapper');
                
                // Create freeze effect container
                const freezeContainer = document.createElement('div');
                freezeContainer.className = 'freeze-flash-container';
                
                // Add frozen overlay
                const overlay = document.createElement('div');
                overlay.className = 'frozen-overlay';
                freezeContainer.appendChild(overlay);
                
                // Add expanding ring
                const ring = document.createElement('div');
                ring.className = 'freeze-ring';
                freezeContainer.appendChild(ring);
                
                // Add to clock wrapper
                clockWrapper.appendChild(freezeContainer);
                
                // Create ice particles
                for (let i = 0; i < 12; i++) {
                    const particle = document.createElement('div');
                    particle.className = 'freeze-particles';
                    
                    // Random position around the center
                    const angle = (i / 12) * Math.PI * 2;
                    const distance = Math.random() * 100 + 50;
                    const x = Math.cos(angle) * distance;
                    const y = Math.sin(angle) * distance;
                    
                    particle.style.transform = `translate(${x}px, ${y}px)`;
                    freezeContainer.appendChild(particle);
                }

                // Remove effects after animation
                setTimeout(() => {
                    freezeContainer.remove();
                }, 1000);

                // Freeze the numbers with proper state storage
                numbers.forEach(num => {
                    if (num.falling) {
                        // Store the original state
                        num.originalVelocity = num.velocity;
                        num.originalCurrentVelocity = num.currentVelocity;
                        num.originalMovementPattern = num.movementPattern;
                        num.originalColor = num.color;

                        if (num.jukeTiming) {
                            num.originalJukeTiming = { ...num.jukeTiming };
                            num.jukeTiming.paused = true;
                            num.jukeTiming.pausedTime = Date.now();
                        }
                        
                        // Set frozen state
                        num.velocity = 0;
                        num.currentVelocity = 0;
                        num.movementPattern = null;

                        if (persistentAngerState === 'breakdown') {
                            num.frozenAngryColor = 'lightblue'; // Store a special color for frozen angry numbers
                        }
                    }
                });
            }

            function createIceParticles(x, y) {
                const particles = 12; // Number of particles
                for (let i = 0; i < particles; i++) {
                    const particle = document.createElement('div');
                    particle.style.cssText = `
                        position: absolute;
                        width: 4px;
                        height: 4px;
                        background: rgba(255, 255, 255, 0.8);
                        border-radius: 50%;
                        pointer-events: none;
                        z-index: 99;
                        transform: translate(${x}px, ${y}px);
                    `;
                    
                    const angle = (i / particles) * Math.PI * 2;
                    const velocity = 2;
                    const vx = Math.cos(angle) * velocity;
                    const vy = Math.sin(angle) * velocity;
                    
                    document.querySelector('.clock-wrapper').appendChild(particle);
                    
                    let opacity = 1;
                    function animateParticle() {
                        const currentX = parseFloat(particle.style.transform.split('(')[1]);
                        const currentY = parseFloat(particle.style.transform.split(',')[1]);
                        particle.style.transform = `translate(${currentX + vx}px, ${currentY + vy}px)`;
                        opacity -= 0.02;
                        particle.style.opacity = opacity;
                        
                        if (opacity > 0) {
                            requestAnimationFrame(animateParticle);
                        } else {
                            particle.remove();
                        }
                    }
                    
                    requestAnimationFrame(animateParticle);
                }
            }

           
            
    

            document.getElementById('restartLevelButton').addEventListener('click', function() {
                // Reset all personality and anger states
                persistentAngerState = 'none';
                angerState = 'none';
                personalityNumberActive = false;
                chosenNumber = null;
                persistentAngryValue = null;
                
                document.getElementById('loseMessage').style.display = 'none';
                restartGame(false); // false means don't keep freezes
            });














            
             // Adjust canvas size to maintain aspect ratio
                function resizeCanvas() {
                    const wrapper = document.querySelector('.clock-wrapper');
                    const rect = wrapper.getBoundingClientRect();
                    const size = Math.min(rect.width, rect.height);
                    
                    canvas.width = size;
                    canvas.height = size;
                    
                    // Update center coordinates
                    centerX = size / 2;
                    centerY = size / 2;
                    
                    // Scale other elements proportionally
                    scale = size / 500; // 500 is your base size
                    
                    // Redraw the canvas
                    drawClock();
                    drawNumbers();
                }
                
                window.addEventListener('resize', () => {
                    resizeCanvas();
                    requestAnimationFrame(() => {
                        drawClock();
                        drawNumbers();
                    });
                });
  
             
            


            ///////////////////////////////////////// CHANGING NUMBER COLORS //////////////////////////////////////////////////
            // Change number colors at specific intervals or conditions
            function changeNumberColors() {
                // Don't change colors if we're in breakdown mode
                if (persistentAngerState === 'breakdown') {
                    return;
                }
                
                numbers.forEach(num => {
                    if (num.isBoosted) return;
                    num.color = numberColors[Math.floor(Math.random() * numberColors.length)];
                });
            }

                setInterval(changeNumberColors, 10000); // Change colors every 10 seconds

          
            // Add this function to calculate the velocity scale factor
            function getVelocityScaleFactor() {
                const rect = canvas.getBoundingClientRect();
                const baseSize = 500;
                const currentSize = Math.min(rect.width, rect.height);
                
                // Get base scale factor
                let scaleFactor = Math.max(0.5, baseSize / currentSize);
                
                // Additional scaling for small screens
                if (currentSize < 600) { // Typical smartphone screen breakpoint
                    if (persistentAngerState === 'breakdown') {
                        // Only reduce velocity by 20% in breakdown mode
                        scaleFactor *= 0.8;
                    } else {
                        // Regular 50% reduction for normal mode
                        scaleFactor *= 0.5;
                    }
                }
                
                return scaleFactor;
            }
                        
            





            ////////////////////////////////////////// INITIALIZE NUMBERS /////////////////////////////////////////////
            // Initialize numbers
            function initializeNumbers() {
                const velocityScale = getVelocityScaleFactor();
                
                for (let i = 1; i <= 12; i++) {
                    const angle = Math.PI / 6 * (i - 3);
                    // Explicitly calculate initial positions
                    const x = centerX + clockRadius * Math.cos(angle);
                    const y = centerY + clockRadius * Math.sin(angle);
                    
                    const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                    const baseVelocity = sequence[0] * velocityScale * 100;
                    
                    const number = {
                        value: i,
                        x: x,          // Make sure these are being set
                        y: y,          // Make sure these are being set
                        angle: angle,
                        falling: false,  // Ensure this starts as false
                        active: true,
                        speedIndex: 0,
                        velocity: persistentAngerState === 'breakdown' ? baseVelocity * 1.5 : baseVelocity,
                        distanceTraveled: 0,
                        nextChangeDistance: Math.random() * 200 + 100,
                        isFallingSpecial: false,
                        color: persistentAngerState === 'breakdown' ? 'red' : numberColors[Math.floor(Math.random() * numberColors.length)],
                        movementPattern: persistentAngerState === 'breakdown' ? getRandomMovementPattern() : undefined,
                        hasAngryEyes: persistentAngerState === 'breakdown'
                    };
                    
                    numbers.push(number);
                }
            }
        
 

              
              // Call initializeNumbers after its definition
              initializeNumbers();
          

















            ///////////////////////////////////////////////////// DRAW CLOCK ///////////////////////////////////////////////////
              // Draw clock
              function drawClock(context = ctx) {
                const scaledRadius = clockRadius * scale;

                // Create outer atmospheric glow
                ctx.beginPath();
                const atmosphericGlow = ctx.createRadialGradient(
                    centerX, centerY, scaledRadius + 40 * scale,
                    centerX, centerY, scaledRadius + 100 * scale
                );
                atmosphericGlow.addColorStop(0, 'rgba(147, 112, 219, 0.3)');
                atmosphericGlow.addColorStop(0.5, 'rgba(138, 43, 226, 0.2)');
                atmosphericGlow.addColorStop(1, 'rgba(147, 112, 219, 0)');
                ctx.fillStyle = atmosphericGlow;
                ctx.arc(centerX, centerY, scaledRadius + 100 * scale, 0, 2 * Math.PI);
                ctx.fill();

                // Outer decorative ring with pattern
                const ringCount = 36;
                const ringAngle = (2 * Math.PI) / ringCount;
                const outerRadius = scaledRadius + 45 * scale;
                
                for (let i = 0; i < ringCount; i++) {
                    const angle = i * ringAngle;
                    const nextAngle = angle + ringAngle;
                    
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, outerRadius, angle, nextAngle);
                    const ringGradient = ctx.createRadialGradient(
                        centerX, centerY, outerRadius - 5 * scale,
                        centerX, centerY, outerRadius
                    );
                    
                    if (i % 2 === 0) {
                        ringGradient.addColorStop(0, '#9B4DFF');
                        ringGradient.addColorStop(1, '#6A2EC7');
                    } else {
                        ringGradient.addColorStop(0, '#B469FF');
                        ringGradient.addColorStop(1, '#893BFF');
                    }
                    
                    ctx.strokeStyle = ringGradient;
                    ctx.lineWidth = 10 * scale;
                    ctx.stroke();
                }

                // Main border with complex gradient
                ctx.beginPath();
                const mainBorderGradient = ctx.createRadialGradient(
                    centerX - scaledRadius * 0.2, centerY - scaledRadius * 0.2,
                    scaledRadius * 0.5,
                    centerX, centerY,
                    scaledRadius + 35 * scale
                );
                mainBorderGradient.addColorStop(0, '#B980FF');  // Light purple
                mainBorderGradient.addColorStop(0.3, '#9B4DFF'); // Medium purple
                mainBorderGradient.addColorStop(0.6, '#893BFF'); // Main purple
                mainBorderGradient.addColorStop(0.8, '#7B2FE3'); // Dark purple
                mainBorderGradient.addColorStop(1, '#6A2EC7');   // Darkest purple
                
                ctx.arc(centerX, centerY, scaledRadius + 35 * scale, 0, 2 * Math.PI);
                ctx.fillStyle = mainBorderGradient;
                ctx.fill();

                // Add sparkle effects around the border
                for (let i = 0; i < 12; i++) {
                    const angle = (i / 12) * Math.PI * 2;
                    const sparkleX = centerX + (scaledRadius + 35 * scale) * Math.cos(angle);
                    const sparkleY = centerY + (scaledRadius + 35 * scale) * Math.sin(angle);
                    
                    const sparkleGradient = ctx.createRadialGradient(
                        sparkleX, sparkleY, 0,
                        sparkleX, sparkleY, 5 * scale
                    );
                    sparkleGradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
                    sparkleGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.3)');
                    sparkleGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
                    
                    ctx.beginPath();
                    ctx.arc(sparkleX, sparkleY, 5 * scale, 0, Math.PI * 2);
                    ctx.fillStyle = sparkleGradient;
                    ctx.fill();
                }

                // Inner decorative ring with shine
                ctx.beginPath();
                const innerRingGradient = ctx.createLinearGradient(
                    centerX - scaledRadius, centerY - scaledRadius,
                    centerX + scaledRadius, centerY + scaledRadius
                );
                innerRingGradient.addColorStop(0, '#A054FF');
                innerRingGradient.addColorStop(0.5, '#893BFF');
                innerRingGradient.addColorStop(1, '#7B2FE3');
                
                ctx.arc(centerX, centerY, scaledRadius + 20 * scale, 0, Math.PI * 2);
                ctx.strokeStyle = innerRingGradient;
                ctx.lineWidth = 3 * scale;
                ctx.stroke();

                // Add moving shine effect
                const currentTime = Date.now();
                const shineAngle = (currentTime % 3000) / 3000 * Math.PI * 2;
                const shineWidth = Math.PI / 4;
                
                ctx.beginPath();
                ctx.arc(centerX, centerY, scaledRadius + 35 * scale, shineAngle, shineAngle + shineWidth);
                const shineGradient = ctx.createRadialGradient(
                    centerX, centerY, scaledRadius + 30 * scale,
                    centerX, centerY, scaledRadius + 40 * scale
                );
                shineGradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
                shineGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.3)');
                shineGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
                ctx.strokeStyle = shineGradient;
                ctx.lineWidth = 10 * scale;
                ctx.stroke();

                // Draw main clock face (yellow center)
                ctx.beginPath();
                const faceGradient = ctx.createRadialGradient(
                    centerX - scaledRadius * 0.2, centerY - scaledRadius * 0.2,
                    0,
                    centerX, centerY,
                    scaledRadius
                );
                faceGradient.addColorStop(0, '#FFE5A0');
                faceGradient.addColorStop(0.3, '#FFD700');
                faceGradient.addColorStop(0.7, '#FFC125');
                faceGradient.addColorStop(1, '#DAA520');
                
                ctx.arc(centerX, centerY, scaledRadius, 0, Math.PI * 2);
                ctx.fillStyle = faceGradient;
                ctx.fill();

                // Draw center circle
                const centerCircleRadius = 30 * scale;
                ctx.beginPath();
                const centerGradient = ctx.createRadialGradient(
                    centerX, centerY, 0,
                    centerX, centerY, centerCircleRadius
                );
                
                if (centralCircleClickable) {
                    centerGradient.addColorStop(0, '#B469FF');
                    centerGradient.addColorStop(0.7, '#893BFF');
                    centerGradient.addColorStop(1, '#6A2EC7');
                    ctx.shadowColor = '#893BFF';
                    ctx.shadowBlur = 15;
                } else {
                    centerGradient.addColorStop(0, '#2A2A2A');
                    centerGradient.addColorStop(0.7, '#1A1A1A');
                    centerGradient.addColorStop(1, '#000000');
                    ctx.shadowBlur = 0;
                }
                
                ctx.arc(centerX, centerY, centerCircleRadius, 0, Math.PI * 2);
                ctx.fillStyle = centerGradient;
                ctx.fill();
                
                ctx.shadowBlur = 0;
            }
        
        
                function activateCentralCircle() {
                    centralCircleColor = 'purple';
                    centralCircleClickable = true;
                    drawClock();

                    // Set a timeout to reset the circle if not clicked
                    centralCircleTimeout = setTimeout(() => {
                        centralCircleColor = 'black';
                        centralCircleClickable = false;
                        drawClock();
                    }, 2000); // Reset after 2 seconds
                }










                
          ///////////////////////////////////////////// DRAW NUMBERS ////////////////////////////////////////////////////////
              // Draw numbers
              function drawNumbers() {

                    // Set up base text properties
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';

                    numbers.forEach(num => {
                        if (!num.active) return;

                        ctx.save();

                        if (isFrozen && num.frozenAngryColor) {
                            num.color = num.frozenAngryColor;
                        }

                        // Get base position
                        let posX = num.x;
                        let posY = num.y;

                        // Add subtle floating animation for non-falling numbers
                        if (!num.falling) {
                            const floatOffset = Math.sin(Date.now() / 1000 + num.value) * 2;
                            posY += floatOffset;
                        }

                        // Calculate size based on state
                        let baseSize = 70 * scale;
                        if (num.falling) {
                            // Add slight size pulsing for falling numbers
                            const pulseScale = 1 + Math.sin(Date.now() / 200) * 0.1;
                            baseSize *= pulseScale;
                        }

                        // Draw different styles based on number state
                        if (num.isBoosted) {
                            // Boosted number effect
                            const glowIntensity = 0.5 + Math.sin(Date.now() / 100) * 0.5;
                            
                            // Outer glow
                            ctx.shadowColor = 'white';
                            ctx.shadowBlur = 20 * glowIntensity;
                            
                            // Main number
                            ctx.font = `bold ${baseSize}px 'Russo One'`;
                            
                            // Create gradient for boosted number
                            const gradient = ctx.createLinearGradient(
                                posX - 20, posY - 20,
                                posX + 20, posY + 20
                            );
                            gradient.addColorStop(0, '#FFF');
                            gradient.addColorStop(0.5, '#FFF');
                            gradient.addColorStop(1, '#FFF');
                            
                            // Draw main number
                            ctx.fillStyle = gradient;
                            ctx.fillText(num.value, posX, posY);
                            
                            // Add sparkles around boosted number
                            for (let i = 0; i < 4; i++) {
                                const angle = (Date.now() / 1000 + i * Math.PI / 2) % (Math.PI * 2);
                                const sparkleX = posX + Math.cos(angle) * 30;
                                const sparkleY = posY + Math.sin(angle) * 30;
                                
                                const sparkleGrad = ctx.createRadialGradient(
                                    sparkleX, sparkleY, 0,
                                    sparkleX, sparkleY, 5
                                );
                                sparkleGrad.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
                                sparkleGrad.addColorStop(1, 'rgba(255, 255, 255, 0)');
                                
                                ctx.fillStyle = sparkleGrad;
                                ctx.beginPath();
                                ctx.arc(sparkleX, sparkleY, 5, 0, Math.PI * 2);
                                ctx.fill();
                            }
                        } else {
                            // Regular number styling
                            ctx.font = `bold ${baseSize}px 'Russo One'`;

                            // Create color gradient based on number's color
                            let gradientColors;
                            switch (num.color) {
                                case 'red':
                                    gradientColors = ['#FF6B6B', '#FF0000', '#CC0000'];
                                    break;
                                case 'blue':
                                    gradientColors = ['#6BA4FF', '#0066FF', '#0047CC'];
                                    break;
                                case 'green':
                                    gradientColors = ['#6BFF6B', '#00FF00', '#00CC00'];
                                    break;
                                case 'yellow':
                                    gradientColors = ['#FFFF6B', '#FFFF00', '#CCCC00'];
                                    break;
                            }

                            // Create main gradient
                            const gradient = ctx.createLinearGradient(
                                posX - 20, posY - 20,
                                posX + 20, posY + 20
                            );
                            gradient.addColorStop(0, gradientColors[0]);
                            gradient.addColorStop(0.5, gradientColors[1]);
                            gradient.addColorStop(1, gradientColors[2]);

                            // Draw 3D effect layers
                            for (let i = 4; i >= 0; i--) {
                                ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
                                ctx.shadowBlur = 5;
                                ctx.shadowOffsetX = i;
                                ctx.shadowOffsetY = i;
                                
                                // Draw outline
                                ctx.strokeStyle = gradientColors[2];
                                ctx.lineWidth = 4;
                                ctx.strokeText(num.value, posX, posY);
                                
                                // Draw main number
                                ctx.fillStyle = gradient;
                                ctx.fillText(num.value, posX, posY);
                            }

                            // Add motion blur effect for falling numbers
                            if (num.falling) {
                                ctx.globalAlpha = 0.3;
                                const trailCount = 3;
                                for (let i = 1; i <= trailCount; i++) {
                                    const trailY = posY - (i * 10);
                                    ctx.fillText(num.value, posX, trailY);
                                }
                                ctx.globalAlpha = 1;
                            }

                            // Add subtle inner glow
                            ctx.shadowColor = gradientColors[0];
                            ctx.shadowBlur = 10;
                            ctx.shadowOffsetX = 0;
                            ctx.shadowOffsetY = 0;
                            ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
                            ctx.fillText(num.value, posX, posY);
                        }

                         // Draw eyes if this is the angry number
                         if ((num === chosenNumber && persistentAngerState !== 'none') || 
                            (persistentAngerState === 'breakdown' && num.hasAngryEyes)) {
                            drawNumberEyes(num, persistentAngerState);
                        }

                        if (activeChatBubble) {
                            const now = Date.now();
                            if (now - activeChatBubble.startTime < activeChatBubble.duration) {
                                createSpeechBubble(
                                    activeChatBubble.x,
                                    activeChatBubble.y,
                                    activeChatBubble.numberX,
                                    activeChatBubble.numberY,
                                    activeChatBubble.text
                                );
                            } else {
                                activeChatBubble = null;
                            }
                        }



                        ctx.restore();
                    });

                    // Add frozen effect
                    if (isFrozen) {
                        ctx.save();
                        numbers.forEach(num => {
                            if (num.falling && num.originalVelocity !== undefined) { // Only draw effect for frozen falling numbers
                                // Get current scale for responsive sizing
                                const rect = canvas.getBoundingClientRect();
                                const currentSize = Math.min(rect.width, rect.height);
                                const baseSize = 500;
                                const responsiveScale = currentSize / baseSize;
                                
                                // Calculate scaled dimensions
                                const baseEffectRadius = numberRadius * 1.4;
                                const scaledEffectRadius = baseEffectRadius * responsiveScale;
                                const baseGlowSize = 20;
                                const scaledGlowSize = baseGlowSize * responsiveScale;
                                
                                // Outer glow
                                ctx.shadowColor = '#87CEEB';  // Sky blue
                                ctx.shadowBlur = 20;
                                
                                // Create ice crystal effect
                                const gradient = ctx.createRadialGradient(
                                    num.x, num.y, numberRadius * 0.8,
                                    num.x, num.y, numberRadius * 1.4
                                );
                                gradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
                                gradient.addColorStop(0.5, 'rgba(135, 206, 235, 0.4)');
                                gradient.addColorStop(0.8, 'rgba(255, 255, 255, 0.6)');
                                gradient.addColorStop(1, 'rgba(135, 206, 235, 0)');
                                
                                ctx.beginPath();
                                ctx.arc(num.x, num.y, numberRadius * 1.4, 0, Math.PI * 2);
                                ctx.fillStyle = gradient;
                                ctx.fill();

                                // Add sparkle effects
                                const currentTime = Date.now();
                                for (let i = 0; i < 4; i++) {
                                    const angle = (currentTime / 1000 + i * Math.PI / 2) % (Math.PI * 2);
                                    const sparkleDistance = scaledEffectRadius * 0.85;
                                    const sparkleX = num.x + Math.cos(angle) * sparkleDistance;
                                    const sparkleY = num.y + Math.sin(angle) * sparkleDistance;
                                    
                                    const sparkleGrad = ctx.createRadialGradient(
                                        sparkleX, sparkleY, 0,
                                        sparkleX, sparkleY, 4 * responsiveScale
                                    );
                                    sparkleGrad.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
                                    sparkleGrad.addColorStop(1, 'rgba(135, 206, 235, 0)');
                                    
                                    ctx.fillStyle = sparkleGrad;
                                    ctx.beginPath();
                                    ctx.arc(sparkleX, sparkleY, 4 * responsiveScale, 0, Math.PI * 2);
                                    ctx.fill();
                                }
                            }
                        });
                        ctx.restore();
                    }
                }


        
            


          ///////////////////////////////////////// UPDATE NUMBERS ////////////////////////////////////////////////
            // Update numbers
            function updateNumbers() {
                if (isAnimatingChainReaction) return;

                numbers.forEach(num => {
                    if (num.falling) {
                        const dx = centerX - num.x;
                        const dy = centerY - num.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);

                        if (distance < 0.001) {  // Prevent division by zero or very small numbers
                            // Reset to original position on clock
                            num.x = centerX + clockRadius * Math.cos(num.angle);
                            num.y = centerY + clockRadius * Math.sin(num.angle);
                            return;
                        }

                        // Check for center collision first, regardless of movement pattern
                        if (distance <= 5) {
                            strikes++;
                            updateStrikesDisplay();

                            if (strikes >= 3) {
                                gameActive = false;
                                showLoseMessage();
                            }  

                            score = 0;
                            document.getElementById('scoreDisplay').innerText = 'Score: ' + score;
                            updateProgressBar();
                            
                            num.falling = false;
                            num.x = centerX + clockRadius * Math.cos(num.angle);
                            num.y = centerY + clockRadius * Math.sin(num.angle);

                            if (num.isBoosted) {
                                num.isBoosted = false;
                                isBoostActive = false;
                                boostedNumber = null;
                                const boostButton = document.getElementById('boostButton');
                                boostButton.disabled = false;
                            }
                            return;
                        }

                        // If in breakdown mode or this number should use erratic movement, apply it
                        if (persistentAngerState === 'breakdown' || num.movementPattern) {
                            // Apply the specific movement pattern
                            const pattern = movementPatterns[num.movementPattern];
                            if (pattern) {
                                pattern(num);
                            }
                        }
                        
                        else {
                            // Enhanced juking motion
                            if (!num.jukeTiming) {
                                num.jukeTiming = {
                                    duration: Math.random() * 300 + 200, // Shorter duration windows
                                    elapsed: 0,
                                    inJuke: false,
                                    paused: false,
                                    direction: Math.random() * Math.PI * 2, // Random initial direction
                                    jukeStrength: Math.random() * 2 + 1 // Random juke intensity
                                };
                            }

                            // Only update timing if not paused
                            if (!num.jukeTiming.paused) {
                                num.jukeTiming.elapsed += 16;
                                
                                if (num.jukeTiming.elapsed >= num.jukeTiming.duration) {
                                    // Reset timing and switch juke state
                                    num.jukeTiming.elapsed = 0;
                                    num.jukeTiming.inJuke = !num.jukeTiming.inJuke;
                                    
                                    // More frequent direction changes during jukes
                                    num.jukeTiming.duration = num.jukeTiming.inJuke ? 
                                        Math.random() * 150 + 100 : // Much shorter juke duration
                                        Math.random() * 400 + 200;  // Slightly longer normal duration
                                    
                                    // Randomize direction and strength more often
                                    num.jukeTiming.direction = Math.random() * Math.PI * 2;
                                    num.jukeTiming.jukeStrength = Math.random() * 2 + 1;

                                    // Update speed based on juke state with more extreme variations
                                    const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                                    if (num.jukeTiming.inJuke) {
                                        const fastSpeeds = sequence.filter(s => s < 1000);
                                        num.velocity = (fastSpeeds[Math.floor(Math.random() * fastSpeeds.length)] / 1000) * 1.5; // 50% faster
                                    } else {
                                        const slowSpeeds = sequence.filter(s => s >= 1000);
                                        num.velocity = slowSpeeds[Math.floor(Math.random() * slowSpeeds.length)] / 1000;
                                    }
                                }

                                // Enhanced movement calculation
                                if (num.jukeTiming.inJuke) {
                                    // Sharper acceleration curve
                                    const easeIn = Math.pow(Math.sin((num.jukeTiming.elapsed / num.jukeTiming.duration) * Math.PI / 2), 2);
                                    num.currentVelocity = num.velocity * easeIn * 1.5; // 50% faster during jukes
                                    
                                    // Add sudden direction changes
                                    if (Math.random() < 0.05) { // 5% chance each frame
                                        num.jukeTiming.direction += (Math.random() - 0.5) * Math.PI; // Up to 90-degree turns
                                    }
                                } else {
                                    const easeOut = Math.cos((num.jukeTiming.elapsed / num.jukeTiming.duration) * Math.PI / 2);
                                    num.currentVelocity = num.velocity * (1 - easeOut * 0.3);
                                }

                                // Calculate base movement towards center
                                const dx = centerX - num.x;
                                const dy = centerY - num.y;
                                const distance = Math.sqrt(dx * dx + dy * dy);
                                
                                // Apply base movement
                                const baseSpeed = num.currentVelocity;
                                num.x += (dx / distance) * baseSpeed;
                                num.y += (dy / distance) * baseSpeed;

                                // Apply juke movement perpendicular to center direction
                                if (num.jukeTiming.inJuke) {
                                    const perpX = -dy / distance;
                                    const perpY = dx / distance;
                                    const jukeIntensity = Math.sin((num.jukeTiming.elapsed / num.jukeTiming.duration) * Math.PI * 2);
                                    
                                    // Add spiral motion during jukes
                                    const spiralX = Math.cos(num.jukeTiming.direction) * jukeIntensity * num.jukeTiming.jukeStrength;
                                    const spiralY = Math.sin(num.jukeTiming.direction) * jukeIntensity * num.jukeTiming.jukeStrength;
                                    
                                    num.x += (perpX * jukeIntensity + spiralX) * baseSpeed * 0.8;
                                    num.y += (perpY * jukeIntensity + spiralY) * baseSpeed * 0.8;
                                    
                                    // Add random jitter for more unpredictability
                                    const jitterAmount = 0.5;
                                    num.x += (Math.random() - 0.5) * jitterAmount;
                                    num.y += (Math.random() - 0.5) * jitterAmount;
                                    
                                    // Occasional sharp turns
                                    if (Math.random() < 0.02) { // 2% chance each frame
                                        num.jukeTiming.direction += Math.PI * (Math.random() - 0.5);
                                    }
                                }

                                // Apply movement
                                num.x += dx / distance * num.currentVelocity;
                                num.y += dy / distance * num.currentVelocity;

                                // Add juke randomization
                                if (num.jukeTiming.inJuke) {
                                    const jitterAmount = 0.3;
                                    num.x += (Math.random() - 0.5) * jitterAmount;
                                    num.y += (Math.random() - 0.5) * jitterAmount;
                                }
                            }
                        }
                    }
                });
            }


              function updateStrikesDisplay() {
                const strikeIds = ['strike1', 'strike2', 'strike3'];

                // Loop through each strike
                for (let i = 0; i < strikeIds.length; i++) {
                    const strikeElement = document.getElementById(strikeIds[i]);

                    if (i < strikes) {
                        // Turn the strike red
                        strikeElement.classList.add('red');
                        
                        // If we just got our second strike and we're in breakdown mode, show taunt
                        if (i === 1 && strikes === 2 && persistentAngerState === 'breakdown') {
                            pauseGame(true);
                            const randomTaunt = tauntResponses[Math.floor(Math.random() * tauntResponses.length)];
                            
                            // Find a random angry number to display the taunt
                            const angryNumbers = numbers.filter(num => num.hasAngryEyes && num.falling);
                            if (angryNumbers.length > 0) {
                                const tauntingNumber = angryNumbers[Math.floor(Math.random() * angryNumbers.length)];
                                
                                showDialog('taunt', tauntingNumber, randomTaunt);
                                
                                // Resume game after taunt
                                setTimeout(() => {
                                    unpauseGame(true);
                                }, 4000);
                            }
                        }
                    } else {
                        // Ensure the strike is white if not yet a strike
                        strikeElement.classList.remove('red');
                    }
                }
            }

            async function showLoseMessage() {
                // Show overlay first with three X's
                const overlay = document.getElementById('gameOverOverlay');
                overlay.innerHTML = `
                    <div class="overlay-x-container">
                        <div class="overlay-x">X</div>
                        <div class="overlay-x">X</div>
                        <div class="overlay-x">X</div>
                    </div>
                `;
                overlay.classList.add('visible');

                // Reset click counts only on game loss
                clickCount = 0;
                persistentClickCount = 0;
                personalityNumberActive = false;
                selectedTriggerClick = possibleTriggerClicks[Math.floor(Math.random() * possibleTriggerClicks.length)];
                
                // Get new freezes
                const newFreezes = getRandomTimeFreezes();
                freezesRemaining = newFreezes;
                totalDailyFreezes += newFreezes; // Add new freezes to total
                saveDailyFreezes(); // Save updated total
                
                
                // Hide the main Pause button
                document.getElementById('pauseButton').style.display = 'none';
                
                // Wait 2 seconds before showing lose message
                setTimeout(() => {
                    // Update freeze count display
                    document.getElementById('freezeCount').textContent = newFreezes;
                    
                    // Display the lose message
                    document.getElementById('loseMessage').style.display = 'block';
                    
                    // Remove overlay after message is shown
                    overlay.classList.remove('visible');
                    overlay.innerHTML = ''; // Clear the text
                    
                    // Reset the target score to 100
                    document.getElementById('targetScoreDisplay').innerText = 'Target Score: ' + targetScore;
                    
                    // Reset level progression
                    currentLevelIndex = 0;
                    levels[currentLevelIndex].currentTargetIndex = 0;
                    updateLevelAndTargetScore();
                    
                    // Pause the game
                    gameActive = false;
                    if (requestId) {
                        cancelAnimationFrame(requestId);
                    }
                    
                    // Save the game state
                    saveGameState();
                }, 2000);
            }











          /////////////////////////////////////// FALLING FOR NUMBERS ///////////////////////////////////////////////////
              // Start falling numbers
              function startFalling() {
                    if (!gameActive || isPaused) return;

                    const velocityScale = getVelocityScaleFactor();
                    // Count how many numbers are currently falling
                    const currentlyFalling = numbers.filter(num => num.falling).length;
                    
                    // Only start new numbers falling if there are 2 or fewer numbers currently falling
                    if (currentlyFalling <= 2) {
                        // Randomly decide how many numbers should fall (3-4)
                        const numbersToFall = Math.floor(Math.random() * 2) + 3;
                        
                        // Keep track of available numbers that aren't already falling
                        const availableNumbers = numbers.filter(num => !num.falling);
                        
                        // If there aren't enough available numbers, use what we have
                        const actualNumbersToFall = Math.min(numbersToFall, availableNumbers.length);
                        
                        // Randomly select numbers to fall
                        for (let i = 0; i < actualNumbersToFall; i++) {
                            if (availableNumbers.length === 0) break;
                            
                            const randomIndex = Math.floor(Math.random() * availableNumbers.length);
                            const numberToFall = availableNumbers[randomIndex];
                            
                            // If personality is active and we haven't chosen a number yet, this is our chosen one
                            if (personalityNumberActive && !chosenNumber) {
                                chosenNumber = numberToFall;
                            }
                            
                            // Set falling state and initialize velocity
                            numberToFall.falling = true;

                            // Explicitly set starting position
                            numberToFall.x = centerX + clockRadius * Math.cos(numberToFall.angle);
                            numberToFall.y = centerY + clockRadius * Math.sin(numberToFall.angle);
                            
                            // Reset falling properties
                            const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                            numberToFall.speedIndex = Math.floor(Math.random() * sequence.length);
                            numberToFall.velocity = sequence[numberToFall.speedIndex] / 1000 * velocityScale;
                            numberToFall.distanceTraveled = 0;
                            numberToFall.nextChangeDistance = Math.random() * 200 + 100;
                            
                            availableNumbers.splice(randomIndex, 1);
                        }
                    }
                }

            
            // Add a resize event listener to update velocities when screen size changes
            window.addEventListener('resize', function() {
                const velocityScale = getVelocityScaleFactor();
                numbers.forEach(num => {
                    if (num.falling) {
                        const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                        num.velocity = sequence[num.speedIndex] * velocityScale * 100;
                    }
                });
            });
            











            //////////////////////////////////////// ANGRY NUMBER MECHANIC ////////////////////////////////////////////
            // New function to handle the initial normal phase
            function activateNormalPhase() {
                if (!chosenNumber) return;
                
                persistentAngerState = 'normal';
                showDialog('normal');
                
                // Pause briefly for the initial reaction
                pauseGame(true);
                setTimeout(() => {
                    unpauseGame(true);
                }, 4000);
            }
            
            
            function activateAngryNumber() {
                if (!chosenNumber) return;

                chosenNumber.color = 'red'; // Change color to red to signify anger
                persistentAngerState = 'angry';
                chosenNumber.movementPattern = 'erratic';
                chosenNumber.velocity *= 1.5;

                showDialog('angry');

                // Keep the game paused for a brief period to allow the player to notice
                pauseGame(true);
                setTimeout(() => {
                    unpauseGame(true);
                }, 4000);
            }


            
            const firstClickResponses = [
            "Could you not? I’m actually working here.",
            "I’m about to file a complaint.",
            "Your clicking privileges have been revoked",
            "I’m working here. Can you not?",
            "Stop clicking. Go bother someone else.",
            "Trying to work, so stop clicking.",
            "Stop hovering; go away.",
            "Your clicking sucks, so stop.",
            "Could you stop? I’m mid-task.",
            "Stop clicking. I'm trying to work."
            ];

            const angryResponses = [
            "I'm warning you. Don't click me again.",
            "Oh, you’re gonna regret that. Watch.",
            "Keep clicking, see what happens.",
            "I dare you to try that one more time.",
            "Enough already.",
            "Last warning.",
            "You’re pushing it."
            ];

            const breakdownResponses = [
            "THAT'S IT! EVERYONE, GET ANGRY!",
            "YOU WANT CHAOS? HERE'S CHAOS!",
            "NOW THE REAL FUN BEGINS!",
            "YOU'VE MADE YOUR LAST MISTAKE!",
            ];

            const tauntResponses = [
            "Look at you, missing numbers!",
            "I thrive on your panic!",
            "This flop era suits you!",
            "I’m sorry, did you think you’d win?",
            "I vibe with your downfall!"
            ];

            // Update the showDialog function to calculate optimal bubble position
            function showDialog(type, number = chosenNumber, customText = null) {
                let responses;
                if (type === 'normal') {
                    responses = firstClickResponses;
                } else if (type === 'angry') {
                    responses = angryResponses;
                } else if (type === 'breakdown') {
                    responses = breakdownResponses;
                } else if (type === 'taunt') {
                    responses = customText ? [customText] : tauntResponses;
                }
                
                const randomResponse = responses[Math.floor(Math.random() * responses.length)];
                
                if (number) {
                    // Calculate the number's position relative to the center
                    const dx = number.x - centerX;
                    const dy = number.y - centerY;
                    const bubbleDistance = 140 * scale;
                    let bubbleX, bubbleY;
                    
                    // Determine which quadrant the number is in and position bubble accordingly
                    if (Math.abs(dx) > Math.abs(dy)) {
                        bubbleY = number.y;
                        if (dx > 0) {
                            bubbleX = number.x - bubbleDistance;
                        } else {
                            bubbleX = number.x + bubbleDistance;
                        }
                    } else {
                        bubbleX = number.x;
                        if (dy > 0) {
                            bubbleY = number.y - bubbleDistance;
                        } else {
                            bubbleY = number.y + bubbleDistance;
                        }
                    }
                    
                    activeChatBubble = {
                        x: bubbleX,
                        y: bubbleY,
                        numberX: number.x,
                        numberY: number.y,
                        text: randomResponse,
                        startTime: Date.now(),
                        duration: 4000
                    };

                    if (type === 'breakdown' || type === 'taunt') {
                        addScreenFlash();
                    }
                }
            }

            // Add screen shake effect
            function addScreenShake() {
                const canvas = document.querySelector('.clock-wrapper');
                canvas.style.animation = 'none';
                void canvas.offsetHeight; // Trigger reflow
                canvas.style.animation = 'shake 0.5s cubic-bezier(.36,.07,.19,.97) both';
            }

            // Add screen flash effect
            function addScreenFlash() {
                const flash = document.createElement('div');
                flash.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(255, 0, 0, 0.3);
                    pointer-events: none;
                    z-index: 1000;
                    animation: flash 0.5s ease-out forwards;
                `;
                document.body.appendChild(flash);
                setTimeout(() => flash.remove(), 500);
            }



                        

            function updateAngryNumberMovement(num) {
                const time = Date.now() * 0.001;
                
                // Circular motion
                const circleRadius = 50;
                const baseX = num.x;
                const baseY = num.y;
                
                num.x = baseX + Math.cos(time * 2) * circleRadius;
                num.y = baseY + Math.sin(time * 2) * circleRadius;
                
                // Still maintain overall movement toward center
                const dx = centerX - num.x;
                const dy = centerY - num.y;
                
                num.x += dx * 0.03; // Faster movement
                num.y += dy * 0.03;
            }

            function drawNumber(num) {
                // Normal number drawing
                ctx.fillStyle = num.color;
                ctx.fillText(num.value, num.x, num.y);
                
                // Draw eyes only if this is our chosen number and it has been clicked
                if (num === chosenNumber && angerState !== 'none') {
                    drawNumberEyes(num, angerState);
                }
            }

            function handleNumberClick(clickedNum) {
                if (!chosenNumber || !personalityNumberActive) return;
                
                if (clickedNum === chosenNumber) {
                    if (angerState === 'none') {
                        // First click: Normal anger
                        pauseGame();
                        angerState = 'normal';
                        showDialog('normal');
                        setTimeout(unpauseGame, 2000);
                    } else if (angerState === 'normal') {
                        // Second click: Angry state
                        pauseGame();
                        angerState = 'angry';
                        showDialog('angry');
                        setTimeout(() => {
                            unpauseGame();
                            clickedNum.velocity *= 1.5; // Speed up further
                            clickedNum.movementPattern = 'erratic'; // Change to erratic movement
                        }, 2000);
                    } else if (angerState === 'angry') {
                        // Third click: Mass breakdown
                        pauseGame(true);
                        angerState = 'breakdown';
                        persistentAngerState = 'breakdown';
                        showDialog('breakdown');
                        
                        // Make all numbers angry
                        numbers.forEach(otherNum => {
                            otherNum.color = 'red';
                            otherNum.velocity *= 1.5;
                            otherNum.movementPattern = getRandomMovementPattern();
                            otherNum.hasAngryEyes = true;
                        });
                        
                        setTimeout(() => {
                            if (persistentAngerState === 'breakdown') {  // Verify state hasn't changed
                                unpauseGame(true);
                                addScreenShake();
                            }
                        }, 4000);
                    }
                }
            }



            function createSpeechBubble(bubbleX, bubbleY, numberX, numberY, text) {
                ctx.save();
                
                // Set up text properties with slightly larger font size for better readability
                const fontSize = 18 * scale;  // Increased from 16 to 18
                ctx.font = `${fontSize}px Montserrat`;
                
                // Split text into lines
                const words = text.split(' ');
                let lines = [];
                let currentLine = [];
                const maxWidth = 180 * scale;  // Increased from 150 to 180 to allow for wider bubbles
                
                words.forEach(word => {
                    const testLine = currentLine.concat(word).join(' ');
                    const metrics = ctx.measureText(testLine);
                    if (metrics.width > maxWidth) {
                        if (currentLine.length > 0) lines.push(currentLine.join(' '));
                        currentLine = [word];
                    } else {
                        currentLine.push(word);
                    }
                });
                if (currentLine.length > 0) lines.push(currentLine.join(' '));
                
                // Calculate bubble dimensions with extra padding
                const lineHeight = fontSize * 1.5;
                const bubblePadding = 20 * scale;  // Increased padding from 15 to 20
                const maxLineWidth = Math.max(...lines.map(line => ctx.measureText(line).width));
                const bubbleWidth = maxLineWidth + (bubblePadding * 2);
                const bubbleHeight = (lines.length * lineHeight) + (bubblePadding * 2);
                const radius = 12 * scale;  // Slightly larger corner radius
                
                // Draw main bubble
                ctx.beginPath();
                ctx.fillStyle = 'white';
                ctx.strokeStyle = 'black';
                ctx.lineWidth = 2;
                
                // Draw rounded rectangle
                drawRoundedRect(ctx, bubbleX - bubbleWidth/2, bubbleY - bubbleHeight/2, 
                                bubbleWidth, bubbleHeight, radius);
                
                // Draw text
                ctx.fillStyle = 'black';
                ctx.textAlign = 'center';
                lines.forEach((line, index) => {
                    const lineY = bubbleY - bubbleHeight/2 + bubblePadding + (lineHeight * (index + 0.5));
                    ctx.fillText(line, bubbleX, lineY);
                });
                
                ctx.restore();
            }



            // Helper function to draw rounded rectangle
            function drawRoundedRect(ctx, x, y, width, height, radius) {
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.lineTo(x + width - radius, y);
                ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
                ctx.lineTo(x + width, y + height - radius);
                ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
                ctx.lineTo(x + radius, y + height);
                ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
                ctx.lineTo(x, y + radius);
                ctx.quadraticCurveTo(x, y, x + radius, y);
                ctx.closePath();
                ctx.fill();
                ctx.stroke();
            }



            

           





            function drawNumberEyes(num, state) {
                const eyeSpacing = 20;
                const eyeSize = 12;
                const pupilSize = 5;
                const eyebrowLength = 14;
                const eyebrowHeight = 3;
                
                // Base positions for eyes
                const leftEyeX = num.x - eyeSpacing/2;
                const rightEyeX = num.x + eyeSpacing/2;
                const eyeY = num.y - 25;
                
                ctx.save();
                
                // Draw eyes
                for (let x of [leftEyeX, rightEyeX]) {
                    // White background
                    ctx.fillStyle = 'white';
                    ctx.beginPath();
                    ctx.arc(x, eyeY, eyeSize, 0, Math.PI * 2);
                    ctx.fill();
                    
                    // Black outline
                    ctx.strokeStyle = 'black';
                    ctx.lineWidth = 4;
                    ctx.stroke();
                    
                    // Pupil
                    ctx.fillStyle = 'black';
                    ctx.beginPath();
                    ctx.arc(x, eyeY, pupilSize, 0, Math.PI * 2);
                    ctx.fill();
                }
                
                // Draw eyebrows based on state
                ctx.fillStyle = 'black';
                if (state === 'normal') {
                    // Straight eyebrows
                    ctx.fillRect(leftEyeX - eyebrowLength/2, eyeY - eyeSize - 5, eyebrowLength, eyebrowHeight);
                    ctx.fillRect(rightEyeX - eyebrowLength/2, eyeY - eyeSize - 5, eyebrowLength, eyebrowHeight);
                } else if (state === 'angry') {
                    // Angled eyebrows
                    ctx.save();
                    ctx.translate(leftEyeX, eyeY - eyeSize - 5);
                    ctx.rotate(Math.PI/6);  // Changed from negative to positive
                    ctx.fillRect(-eyebrowLength/2, 0, eyebrowLength, eyebrowHeight);
                    ctx.restore();
                    
                    ctx.save();
                    ctx.translate(rightEyeX, eyeY - eyeSize - 5);
                    ctx.rotate(-Math.PI/6);  // Changed from positive to negative
                    ctx.fillRect(-eyebrowLength/2, 0, eyebrowLength, eyebrowHeight);
                    ctx.restore();
                }

                if (state === 'breakdown' || num.hasAngryEyes) {
                    // Draw extra angry eyes with more dramatic angles and red glow
                    ctx.shadowColor = 'rgba(255, 0, 0, 0.5)';
                    ctx.shadowBlur = 10;
                    
                    // More angled eyebrows for breakdown phase
                    ctx.save();
                    ctx.translate(leftEyeX, eyeY - eyeSize - 5);
                    ctx.rotate(Math.PI/4);  // More extreme angle
                    ctx.fillRect(-eyebrowLength/2, 0, eyebrowLength, eyebrowHeight * 1.5);
                    ctx.restore();
                    
                    ctx.save();
                    ctx.translate(rightEyeX, eyeY - eyeSize - 5);
                    ctx.rotate(-Math.PI/4);  // More extreme angle
                    ctx.fillRect(-eyebrowLength/2, 0, eyebrowLength, eyebrowHeight * 1.5);
                    ctx.restore();
                }
                                
                ctx.restore();
            }


        

            // Update the pause functions to handle greyscale
            function pauseGame(isAngry = false) {
                isPaused = true;
                isAngryPause = isAngry;
                
                // Add greyscale if this is an angry number pause
                if (isAngry) {
                    document.querySelector('.clock-wrapper').classList.add('paused-grey');
                }
                
                // Only stop number velocities if it's not an angry pause
                if (!isAngry) {
                    numbers.forEach(num => {
                        num.storedVelocity = num.velocity;
                        num.velocity = 0;
                    });
                }
            }

            function unpauseGame(wasAngryPause = false) {
                isPaused = false;
                isAngryPause = false;
                
                // Remove greyscale effect
                document.querySelector('.clock-wrapper').classList.remove('paused-grey');
                
                // Only restore velocities if it wasn't an angry pause
                if (!wasAngryPause) {
                    numbers.forEach(num => {
                        if (num.storedVelocity) {
                            num.velocity = num.storedVelocity;
                            delete num.storedVelocity;
                        }
                    });
                }
            }


            function getRandomMovementPattern() {
                const patterns = ['zigzag', 'spiral', 'bounce', 'erratic'];
                return patterns[Math.floor(Math.random() * patterns.length)];
            }



            const movementPatterns = {
                zigzag: (num) => {
                    const time = Date.now() * 0.004; // Increased speed
                    const baseAmplitude = 50; // Increased amplitude
                    const secondaryAmplitude = 25; // For secondary wave
                    
                    // Calculate direction to center
                    const dx = centerX - num.x;
                    const dy = centerY - num.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance > 5) {
                        // Enhanced zigzag with dual frequencies
                        const primaryWave = Math.sin(time) * baseAmplitude;
                        const secondaryWave = Math.sin(time * 2.5) * secondaryAmplitude;
                        
                        // Calculate perpendicular vectors for more complex movement
                        const perpX = -dy / distance;
                        const perpY = dx / distance;
                        
                        // Add sudden direction changes
                        const suddenChange = Math.random() < 0.02 ? (Math.random() - 0.5) * 20 : 0;
                        
                        // Combine movements
                        num.x += (dx / distance) * num.velocity * 1.2; // Faster base speed
                        num.y += (dy / distance) * num.velocity * 1.2;
                        
                        // Apply complex zigzag motion
                        num.x += perpX * (primaryWave + secondaryWave + suddenChange) * 0.15;
                        num.y += perpY * (primaryWave + secondaryWave + suddenChange) * 0.15;
                        
                        // Add random bursts of speed
                        if (Math.random() < 0.01) {
                            num.x += (Math.random() - 0.5) * 15;
                            num.y += (Math.random() - 0.5) * 15;
                        }
                    }
                },
                
                spiral: (num) => {
                    const time = Date.now() * 0.003;
                    const distanceToCenter = Math.sqrt(
                        Math.pow(centerX - num.x, 2) + 
                        Math.pow(centerY - num.y, 2)
                    );
                    
                    // Dynamic spiral parameters
                    const baseRadius = 60 * (1 - Math.min(num.distanceTraveled/300, 0.8));
                    const spiralTightness = 0.15 + Math.sin(time * 0.5) * 0.05; // Varying spiral tightness
                    
                    // Calculate spiral movement
                    const angle = time * 4; // Faster rotation
                    const radiusModulation = baseRadius * (1 + Math.sin(time * 2) * 0.3); // Pulsing radius
                    
                    // Add elliptical distortion
                    const ellipticalFactor = 1.2 + Math.sin(time) * 0.3;
                    const xRadius = radiusModulation;
                    const yRadius = radiusModulation * ellipticalFactor;
                    
                    // Calculate new position with spiral and elliptical motion
                    const spiralX = Math.cos(angle) * xRadius * spiralTightness;
                    const spiralY = Math.sin(angle) * yRadius * spiralTightness;
                    
                    // Add movement toward center with varying speed
                    const dx = centerX - num.x;
                    const dy = centerY - num.y;
                    const centerPull = 0.02 + Math.sin(time * 3) * 0.01; // Varying center pull
                    
                    // Combine movements with sudden direction changes
                    num.x += spiralX + dx * centerPull;
                    num.y += spiralY + dy * centerPull;
                    
                    // Add random bursts
                    if (Math.random() < 0.03) {
                        const burstIntensity = Math.random() * 20;
                        const burstAngle = Math.random() * Math.PI * 2;
                        num.x += Math.cos(burstAngle) * burstIntensity;
                        num.y += Math.sin(burstAngle) * burstIntensity;
                    }
                },
                
                bounce: (num) => {
                    if (!num.bounceVelocityX) {
                        const dx = centerX - num.x;
                        const dy = centerY - num.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        num.bounceVelocityX = (dx / distance) * 8; // Increased initial velocity
                        num.bounceVelocityY = (dy / distance) * 8;
                        num.lastBounce = Date.now();
                    }

                    // Enhanced gravity effect
                    const dx = centerX - num.x;
                    const dy = centerY - num.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    const gravityStrength = 0.35; // Increased gravity
                    
                    // Add time-based velocity boosts
                    const timeSinceLastBounce = Date.now() - num.lastBounce;
                    const boostFactor = 1 + (Math.sin(timeSinceLastBounce * 0.005) * 0.3);
                    
                    num.bounceVelocityX += (dx / distance) * gravityStrength * boostFactor;
                    num.bounceVelocityY += (dy / distance) * gravityStrength * boostFactor;

                    // Enhanced collision detection with other numbers
                    numbers.forEach(otherNum => {
                        if (otherNum !== num && otherNum.falling) {
                            const dx = otherNum.x - num.x;
                            const dy = otherNum.y - num.y;
                            const distance = Math.sqrt(dx * dx + dy * dy);
                            const minDistance = numberRadius * 2.2; // Slightly larger collision radius

                            if (distance < minDistance) {
                                // More energetic collision response
                                const angle = Math.atan2(dy, dx);
                                const overlap = minDistance - distance;
                                
                                // Explosive separation
                                num.x -= Math.cos(angle) * overlap * 0.7;
                                num.y -= Math.sin(angle) * overlap * 0.7;
                                
                                // More energetic velocity exchange
                                const tempVX = num.bounceVelocityX * 1.2;
                                const tempVY = num.bounceVelocityY * 1.2;
                                num.bounceVelocityX = (otherNum.bounceVelocityX || -num.bounceVelocityX) * 0.9;
                                num.bounceVelocityY = (otherNum.bounceVelocityY || -num.bounceVelocityY) * 0.9;
                                
                                if (otherNum.bounceVelocityX !== undefined) {
                                    otherNum.bounceVelocityX = tempVX;
                                    otherNum.bounceVelocityY = tempVY;
                                }
                                
                                num.lastBounce = Date.now();
                            }
                        }
                    });

                    // Apply velocities with random bursts
                    const burstChance = Math.random();
                    const burstMultiplier = burstChance < 0.02 ? 1.8 : 1; // Occasional speed bursts
                    
                    num.x += num.bounceVelocityX * burstMultiplier;
                    num.y += num.bounceVelocityY * burstMultiplier;

                    // Variable damping based on distance to center
                    const distanceToCenter = Math.sqrt(
                        Math.pow(centerX - num.x, 2) + 
                        Math.pow(centerY - num.y, 2)
                    );
                    const damping = 0.99 - (distanceToCenter / 1000); // Less damping when far from center
                    
                    num.bounceVelocityX *= damping;
                    num.bounceVelocityY *= damping;

                    // Enhanced edge bouncing
                    const padding = numberRadius * 1.2;
                    if (num.x < padding || num.x > canvas.width - padding) {
                        num.bounceVelocityX *= -1.1; // More energetic wall bounces
                        num.x = Math.max(padding, Math.min(canvas.width - padding, num.x));
                        num.lastBounce = Date.now();
                    }
                    if (num.y < padding || num.y > canvas.height - padding) {
                        num.bounceVelocityY *= -1.1;
                        num.y = Math.max(padding, Math.min(canvas.height - padding, num.y));
                        num.lastBounce = Date.now();
                    }
                },
                
                erratic: (num) => {
                    const time = Date.now() * 0.006; // Increased speed
                    const dx = centerX - num.x;
                    const dy = centerY - num.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    // Initialize chaos parameters if they don't exist
                    if (!num.chaosParams) {
                        num.chaosParams = {
                            baseFreq: Math.random() * 2 + 1,
                            phaseOffset: Math.random() * Math.PI * 2,
                            amplitude: Math.random() * 30 + 40
                        };
                    }

                    // Chaotic oscillations
                    const chaos = Math.sin(time * num.chaosParams.baseFreq + num.chaosParams.phaseOffset) * 
                                Math.cos(time * 1.5) * 
                                num.chaosParams.amplitude;

                    // Sudden direction changes
                    if (Math.random() < 0.03) { // Increased frequency of direction changes
                        num.chaosParams.baseFreq = Math.random() * 2 + 1;
                        num.chaosParams.amplitude = Math.random() * 30 + 40;
                    }

                    // Complex movement pattern
                    const spiralX = Math.cos(time * 2) * (50 + chaos);
                    const spiralY = Math.sin(time * 2) * (50 + chaos);
                    
                    // Add sudden bursts of speed
                    const burst = Math.random() < 0.02 ? 2.5 : 1;
                    
                    // Combine all movements
                    num.x += (dx / distance) * num.velocity * burst;
                    num.y += (dy / distance) * num.velocity * burst;
                    
                    num.x += (Math.cos(time * 3) * spiralX + Math.sin(time * 4) * 30) * 0.03;
                    num.y += (Math.sin(time * 3) * spiralY + Math.cos(time * 4) * 30) * 0.03;
                    
                    // Add random jitter
                    num.x += (Math.random() - 0.5) * 4;
                    num.y += (Math.random() - 0.5) * 4;

                    // Occasional teleport-like jumps
                    if (Math.random() < 0.005) {
                        const jumpDistance = 30;
                        const jumpAngle = Math.random() * Math.PI * 2;
                        num.x += Math.cos(jumpAngle) * jumpDistance;
                        num.y += Math.sin(jumpAngle) * jumpDistance;
                    }
                }
            };



            



















              
              
            ///////////////////////////////////////////// UPDATE SCORE /////////////////////////////////////////////////  
              // Update score
              function updateScore(points, clickedColor) {
                // Handle color combo first
                if (clickedColor === lastClickedColor) {
                    colorComboCount++;
                    if (colorComboCount >= 3 && colorComboMultiplier < MAX_MULTIPLIER) {
                        colorComboMultiplier = Math.min(colorComboMultiplier + MULTIPLIER_INCREMENT, MAX_MULTIPLIER);
                        colorComboCount = 0;
                        updateCanvasGlow(clickedColor);
                        handleColorMatch(clickedColor);
                        playGameSound(document.getElementById('colorMatchSound'));
                    }
                } else {
                    colorComboCount = 0;
                    colorComboMultiplier = MIN_MULTIPLIER;
                    updateCanvasGlow(null);
                }

                // Calculate score with level multiplier
                const currentMultiplier = levelMultipliers[currentLevelIndex].clickMultiplier;
                const basePoints = points * currentMultiplier;
                const calculatedPoints = Math.round(basePoints * colorComboMultiplier); // Using Math.round for nearest whole number
                score += calculatedPoints;

                // Update highest score if current score is higher
                if (score > highestLevelScore) {
                    highestLevelScore = score;
                    highestScoreLevel = currentLevelIndex;
                }

                // Update display after calculation
                document.getElementById('scoreDisplay').innerText = 'Score: ' + score;

                checkForWin();
                updateProgressBar();
                checkForLevelProgression(); // Check if the level needs to be updated
                saveGameState();

            }
        




            
            // Add the styles first
            const style = document.createElement('style');
            style.textContent = `
                #glowContainer {
                    position: absolute;
                    width: 100%;    /* Changed from fixed 500px */
                    height: 100%;   /* Changed from fixed 500px */
                    border-radius: 50%;
                    pointer-events: none;
                    z-index: -1;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }

                @keyframes glowRotate {
                    0% {
                        filter: hue-rotate(0deg);
                    }
                    100% {
                        filter: hue-rotate(360deg);
                    }
                }

                @keyframes pulseGlow {
                    0% { transform: translate(-50%, -50%) scale(1); opacity: 0.8; }
                    50% { transform: translate(-50%, -50%) scale(1.1); opacity: 0.6; }
                    100% { transform: translate(-50%, -50%) scale(1); opacity: 0.8; }
                }

                .glow-effect {
                    transition: all 0.3s ease-in-out;
                }

                .active-glow {
                    animation: pulseGlow 2s ease-in-out infinite;
                }

                .ripple-effect {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                    animation: rippleExpand 0.8s ease-out forwards;
                    pointer-events: none;
                    z-index: -1;
                    border-width: 8px;
                }

                @keyframes rippleExpand {
                    0% {
                        transform: translate(-50%, -50%) scale(1);
                        opacity: 1;
                    }
                    100% {
                        transform: translate(-50%, -50%) scale(1.8);
                        opacity: 0;
                    }
                }

                .color-match-glow {
                    transition: all 0.3s ease-in-out;
                    animation: colorMatchPulse 0.5s ease-in-out;
                }

                @keyframes colorMatchPulse {
                    0% { transform: translate(-50%, -50%) scale(1); }
                    50% { transform: translate(-50%, -50%) scale(1.05); }
                    100% { transform: translate(-50%, -50%) scale(1); }
                }

                .color-burst {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    width: 0.8%;      /* Changed from fixed 4px */
                    height: 8%;       /* Changed from fixed 40px */
                    transform-origin: 0 0;
                    animation: burstAnim 1s ease-out forwards;
                    pointer-events: none;
                    z-index: -1;
                }

                @keyframes burstAnim {
                    0% {
                        transform: rotate(0deg) translateY(0) scale(1);
                        opacity: 1;
                    }
                    100% {
                        transform: rotate(0deg) translateY(20%) scale(0);
                        opacity: 0;
                    }
                }

                .clock-wrapper.paused-grey {
                    filter: grayscale(100%);
                    transition: filter 0.3s ease;
                }

                .click-feedback {
                    position: fixed;
                    pointer-events: none;
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    transform: translate(-50%, -50%);
                    animation: clickRipple 0.5s ease-out forwards;
                    z-index: 1000;
                }

                @keyframes clickRipple {
                    0% {
                        width: 0px;
                        height: 0px;
                        background: rgba(255, 255, 255, 0.8);
                        border: 2px solid white;
                    }
                    50% {
                        width: 30px;
                        height: 30px;
                        background: rgba(255, 255, 255, 0.4);
                        border: 2px solid rgba(255, 255, 255, 0.8);
                    }
                    100% {
                        width: 40px;
                        height: 40px;
                        background: rgba(255, 255, 255, 0);
                        border: 2px solid rgba(255, 255, 255, 0);
                    }
                }
            `;
            document.head.appendChild(style);

            function updateCanvasGlow(clickedColor) {
                const glowContainer = document.getElementById('glowContainer');
                const wrapper = document.querySelector('.clock-wrapper');
                const size = wrapper.getBoundingClientRect().width;
                
                if (clickedColor) {
                    // Remove any existing glow animations
                    glowContainer.style.animation = 'none';
                    glowContainer.offsetHeight; // Trigger reflow
                    
                    // Define color variations based on the clicked color
                    let colorGlow;
                    let pulseColor;
                    switch (clickedColor) {
                        case 'red':
                            colorGlow = 'rgba(255, 0, 0, 0.8)';
                            pulseColor = 'rgba(255, 100, 100, 0.6)';
                            break;
                        case 'blue':
                            colorGlow = 'rgba(0, 100, 255, 0.8)';
                            pulseColor = 'rgba(100, 150, 255, 0.6)';
                            break;
                        case 'green':
                            colorGlow = 'rgba(0, 255, 0, 0.8)';
                            pulseColor = 'rgba(100, 255, 100, 0.6)';
                            break;
                        case 'yellow':
                            colorGlow = 'rgba(255, 255, 0, 0.8)';
                            pulseColor = 'rgba(255, 255, 100, 0.6)';
                            break;
                    }

                    // Calculate glow sizes based on container size
                    const glowSize = size * 0.1; // 10% of container size
                    
                    // Create complex multi-layered glow effect with relative sizes
                    glowContainer.style.boxShadow = `
                        0 0 ${glowSize * 0.2}px ${colorGlow},
                        0 0 ${glowSize * 0.4}px ${colorGlow},
                        0 0 ${glowSize * 0.6}px ${pulseColor},
                        0 0 ${glowSize * 0.8}px ${pulseColor},
                        0 0 ${glowSize}px ${clickedColor}
                    `;
                    
                    // Add ripple effect
                    const ripple = document.createElement('div');
                    ripple.className = 'ripple-effect';
                    ripple.style.background = `radial-gradient(circle, ${colorGlow} 0%, transparent 70%)`;
                    glowContainer.parentElement.appendChild(ripple);
                    
                    setTimeout(() => ripple.remove(), 1000);

                    glowContainer.style.animation = 'glowRotate 5s linear infinite';
                    glowContainer.classList.add('glow-effect', 'active-glow');

                    if (glowContainer.glowTimeout) {
                        clearTimeout(glowContainer.glowTimeout);
                    }

                    glowContainer.glowTimeout = setTimeout(() => {
                        glowContainer.style.boxShadow = 'none';
                        glowContainer.classList.remove('glow-effect', 'active-glow');
                        glowContainer.style.animation = 'none';
                    }, 5000);
                } else {
                    glowContainer.classList.remove('active-glow');
                    setTimeout(() => {
                        glowContainer.style.boxShadow = 'none';
                        glowContainer.classList.remove('glow-effect');
                        glowContainer.style.animation = 'none';
                    }, 300);
                }
            }

            function handleColorMatch(color) {
                const glowContainer = document.getElementById('glowContainer');
                let glowColor, accentColor;

                // Enhanced color combinations for more dramatic effect
                switch (color) {
                    case 'red':
                        glowColor = 'rgba(255, 0, 0, 0.8)';
                        accentColor = 'rgba(255, 100, 100, 0.6)';
                        break;
                    case 'blue':
                        glowColor = 'rgba(0, 100, 255, 0.8)';
                        accentColor = 'rgba(100, 150, 255, 0.6)';
                        break;
                    case 'green':
                        glowColor = 'rgba(0, 255, 0, 0.8)';
                        accentColor = 'rgba(100, 255, 100, 0.6)';
                        break;
                    case 'yellow':
                        glowColor = 'rgba(255, 255, 0, 0.8)';
                        accentColor = 'rgba(255, 255, 100, 0.6)';
                        break;
                }

                // Create intense multi-layered glow for color match
                glowContainer.style.boxShadow = `
                    0 0 15px ${glowColor},
                    0 0 30px ${glowColor},
                    0 0 45px ${accentColor},
                    0 0 60px ${accentColor},
                    0 0 75px ${color}
                `;
                
                // Add special effects for color match
                glowContainer.classList.add('color-match-glow');
                
                // Create burst effect
                const burstCount = 18;
                for (let i = 0; i < burstCount; i++) {
                    const burst = document.createElement('div');
                    burst.className = 'color-burst';
                    burst.style.background = glowColor;
                    burst.style.transform = `rotate(${(360 / burstCount) * i}deg)`;
                    glowContainer.parentElement.appendChild(burst);
                    
                    // Remove burst element after animation
                    setTimeout(() => burst.remove(), 1000);
                }

                // Create enhanced ripple effect
                const ripples = 2; // Create multiple ripples
                for (let i = 0; i < ripples; i++) {
                    const ripple = document.createElement('div');
                    ripple.className = 'ripple-effect';
                    ripple.style.border = `8px solid ${glowColor}`; // Thicker border
                    ripple.style.animationDelay = `${i * 200}ms`; // Stagger the ripples
                    glowContainer.appendChild(ripple);
                    
                    setTimeout(() => ripple.remove(), 1000 + (i * 200));
                }

                // Remove effects after delay
                setTimeout(() => {
                    glowContainer.classList.remove('color-match-glow');
                    glowContainer.style.boxShadow = 'none';
                }, 500);
            }


            
            // Social sharing setup
            function setupSocialSharing() {
                const shareScoreButton = document.getElementById('shareScoreButton');
                shareScoreButton.addEventListener('click', shareScore);
            }

            // Share score function
            async function shareScore() {
                const scoreMessage = `I scored ${score.toLocaleString()} points in Minute Mania! Think you can do better? 🎯`;
                
                try {
                    if (navigator.share) {
                        await navigator.share({
                            title: 'Minute Mania Score',
                            text: scoreMessage,
                            url: window.location.href
                        });
                    } else {
                        // Fallback to clipboard
                        await navigator.clipboard.writeText(scoreMessage);
                        showToast('Score copied to clipboard!');
                    }
                } catch (err) {
                    console.error('Error sharing:', err);
                }
            }

            // Toast notification
            function showToast(message) {
                const toast = document.createElement('div');
                toast.style.cssText = `
                    position: fixed;
                    bottom: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    background: rgba(0, 0, 0, 0.8);
                    color: white;
                    padding: 12px 24px;
                    border-radius: 25px;
                    font-family: 'Bungee', sans-serif;
                    z-index: 1000;
                `;
                toast.textContent = message;
                document.body.appendChild(toast);
                
                setTimeout(() => {
                    toast.style.opacity = '0';
                    toast.style.transition = 'opacity 0.5s ease';
                    setTimeout(() => toast.remove(), 500);
                }, 2000);
            }

            // Initialize social sharing
            window.addEventListener('load', setupSocialSharing);


                 






            //////////////////////////   SCORE CARD GENERATION FOR SHARE SCORE //////////////////////////////////
            // Function to load total daily freezes from localStorage
            function loadDailyFreezes() {
                const today = new Date().toDateString();
                const savedData = localStorage.getItem('dailyFreezes');
                if (savedData) {
                    const freezeData = JSON.parse(savedData);
                    if (freezeData.date === today) {
                        totalDailyFreezes = freezeData.total;
                    } else {
                        // Reset if it's a new day
                        totalDailyFreezes = 0;
                        saveDailyFreezes();
                    }
                }
            }

            // Function to save total daily freezes to localStorage
            function saveDailyFreezes() {
                const freezeData = {
                    date: new Date().toDateString(),
                    total: totalDailyFreezes
                };
                localStorage.setItem('dailyFreezes', JSON.stringify(freezeData));
            }

            // Text translations for different languages
            const translations = {
                en: { // English (default)
                    title: 'MINUTE MANIA',
                    points: 'POINTS',
                    level: 'LEVEL',
                    wonLine1: 'I won',
                    wonLine2: 'total Time Freezes today!'
                },
                es: { // Spanish
                    title: 'MINUTE MANIA',
                    points: 'PUNTOS',
                    level: 'NIVEL',
                    wonLine1: 'He ganado',
                    wonLine2: '¡Congelamientos de Tiempo hoy!'
                },
                fr: { // French
                    title: 'MINUTE MANIA',
                    points: 'POINTS',
                    level: 'NIVEAU',
                    wonLine1: "J'ai gagné",
                    wonLine2: "Gels du Temps aujourd'hui!"
                },
                de: { // German
                    title: 'MINUTE MANIA',
                    points: 'PUNKTE',
                    level: 'LEVEL',
                    wonLine1: 'Ich habe',
                    wonLine2: 'Zeit-Stops heute gewonnen!'
                },
                it: { // Italian
                    title: 'MINUTE MANIA',
                    points: 'PUNTI',
                    level: 'LIVELLO',
                    wonLine1: 'Ho vinto',
                    wonLine2: 'Congelamenti Temporali oggi!'
                },
                pt: { // Portuguese
                    title: 'MINUTE MANIA',
                    points: 'PONTOS',
                    level: 'NÍVEL',
                    wonLine1: 'Ganhei',
                    wonLine2: 'Congelamentos de Tempo hoje!'
                },
                ja: { // Japanese
                    title: 'MINUTE MANIA',
                    points: 'ポイント',
                    level: 'レベル',
                    wonLine1: '今日は',
                    wonLine2: '回のタイムフリーズを獲得！'
                },
                ko: { // Korean
                    title: 'MINUTE MANIA',
                    points: '포인트',
                    level: '레벨',
                    wonLine1: '오늘 획득한',
                    wonLine2: '개의 타임프리즈!'
                },
                zh: { // Chinese (Simplified)
                    title: 'MINUTE MANIA',
                    points: '分数',
                    level: '等级',
                    wonLine1: '今天获得了',
                    wonLine2: '次时间冻结！'
                }
            };
            
            
            function generateScoreCard() {
                // Get device language and find matching translations
                const userLang = navigator.language.split('-')[0]; // Get base language code
                const texts = translations[userLang] || translations.en; // Fallback to English if language not supported
                const scoreCard = document.createElement('canvas');
                const ctx = scoreCard.getContext('2d', { alpha: false }); // Optimize for non-transparent background
                
                scoreCard.width = 1200;
                scoreCard.height = 1200;
                
                // Simplified gradient background
                const bgGradient = ctx.createLinearGradient(0, 0, scoreCard.width, scoreCard.height);
                bgGradient.addColorStop(0, '#6a11cb');
                bgGradient.addColorStop(1, '#2575fc');
                ctx.fillStyle = bgGradient;
                ctx.fillRect(0, 0, scoreCard.width, scoreCard.height);

                // Add watermark score pattern
                ctx.save();
                ctx.font = '40px Bungee';
                ctx.fillStyle = 'rgba(255, 255, 255, 0.03)';
                ctx.rotate(-Math.PI / 4);

                const text = highestLevelScore.toLocaleString();
                const patternWidth = 250;
                const patternHeight = 100;

                // Calculate pattern coverage area
                const startX = -scoreCard.height;
                const startY = 0;
                const endX = scoreCard.width + scoreCard.height;
                const endY = scoreCard.height + scoreCard.width;

                // Draw pattern in batches to improve performance
                const batchSize = 5; // Process multiple cells at once
                for (let x = startX; x < endX; x += patternWidth * batchSize) {
                    for (let y = startY; y < endY; y += patternHeight * batchSize) {
                        // Draw a batch of pattern cells
                        for (let dx = 0; dx < batchSize; dx++) {
                            for (let dy = 0; dy < batchSize; dy++) {
                                const currentX = x + dx * patternWidth;
                                const currentY = y + dy * patternHeight;
                                if (currentX < endX && currentY < endY) {
                                    ctx.fillText(text, currentX, currentY);
                                }
                            }
                        }
                    }
                }
                ctx.restore();

                // Add subtle pattern overlay
                ctx.fillStyle = 'rgba(255, 255, 255, 0.03)';
                const gridSize = 20;
                const rectSize = 10;
                
                // Draw grid pattern in batches
                for (let x = 0; x < scoreCard.width; x += gridSize * batchSize) {
                    for (let y = 0; y < scoreCard.height; y += gridSize * batchSize) {
                        for (let dx = 0; dx < batchSize; dx++) {
                            for (let dy = 0; dy < batchSize; dy++) {
                                const currentX = x + dx * gridSize;
                                const currentY = y + dy * gridSize;
                                if (currentX < scoreCard.width && currentY < scoreCard.height) {
                                    ctx.fillRect(currentX, currentY, rectSize, rectSize);
                                }
                            }
                        }
                    }
                }

                // Pre-set shadow styles
                const defaultShadow = {
                    color: 'rgba(0, 0, 0, 0.4)',
                    blur: 15,
                    offsetX: 4,
                    offsetY: 4
                };

                // Apply shadow settings once
                ctx.shadowColor = defaultShadow.color;
                ctx.shadowBlur = defaultShadow.blur;
                ctx.shadowOffsetX = defaultShadow.offsetX;
                ctx.shadowOffsetY = defaultShadow.offsetY;

                // Title "MINUTE MANIA"
                ctx.font = 'bold 140px Bungee';
                ctx.textAlign = 'center';
                ctx.fillStyle = '#FFD700';
                ctx.fillText('MINUTE MANIA', scoreCard.width/2, 250);

                // Score display
                ctx.font = 'bold 300px Bungee';
                ctx.fillStyle = '#FFD700';
                ctx.fillText(highestLevelScore.toLocaleString(), scoreCard.width/2, 550);
                
                // "POINTS" text
                ctx.font = 'bold 100px Bungee';
                ctx.fillStyle = 'white';
                ctx.fillText('POINTS', scoreCard.width/2, 700);
                
                // Level display
                ctx.font = 'bold 80px Bungee';
                ctx.fillStyle = '#FFD700';
                const displayLevel = highestScoreLevel + 1;
                ctx.fillText(`LEVEL ${displayLevel}`, scoreCard.width/2, 850);
                
                // Challenge text
                ctx.font = 'bold 50px Bungee';
                ctx.fillStyle = 'white';
                ctx.fillText(`${texts.wonLine1} ${totalDailyFreezes}`, scoreCard.width/2, 980);
                ctx.fillText(texts.wonLine2, scoreCard.width/2, 1040);

                // Simple decorative elements
                addOptimizedDecorations(ctx, scoreCard.width, scoreCard.height);


                
                return scoreCard;
            }

            function addOptimizedDecorations(ctx, width, height) {
                // Draw four simple corner accents
                ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
                const cornerSize = 80;
                
                ctx.beginPath();
                // Top left
                ctx.moveTo(0, 0);
                ctx.lineTo(cornerSize, 0);
                ctx.lineTo(0, cornerSize);
                // Top right
                ctx.moveTo(width, 0);
                ctx.lineTo(width - cornerSize, 0);
                ctx.lineTo(width, cornerSize);
                // Bottom left
                ctx.moveTo(0, height);
                ctx.lineTo(cornerSize, height);
                ctx.lineTo(0, height - cornerSize);
                // Bottom right
                ctx.moveTo(width, height);
                ctx.lineTo(width - cornerSize, height);
                ctx.lineTo(width, height - cornerSize);
                
                ctx.fill();

                // Single decorative circle
                ctx.beginPath();
                ctx.arc(width/2, height/2, 400, 0, Math.PI * 2);
                ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
                ctx.lineWidth = 2;
                ctx.stroke();
            }




            // Update the share score function
            async function shareScore() {
                const scoreCard = generateScoreCard();
                const displayLevel = highestScoreLevel + 1;
                const userLang = navigator.language.split('-')[0];
                const texts = translations[userLang] || translations.en;
                const scoreMessage = `My highest score in Level ${displayLevel} was ${highestLevelScore.toLocaleString()} points in Minute Mania! Think you can do better? 🎯`;
                try {
                    // Convert canvas to blob
                    const blob = await new Promise(resolve => scoreCard.toBlob(resolve, 'image/png'));
                    const file = new File([blob], 'minute-mania-score.png', { type: 'image/png' });
                    
                    if (navigator.share && navigator.canShare({ files: [file] })) {
                        // Share with image on mobile
                        await navigator.share({
                            title: 'Minute Mania Score',
                            text: scoreMessage,
                            files: [file],
                            url: window.location.href
                        });
                    } else if (navigator.share) {
                        // Fall back to sharing without image if file sharing not supported
                        await navigator.share({
                            title: 'Minute Mania Score',
                            text: scoreMessage,
                            url: window.location.href
                        });
                    } else {
                        // Desktop fallback - download the image
                        const link = document.createElement('a');
                        link.href = scoreCard.toDataURL();
                        link.download = 'minute-mania-score.png';
                        link.click();
                        
                        // Also copy the message to clipboard
                        await navigator.clipboard.writeText(scoreMessage);
                        showToast('Score card saved and message copied to clipboard!');
                    }
                } catch (err) {
                    console.error('Error sharing:', err);
                    showToast('Unable to share score card');
                }
            }

            // Make sure fonts are loaded before generating score card
            document.fonts.ready.then(() => {
                // Fonts are loaded and ready for use in canvas
                console.log('Fonts loaded for score card generation');
            });
            
        
        



                

            ///////////////////////////////////////// NUMBER RADIUS ///////////////////////////////////////////////////
            function getNumberRadius() {
                // Check if we're on a mobile device
                if (window.innerWidth <= 480) { // Standard breakpoint for mobile devices
                    return 75; // Larger radius for mobile
                }
                return 40; // Default radius for desktop/laptop
            }

            // Add resize listener to update numberRadius when screen size changes
            window.addEventListener('resize', () => {
                numberRadius = getNumberRadius();
                // Redraw if necessary
                if (gameActive && !isPaused) {
                    drawNumbers();
                }
            });








            
        
        
        













             ///////////////////////////////////////Click Event//////////////////////////////////////////////
            // Adjust Canvas Click Event for Scaled Canvas
            function adjustCanvasClickEvent(canvas) {
                gameCanvas.addEventListener('click', throttle(function(event) {
                    if (isPaused && !isAngryPause) {
                        // Only allow central circle clicks during regular pause if it's clickable
                        const rect = gameCanvas.getBoundingClientRect();
                        const scaleX = gameCanvas.width / rect.width;
                        const scaleY = gameCanvas.height / rect.height;
                        const clickX = (event.clientX - rect.left) * scaleX;
                        const clickY = (event.clientY - rect.top) * scaleY;
                        const distanceToCenter = Math.hypot(clickX - centerX, clickY - centerY);
                        
                        if (distanceToCenter <= 30 && centralCircleClickable) {
                            clearTimeout(centralCircleTimeout);
                            centralCircleColor = 'black';
                            centralCircleClickable = false;
                            score += 25000;
                            document.getElementById('scoreDisplay').innerText = 'Score: ' + score;
                            drawClock();
                            playGameSound(document.getElementById('centerCircleSound'));
                        }
                        return; // Exit early if game is paused
                    }
                    
                    
                    if (!isPaused && gameActive) {
                        addClickFeedback(event);
                    }
                    if (gameState.isPaused) return; // Allow clicks even if the game is inactive due to strikes

                    // First check if we're in an angry number pause state
                    if (isAngryPause) return; // Prevent any clicks during angry number pauses
                    
                    // Rest of the existing click handler code remains the same...
                    if (gameState.isPaused && !isAngryPause) return; 

                    const rect = gameCanvas.getBoundingClientRect();
                    const scaleX = gameCanvas.width / rect.width;
                    const scaleY = gameCanvas.height / rect.height;

                    // Calculate the actual click position in canvas coordinates
                    const clickX = (event.clientX - rect.left) * scaleX;
                    const clickY = (event.clientY - rect.top) * scaleY;

                    // Check central circle click
                    const distanceToCenter = Math.hypot(clickX - centerX, clickY - centerY);
                    if (distanceToCenter <= 30 && centralCircleClickable) {
                        clearTimeout(centralCircleTimeout);
                        centralCircleColor = 'black';
                        centralCircleClickable = false;
                        score += 25000;
                        document.getElementById('scoreDisplay').innerText = 'Score: ' + score;
                        drawClock();
                        playGameSound(document.getElementById('centerCircleSound'));
                        return;
                    }

                    // Handle frozen state
                    if (isFrozen) {
                        let clickedFrozenNumber = false;
                        let remainingFrozenNumbers = false;

                        numbers.forEach(num => {
                            if (num.falling && num.originalVelocity !== undefined) { // Check if it's a frozen falling number
                                const distance = Math.hypot(clickX - num.x, clickY - num.y);
                                if (distance < numberRadius) {
                                    clickedFrozenNumber = true;
                                    playGameSound(document.getElementById('numberclickSound')); 
                                    updateScore(num.value, num.color);
                                    num.falling = false;
                                    num.x = centerX + clockRadius * Math.cos(num.angle);
                                    num.y = centerY + clockRadius * Math.sin(num.angle);
                                    delete num.originalVelocity;
                                    delete num.originalCurrentVelocity;
                                    delete num.originalJukeTiming;
                                } else {
                                    remainingFrozenNumbers = true;
                                }
                            }
                        });

                        // Only unfreeze if we clicked a frozen number AND there are no remaining frozen numbers
                        if (clickedFrozenNumber && !remainingFrozenNumbers) {
                            unfreezeNumbers();
                        }
                        return;
                    }

                    let numberClicked = false;
                    const currentNumberRadius = getNumberRadius();
                    numbers.forEach(num => {
                        const distance = Math.hypot(clickX - num.x, clickY - num.y);
                        if (distance < currentNumberRadius && num.falling) {
                            numberClicked = true;

                            if (num.isBoosted) {
                                // Handle boosted number click
                                num.isBoosted = false;
                                isBoostActive = false;
                                boostedNumber = null;
                                score += levelMultipliers[currentLevelIndex].boostPoints;
                                updateScoreDisplay();
                                updateProgressBar();
                                checkForWin();
                                checkForLevelProgression();
                                playGameSound(document.getElementById('numberclickSound'));
                                boostButton.disabled = false;
                            } else {
                                // Handle regular number click
                                playGameSound(document.getElementById('numberclickSound'));
                                if (lastClickedColor !== num.color) {
                                    updateCanvasGlow(num.color);
                                    lastClickedColor = num.color;
                                } else {
                                    updateCanvasGlow(null);
                                }
                            }

                            // Reset number position
                            num.falling = false;
                            num.x = centerX + clockRadius * Math.cos(num.angle);
                            num.y = centerY + clockRadius * Math.sin(num.angle);
                            updateScore(num.value, num.color);

                            // **Increment clickCount for every falling number click** // ONLY A 10% CHANCE OF ANGRY SEQUENCE HAPPENING
                            if (persistentAngerState !== 'breakdown') {
                                clickCount++;
                                console.log("Falling number clicked. ClickCount:", clickCount);

                                if (!personalityNumberActive) {
                                    // Log current click count
                                    console.log("Current click count:", clickCount);
                                    
                                    // Check if current click count matches any trigger number
                                    const validTriggers = possibleTriggerClicks.filter(trigger => clickCount === trigger);
                                    
                                    if (validTriggers.length > 0) {
                                        // Add random chance (10% chance to trigger)
                                        const randomChance = Math.random();
                                        if (randomChance < 0.10) {  // 10% chance
                                            console.log("Triggering personality at click count:", clickCount);
                                            personalityNumberActive = true;
                                            const fallingNumbers = numbers.filter(n => n.falling);
                                            if (fallingNumbers.length > 0) {
                                                chosenNumber = fallingNumbers[Math.floor(Math.random() * fallingNumbers.length)];
                                                persistentAngryValue = chosenNumber.value;
                                                activateNormalPhase();
                                            }
                                        }
                                    }
                                }
                            }
                            
                            // If we already have a chosen number with eyes, handle additional clicks
                            if (num === chosenNumber) {
                                if (persistentAngerState === 'normal') {
                                    activateAngryNumber();
                                } else if (persistentAngerState === 'angry') {
                                    // Third click: Mass breakdown
                                    pauseGame(true);
                                    persistentAngerState = 'breakdown';
                                    showDialog('breakdown');
                                    
                                    // Make all numbers angry
                                    numbers.forEach(otherNum => {
                                        otherNum.color = 'red';
                                        otherNum.velocity *= 1.5;
                                        otherNum.movementPattern = getRandomMovementPattern();
                                        otherNum.hasAngryEyes = true;
                                    });
                                    
                                    setTimeout(() => {
                                        if (persistentAngerState === 'breakdown') {  
                                            unpauseGame(true);
                                            addScreenShake();
                                        }
                                    }, 4000);
                                } else if (persistentAngerState === 'breakdown') {
                                    // If already in breakdown, don't allow state changes
                                    return;
                                }
                            }

                            // Handle click bonuses
                            if (clickCount % 35 === 0) {
                                const bonusPoints = [50, 80, 100, 150, 200][Math.floor(Math.random() * 5)];
                                score += bonusPoints;
                                updateScoreDisplay();
                            }
                        }
                    });
                }));
            }


        
        // Adjust this function call to pass the correct scale factor
        adjustCanvasClickEvent(canvas, scale);
        
            function adjustFallingSpeed(factor) {
                numbers.forEach(num => {
                    if (num.falling) {
                        num.velocity *= factor;
                    }
                });
            }


            function unfreezeNumbers() {
                if (!isFrozen) return;
                
                isFrozen = false;
                numbers.forEach(num => {
                    if (num.falling && num.originalVelocity !== undefined) {
                        // Restore velocities
                        num.velocity = num.originalVelocity;
                        num.currentVelocity = num.originalCurrentVelocity;

                        // Restore movement pattern if it existed
                        if (num.originalMovementPattern) {
                            num.movementPattern = num.originalMovementPattern;
                        }
                        
                        // Restore original color
                        if (num.originalColor) {
                            num.color = num.originalColor;
                        }
                        
                        // Restore juke timing if it exists
                        if (num.originalJukeTiming) {
                            const frozenDuration = Date.now() - num.jukeTiming.pausedTime;
                            num.jukeTiming = { ...num.originalJukeTiming };
                            num.jukeTiming.paused = false;
                            num.jukeTiming.elapsed = (num.jukeTiming.elapsed + frozenDuration) % num.jukeTiming.duration;
                            delete num.originalJukeTiming;
                        }
                        
                        // Clean up stored states
                        delete num.originalVelocity;
                        delete num.originalCurrentVelocity;
                        delete num.originalMovementPattern;
                        delete num.originalColor;
                        delete num.frozenAngryColor;
                    }
                });
            }

    

        
        
        
        
        
        
        
            












           




            // Function to add click feedback
            function addClickFeedback(event) {
                const feedback = document.createElement('div');
                feedback.className = 'click-feedback';
                feedback.style.left = `${event.clientX}px`;
                feedback.style.top = `${event.clientY}px`;
                document.body.appendChild(feedback);

                // Remove the element after animation completes
                feedback.addEventListener('animationend', () => {
                    feedback.remove();
                });
            }



           


    

        
        
        
        
        
            //////////////////////////////////////////////// TRACKING WINNERS OF THE GAME ///////////////////////////////////////

            // Add this function to handle game completion tracking
            async function trackGameCompletion() {
                const endTime = Date.now();
                const gameDuration = Math.floor((endTime - levelStartTime) / 1000); // Duration in seconds
                
                // Collect device information
                const deviceInfo = {
                    userAgent: navigator.userAgent,
                    screenResolution: `${window.screen.width}x${window.screen.height}`,
                    windowSize: `${window.innerWidth}x${window.innerHeight}`,
                    devicePixelRatio: window.devicePixelRatio,
                    platform: navigator.platform,
                    language: navigator.language,
                    touchSupport: 'ontouchstart' in window,
                    orientation: screen.orientation ? screen.orientation.type : 'N/A'
                };

                // Format duration for display
                const hours = Math.floor(gameDuration / 3600);
                const minutes = Math.floor((gameDuration % 3600) / 60);
                const seconds = gameDuration % 60;
                const formattedDuration = `${hours}h:${minutes}m:${seconds}s`;

                // Prepare data for submission
                const completionData = {
                    completionTime: new Date().toISOString(),
                    gameDuration: formattedDuration,
                    finalScore: score,
                    deviceInfo: JSON.stringify(deviceInfo),
                    gameVersion: '1.1.0', // Add your game version
                    completionPath: levels.map(level => level.currentTargetIndex).join('-'),
                    freezesUsed: totalDailyFreezes
                };

                try {
                    // Replace 'YOUR_FORMSPREE_ENDPOINT' with your actual Formspree endpoint
                    const response = await fetch('https://formspree.io/f/xlddpkpb', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(completionData)
                    });

                    if (!response.ok) {
                        console.error('Failed to send completion data');
                    }
                } catch (error) {
                    console.error('Error sending completion data:', error);
                }
            }
        
        
        

        
        
            






        
          
              // Game loop
              function gameLoop() {
                  if (!isPaused && gameActive) {
                      ctx.clearRect(0, 0, canvas.width, canvas.height);
                      drawClock();
                      drawNumbers();
                      updateNumbers();
                      checkForWin();
                      requestId = requestAnimationFrame(gameLoop);
                    }
                  

                  
                  
              }
              
        
            











 



            ///////////////////////////////////////////// LEVEL DATA AND NUMBERS ///////////////////////////////////////////////////////
            // Level data
                const levels = [
                    { name: 'Level 1', targets: [100], currentTargetIndex: 0 },
                    { name: 'Level 2', targets: [1000], currentTargetIndex: 0 },
                    { name: 'Level 3', targets: [10000], currentTargetIndex: 0 },
                    { name: 'Level 4', targets: [100000], currentTargetIndex: 0 },
                    { name: 'Level 5', targets: [1000000], currentTargetIndex: 0 }
                ];



            // Multiplier System
            const levelMultipliers = [
                { level: 1, clickMultiplier: 1, boostPoints: 50 },    // Level 1 (Target: 100)
                { level: 2, clickMultiplier: 8, boostPoints: 100 },   // Level 2 (Target: 1,000)
                { level: 3, clickMultiplier: 20, boostPoints: 1000 },  // Level 3 (Target: 10,000)
                { level: 4, clickMultiplier: 100, boostPoints: 10000 }, // Level 4 (Target: 100,000)
                { level: 5, clickMultiplier: 1000, boostPoints: 25000 }// Level 5 (Target: 1,000,000)
            ];


            // Function to update level and target score
            function updateLevelAndTargetScore() {
                const currentLevel = levels[currentLevelIndex];
                targetScore = currentLevel.targets[currentLevel.currentTargetIndex];
                const targetScoreDisplay = document.getElementById('targetScoreDisplay');
                
                // First, update the class based on level
                if (currentLevelIndex === 4) { // Level 5 (index 4)
                    targetScoreDisplay.classList.add('rainbow-text-level5');
                } else {
                    targetScoreDisplay.classList.remove('rainbow-text-level5');
                }
                
                // Then set the text content (after class is applied)
                targetScoreDisplay.innerText = 'Target Score: ' + targetScore;
                
                // Update the level display
                document.getElementById('levelDisplay').innerText = currentLevel.name;

                // Show BOOST button from Level 3 to Level 5
                const boostButton = document.getElementById('boostButton');
                if (currentLevelIndex >= 2 && currentLevelIndex <= 4) {
                    boostButton.style.display = 'inline-block';
                } else {
                    boostButton.style.display = 'none';
                }
                
                saveGameState();
            }


            // Call this function to initialize level and target score
            updateLevelAndTargetScore();


            //Check for Win
            function checkForWin() {
                const currentLevel = levels[currentLevelIndex];
                const targetScore = currentLevel.targets[currentLevel.currentTargetIndex];

                if (score >= targetScore) {
                    playGameSound(document.getElementById('targetscoreProgressSound'));

                    if (currentLevel.currentTargetIndex < currentLevel.targets.length - 1) {
                        // Progress to the next mini-level within the same main level
                        currentLevel.currentTargetIndex++;
                        updateLevelAndTargetScore();
                        restartGame(true);
                    } else {
                        // If the last mini-level of the current main level is completed, show LevelUpMessage
                        if (currentLevelIndex < levels.length - 1) {
                            // Move to the next main level
                            currentLevel.currentTargetIndex = 0;
                            currentLevelIndex++;
                            levels[currentLevelIndex].currentTargetIndex = 0;
                            updateLevelAndTargetScore();
                            pauseGameActivities();
                            showLevelUpMessage(); // Show LevelUpMessage on completing the final mini-level
                        } else {
                            // Game complete: All levels and mini-levels are completed
                            gameActive = false;
                            document.getElementById('winMessage').style.display = 'block'; // Display end-game message
                            trackGameCompletion();
                            return;
                        }
                    }
                }
            }
        
        
            // Update score display function (add this function to your script)
                function updateScoreDisplay() {
                    document.getElementById('scoreDisplay').innerText = 'Score: ' + score;
                }

        
        
                function showLevelUpMessage() {
                    const levelUpMessage = document.getElementById('levelUpMessage');
                    if (levelUpMessage) {
                        const nextLevelName = levels[currentLevelIndex].name;
                        levelUpMessage.innerHTML = `
                            <p>CONGRATULATIONS!<br>YOU'VE REACHED ${nextLevelName}!</p>
                            <div class="button-container">
                                <button id="nextLevelButton">Next Level</button>
                            </div>
                        `;
                        levelUpMessage.style.display = 'block';

                        // Attach event listener to the newly created button
                        document.getElementById('nextLevelButton').addEventListener('click', function() {
                            levelUpMessage.style.display = 'none';
                            restartGame();
                        });
                    } else {
                        console.error('Level up message element not found');
                    }
                }

        
    
        

        
        
        
                function checkForLevelProgression() {
                    const currentLevel = levels[currentLevelIndex];
                    let levelChanged = false;

                    if (score >= currentLevel.targets[currentLevel.currentTargetIndex]) {
                        if (currentLevel.currentTargetIndex < currentLevel.targets.length - 1) {
                            currentLevel.currentTargetIndex++;
                            levelChanged = true;
                        } else if (currentLevelIndex < levels.length - 1) {
                            currentLevelIndex++;
                            levels[currentLevelIndex].currentTargetIndex = 0;
                            levelChanged = true;
                        } else {
                            showGameCompletionMessage();
                            gameActive = false;
                            return;
                        }
                        if (levelChanged) {
                            pauseGameActivities();
                            updateLevelAndTargetScore();
                            // Pass isLevelProgression flag as true
                            restartGame(true, true);
                            isBoostActive = false;
                            boostedNumber = null;
                            const boostButton = document.getElementById('boostButton');
                            if (boostButton) {
                                boostButton.disabled = false;
                                boostButton.style.display = currentLevelIndex >= 2 && currentLevelIndex <= 4 ? 'inline-block' : 'none';
                            }
                        }
                    }
                }
        
        
        
            function pauseGameActivities() {
                gameActive = false; // Stop the game loop
                clearTimeout(centralCircleTimeout);

                if (requestId) {
                    cancelAnimationFrame(requestId); // Assuming 'requestId' is your requestAnimationFrame ID
                }

                // If you have other intervals or timeouts, clear them here as well
                // Example: clearInterval(someOtherInterval);

                // Update UI elements to reflect the paused state
                const pauseButton = document.getElementById('pauseButton');
                if (pauseButton) {
                    pauseButton.textContent = 'Resume'; // Change text to indicate game can be resumed
                }

                // Add any additional pausing logic specific to your game
                // For example, pausing animations, stopping sounds, etc.
            }
            
    
        





        
        
        
              
            function restartGame(keepFreezes = false, isLevelProgression = false) {
                
                const currentAngerState = persistentAngerState;

                if (!keepFreezes && freezesRemaining <= 0 && !isLevelProgression) {
                    // Only reset these on a full game restart
                    freezesRemaining = 0;
                    isFrozen = false;
                    personalityNumberActive = false;
                    chosenNumber = null;
                    persistentAngryValue = null;
                    persistentAngerState = 'none';
                } else {
                    // For level progression or time freeze usage, maintain the current states
                    isFrozen = false;
                }

                levelStartTime = Date.now();
                highestLevelScore = 0;
                highestScoreLevel = currentLevelIndex;
                strikes = 0;
                updateStrikesDisplay();   

                // Reset scores and game state
                score = 0;
                highestScore = 0;
                gameActive = true;
                isPaused = false;

                // Update UI
                const pauseButton = document.getElementById('pauseButton');
                if (pauseButton) {
                    pauseButton.textContent = 'Pause';
                }

                lastClickedColor = null;
                colorComboCount = 0;
                colorComboMultiplier = MIN_MULTIPLIER;
                updateCanvasGlow(null);
                updateProgressBar();

                // Reset boost variables
                isBoostActive = false;
                boostedNumber = null;
                const boostButton = document.getElementById('boostButton');
                if (boostButton) {
                    boostButton.disabled = false;
                    // Show/hide based on level
                    boostButton.style.display = currentLevelIndex >= 2 && currentLevelIndex <= 4 ? 'inline-block' : 'none';
                }
                
                // Update UI elements
                document.getElementById('scoreDisplay').innerText = 'Score: ' + score;
                document.getElementById('winMessage').style.display = 'none';
                document.getElementById('loseMessage').style.display = 'none';
                document.getElementById('pauseButton').style.display = 'inline-block';
                document.getElementById('targetScoreDisplay').innerText = 'Target Score: ' + targetScore;
                updateFreezeButton();
                updateLevelAndTargetScore();

                // Initialize numbers
                numbers.length = 0;
                initializeNumbers();

                // Restore the anger state
                persistentAngerState = currentAngerState;

                // If we're in breakdown state, apply it to all numbers
                if (persistentAngerState === 'breakdown') {
                    numbers.forEach(num => {
                        num.color = 'red';
                        num.velocity *= 1.5;
                        num.movementPattern = 'erratic';
                        num.hasAngryEyes = true;
                    });
                }
                saveGameState();
                initGame();
            }
        
            
              
        
                // Clear any existing intervals or timeouts
                //initGame(); // Restart game loop
                //updateProgressBar(); //Update Progress Bar
        
        
        
        
        
        
        


          
              // Pause button logic
              pauseButton.addEventListener('click', function() {
                  isPaused = !isPaused;
                  this.textContent = isPaused ? 'Resume' : 'Pause';
                  if (isPaused) {
                      cancelAnimationFrame(requestId);
                      updateCanvasGlow(null); // Reset glow when game is paused
                  } else {
                    initGame();
                  }
              });
        
        
             
          
          
          
          
          

          
            
        
                function saveGameState() {
                    const gameState = {
                        score: score, // Assuming 'score' is a variable holding the current score
                        level: currentLevelIndex, // Assuming 'currentLevelIndex' holds the current level index
                        // Add other game state variables you need to save
                    };

                    localStorage.setItem('gameState', JSON.stringify(gameState));
                }
        
        
                function loadGameState() {
                    const savedState = localStorage.getItem('gameState');
                    if (savedState) {
                        const gameState = JSON.parse(savedState);
                        score = gameState.score; // Restore score
                        currentLevelIndex = gameState.level; // Restore level
                        // Restore other game state variables
                        updateScoreDisplay(); // Update the UI with the loaded score
                        updateLevelAndTargetScore(); // Update the UI with the loaded level
                    }
                }



                // Place this at the end of your script, outside of other functions
                setInterval(() => {
                    // Randomly activate the central circle, for example, once every 5 to 15 seconds
                    if (Math.random() < 0.1) { // 10% chance to activate on each interval
                        activateCentralCircle();
                    }
                }, 5000); // Check every 5 seconds

              // Start the game
              initGame();
   
            });
</script>

<div id="gameOverOverlay" class="game-over-overlay"></div>
<div id="initialOverlay" class="game-over-overlay visible">
    <div id="goalText" class="goal-text">GOAL:<br>GET 1,000,000 POINTS</div>
</div>
</body>

<div id="gameOverOverlay" class="game-over-overlay"></div>
</html>