<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Add version numbers or timestamps to your resource URLs -->
    <script>
        // Generate a version number based on timestamp
        const version = new Date().getTime();
        
        // Function to add version to URLs
        function addVersion(url) {
            return `${url}?v=${version}`;
        }

        // Add version to all script and stylesheet tags
        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>
    
    
    
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Minute Mania</title>
    <link rel="icon" type="image/x-icon" href="mmfavicon.png">
    <link href="https://fonts.googleapis.com/css2?family=Bubblegum+Sans&display=swap" rel="stylesheet">
    <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">

    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                // Use a static version number instead of timestamp
                const VERSION = '1.0.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>
        /* 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;
        }

        /* 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.png');
            background-size: cover;
            background-position: center;
            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;
            }
        }

        /* 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;
            }
        }

       /* 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);
            }
        }

        /* 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;
        }

        /* Time trouble message */
        #timeTroubleMessage {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: clamp(30px, 8vw, 60px);
            color: red;
            font-family: 'Bungee', regular;
            text-align: center;
            white-space: nowrap;
            -webkit-text-stroke: 1px black;
            text-shadow:
                3px 3px 0px black,
                -1px -1px 0 black,
                1px -1px 0 black,
                -1px 1px 0 black,
                1px 1px 0 black;
            z-index: 200;
        }

        .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;
        }



    </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 the target score!
        </div>

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



        <!-- Time Trouble Message -->
        <div id="timeTroubleMessage" style="display: none;">TIME TROUBLE!</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"></audio>
    <audio id="targetscoreProgressSound" src="targetscoreprogression.mp3"></audio>
    <audio id="centerCircleSound" src="buttonselectsound.mp3"></audio>
    <audio id="beginButtonSound" src="numberclick.mp3"></audio>
    <audio id="colorMatchSound" src="numbercomboclick.mp3"></audio>
    <audio id="timeTroubleSound" src="timetroublesound.mp3"></audio>
    <audio id="freezeSound" src="timefreezebuttonsound.mp3"></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.png',
                    'mmfavicon.png'
                ];

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

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

                    gameState.deltaTime = timestamp - gameState.lastTime;

                    if (!isPaused && gameActive) {
                        // Clear only necessary parts of the canvas
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        
                        // Draw the game elements
                        drawClock();
                        drawNumbers();
                        updateNumbers(gameState.deltaTime);
                        checkForWin();
                        
                        // Request next frame if game is still active
                        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'
                });

                 // 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;
                const numberRadius = 55;
                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 currentTime = 60;
                let requestId;
                const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
                const numbers = [];
                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 gameStartTime = null;
                const disappearDuration = 10000; // 10 seconds
                let timeTroubleTimeout = null;
                let displayTimeTroubleMessage = false;
                let gameLostDueToTimeOut = false;
                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; 

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

            // Optimized update function with delta time
            function update(deltaTime) {
                if (!gameState.isPaused && gameState.gameActive) {
                    updateNumbers(deltaTime);
                    checkForWin();
                    updateProgressBar();
                }
            }

            // 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;
                }

                gameState.deltaTime = timestamp - gameState.lastTime;
                
                update(gameState.deltaTime);
                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);
                    }
                };
            }


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

            // 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();
                }
            });


        // Initialize game
        async function initGame() {
            try {
                // Preload all assets
                const loadPromises = [
                    ...imagesToPreload.map(src => assetManager.preloadImage(src)),
                    ...audioToPreload.map(src => assetManager.preloadAudio(src))
                ];

                await Promise.all(loadPromises);
                console.log('All assets loaded');

                // Initialize game state
                gameState.gameActive = true;
                gameState.isPaused = false;
                
                // Initialize numbers if they haven't been initialized
                if (numbers.length === 0) {
                    initializeNumbers();
                }

                // Cache static elements
                drawStaticElements();

                // Clear any existing intervals first
                if (fallingInterval) clearInterval(fallingInterval);
                if (requestId) cancelAnimationFrame(requestId);
                
                // Set up the interval for falling numbers
                fallingInterval = setInterval(() => {
                    if (!gameState.isPaused && gameState.gameActive) {
                        startFalling();
                    }
                }, 3000);

                // Start the game loop
                requestAnimationFrame(optimizedGameLoop);

                // 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;
                if (rand <= 50) {
                    // 50% chance for 1-2 freezes (slightly frustrating but common)
                    return Math.floor(Math.random() * 2) + 1;
                } else if (rand <= 85) {
                    // 35% chance for 3-5 freezes (satisfying sweet spot)
                    return Math.floor(Math.random() * 3) + 3;
                } else if (rand <= 98) {
                    // 13% chance for 6-8 freezes (exciting but not rare)
                    return Math.floor(Math.random() * 3) + 6;
                } else {
                    // 2% chance for 15 freezes (ultra-rare jackpot)
                    return 15;
                }
            }

            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
                document.getElementById('freezeSound').play();

                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
                numbers.forEach(num => {
                    if (num.falling) {
                        num.originalVelocity = num.velocity;
                        num.velocity = 0;
                    }
                });
            }

            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);
                }
            }

           
            
    

            















            
             // Adjust canvas size to maintain aspect ratio
                function resizeCanvas() {
                    const aspectRatio = 16 / 9; // Example aspect ratio
                    let newWidth = window.innerWidth;
                    let newHeight = window.innerWidth / aspectRatio;
                    if (newHeight > window.innerHeight) {
                        newHeight = window.innerHeight;
                        newWidth = newHeight * aspectRatio;
                    }
                }
                
                window.addEventListener('resize', resizeCanvas);
                
  
             
            


              
                  // Change number colors at specific intervals or conditions
                function changeNumberColors() {
                    numbers.forEach(num => {
                    if (num.isBoosted) return;
                    num.color = numberColors[Math.floor(Math.random() * numberColors.length)];
                    });
                }

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

            // Modify the game over logic to set this flag
            if (currentTime <= 0) {
                document.getElementById('loseMessage').style.display = 'block';
                gameLostDueToTimeOut = true; // Set the flag
            }

          
            // 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);
                // Simple linear scale with a minimum threshold
                return Math.max(0.5, baseSize / currentSize);
            }
            
            
            // Initialize numbers
            function initializeNumbers() {
                gameStartTime = Date.now();
                const velocityScale = getVelocityScaleFactor();
                
                for (let i = 1; i <= 12; i++) {
                    const angle = Math.PI / 6 * (i - 3);
                    const x = centerX + clockRadius * Math.cos(angle);
                    const y = centerY + clockRadius * Math.sin(angle);
                    
                    const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                    
                    numbers.push({
                        value: i,
                        x: x,
                        y: y,
                        angle: angle,
                        falling: false,
                        active: true,
                        speedIndex: 0,
                        // Set initial velocity directly in pixels per second
                        velocity: sequence[0] * velocityScale * 100, // Multiply by 100 for better control
                        distanceTraveled: 0,
                        nextChangeDistance: Math.random() * 200 + 100,
                        isFallingSpecial: false,
                        color: numberColors[Math.floor(Math.random() * numberColors.length)]
                    });
                }
            }
        
 

              
              // Call initializeNumbers after its definition
              initializeNumbers();
          
              // 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
              function drawNumbers() {
                    const currentTime = Date.now();
                    const elapsed = currentTime - gameStartTime;

                    // Handle time trouble message display
                    const timeTroubleMessage = document.getElementById('timeTroubleMessage');
                    if (elapsed > disappearDuration && elapsed <= disappearDuration + 800) {
                        timeTroubleMessage.style.display = 'block';
                        document.getElementById('timeTroubleSound').play();
                        setTimeout(() => {
                            timeTroubleMessage.style.display = 'none';
                        }, 800);
                    }

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

                    numbers.forEach(num => {
                        if (!num.active) return;
                        
                        // Handle disappearing logic
                        if (elapsed > disappearDuration && elapsed <= disappearDuration + 10000) {
                            if ((Math.floor(elapsed / 1000) % 2 === 0) && !num.falling) {
                                return;
                            }
                        }

                        ctx.save();

                        // 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(currentTime / 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(currentTime / 200) * 0.1;
                            baseSize *= pulseScale;
                        }

                        // Draw different styles based on number state
                        if (num.isBoosted) {
                            // Boosted number effect
                            const glowIntensity = 0.5 + Math.sin(currentTime / 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 = (currentTime / 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);
                        }

                        ctx.restore();
                    });

                    // Add frozen effect
                    if (isFrozen) {
                        ctx.save();
                        numbers.forEach(num => {
                            if (num.falling && num.originalVelocity) { // Only draw effect for frozen falling numbers
                                // 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 sparkleX = num.x + Math.cos(angle) * (numberRadius * 1.2);
                                    const sparkleY = num.y + Math.sin(angle) * (numberRadius * 1.2);
                                    
                                    const sparkleGrad = ctx.createRadialGradient(
                                        sparkleX, sparkleY, 0,
                                        sparkleX, sparkleY, 4
                                    );
                                    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, 0, Math.PI * 2);
                                    ctx.fill();
                                }
                            }
                        });
                        ctx.restore();
                    }
                }


        
            


          
              // Update numbers
              function updateNumbers() {
                    if (isAnimatingChainReaction) return; // Skip updating numbers when animating

                    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 > 5) {        
                                num.x += dx / distance * num.velocity;
                                num.y += dy / distance * num.velocity;

                                // Update the distance traveled
                                num.distanceTraveled += Math.sqrt(Math.pow(dx / distance * num.velocity, 2) + Math.pow(dy / distance * num.velocity, 2));

                                // Change velocity based on distance traveled
                                if (num.distanceTraveled >= num.nextChangeDistance) {
                                    const sequence = currentLevelIndex === 4 ? level5SpeedSequence : baseSpeedSequence;
                                    num.speedIndex = Math.floor(Math.random() * sequence.length);  // Use the correct sequence length
                                    num.velocity = sequence[num.speedIndex] / 1000;
                                    num.distanceTraveled = 0;
                                    num.nextChangeDistance = Math.random() * 200 + 100;
                                }
                            } else {
                                // Number has reached the center
                                // Increment strikes
                                strikes++;
                                updateStrikesDisplay(); // Update the strikes display

                                // Check if player has 3 strikes
                                if (strikes >= 3) {
                                    gameActive = false;
                                    showLoseMessage(); // Function to display lose message and handle restart
                                }  

                                // Reset score to zero when a number reaches the center
                                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 the number was boosted, reset boost state
                                if (num.isBoosted) {
                                    num.isBoosted = false;
                                    isBoostActive = false;
                                    boostedNumber = null;
                                    boostButton.disabled = false;
                                    
                                }
                            }
                        }
                    });
                }


              function updateStrikesDisplay() {
                // Array of strike element IDs
                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');
                    } else {
                        // Ensure the strike is white if not yet a strike
                        strikeElement.classList.remove('red');
                    }
                }
            }

            function showLoseMessage() {
                // Show overlay first
                const overlay = document.getElementById('gameOverOverlay');
                overlay.classList.add('visible');
                
                // Get new freezes
                const newFreezes = getRandomTimeFreezes();
                freezesRemaining = newFreezes;
                
                // 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');
                    
                    // 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);
            }



          
              // 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];
                            
                            // Set falling state and initialize velocity
                            numberToFall.falling = true;
                            
                            // 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;
                    }
                });
            });
    

              
              // Function to trigger the chain reaction
              function triggerChainReaction() {
                  
                  // Display feedback message
                    const feedbackMessage = document.getElementById('feedbackMessage');
                    feedbackMessage.innerText = "Brilliant!"; // Update this text as needed
                    feedbackMessage.style.display = 'block';

                    // Hide the feedback message after a delay
                    setTimeout(() => {
                        feedbackMessage.style.display = 'none';
                    }, 2000); // Adjust the delay as needed

              
                  setTimeout(() => {
                      // Restore numbers to their original state after a delay
                      numbers.forEach(num => {
                          num.falling = false;
                          num.x = centerX + clockRadius * Math.cos(num.angle);
                          num.y = centerY + clockRadius * Math.sin(num.angle);
                      });
                  }, 1000); // Delay in milliseconds
              
                  score += 100; // Add 100 points for the chain reaction
                  document.getElementById('scoreDisplay').innerText = 'Score: ' + 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);
                        document.getElementById('colorMatchSound').play();
                    }
                } 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;
                    }
                }
            `;
            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 //////////////////////////////////
            // Updated generateScoreCard function using text instead of logo
            function generateScoreCard() {
                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 60px Bungee';
                ctx.fillStyle = 'white';
                ctx.fillText('Can you beat this score?', scoreCard.width/2, 1000);

                // 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();
            }

            // Make sure both fonts and image are loaded before generating score card
            Promise.all([
                document.fonts.ready,
                new Promise(resolve => {
                    if (gameLogo.complete) {
                        resolve();
                    } else {
                        gameLogo.onload = resolve;
                    }
                })
            ]).then(() => {
                console.log('Fonts and logo loaded for score card generation');
            });




            // Update the share score function
            async function shareScore() {
                const scoreCard = generateScoreCard();
                const displayLevel = highestScoreLevel + 1;
                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');
            });
            
        
        



                










            
        
        
        













             ///////////////////////////////////////Click Event//////////////////////////////////////////////
            // Adjust Canvas Click Event for Scaled Canvas
            function adjustCanvasClickEvent(canvas) {
                gameCanvas.addEventListener('click', throttle(function(event) {
                    if (gameState.isPaused || !gameState.gameActive) 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();
                        document.getElementById('centerCircleSound').play();
                        return;
                    }

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

                        numbers.forEach(num => {
                            if (num.falling && num.originalVelocity) { // Check if it's a frozen falling number
                                const distance = Math.hypot(clickX - num.x, clickY - num.y);
                                if (distance < numberRadius) {
                                    clickedFrozenNumber = true;
                                    // Play click sound
                                    document.getElementById('numberclickSound').play(); 
                                    // Handle number click
                                    updateScore(num.value, num.color);
                                    // Reset number position
                                    num.falling = false;
                                    num.x = centerX + clockRadius * Math.cos(num.angle);
                                    num.y = centerY + clockRadius * Math.sin(num.angle);
                                    delete num.originalVelocity; // Remove the frozen state from this number
                                } else {
                                    remainingFrozenNumbers = true; // There's still a frozen number that wasn't clicked
                                }
                            }
                        });

                        // If we either clicked away from frozen numbers or clicked the last frozen number
                        if (!clickedFrozenNumber || !remainingFrozenNumbers) {
                            unfreezeNumbers();
                        }
                        return;
                    }

                    let numberClicked = false;
                    numbers.forEach(num => {
                        const distance = Math.hypot(clickX - num.x, clickY - num.y);
                        if (distance < numberRadius && 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();
                                document.getElementById('numberclickSound').play();
                                boostButton.disabled = false;
                            } else {
                                // Handle regular number click
                                document.getElementById('numberclickSound').play();
                                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);

                            // Handle click count and bonuses
                            clickCount++;
                            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() {
                isFrozen = false;
                numbers.forEach(num => {
                    if (num.falling && num.originalVelocity) {
                        num.velocity = num.originalVelocity;
                        delete num.originalVelocity;
                    }
                });
            }

    

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        
        
            

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

                  
                  
              }
              
              document.getElementById('nextLevelButton').addEventListener('click', function() {
                // Hide the level up message
                document.getElementById('levelUpMessage').style.display = 'none';

                // Simply resume the game, which is already set up for the next main level
                restartGame(true);
            });
        
            











 



            ///////////////////////////////////////////// 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) {
                    document.getElementById('targetscoreProgressSound').play();

                    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
                            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;

                // Check if the player has reached the target score for the current mini-level
                if (score >= currentLevel.targets[currentLevel.currentTargetIndex]) {
                    if (currentLevel.currentTargetIndex < currentLevel.targets.length - 1) {
                        // Progress to the next mini-level within the current main level
                        currentLevel.currentTargetIndex++;
                        levelChanged = true;
                    } else {
                        // Check if there are more main levels
                        if (currentLevelIndex < levels.length - 1) {
                            // Move to the next main level
                            currentLevelIndex++;
                            levels[currentLevelIndex].currentTargetIndex = 0;
                            levelChanged = true;
                        } else {
                            // All levels are completed
                            showGameCompletionMessage();
                            gameActive = false;
                            return;
                        }
                    }
                    if (levelChanged) {
                        pauseGameActivities();
                        updateLevelAndTargetScore();
                        showLevelUpMessage();
                    } 
                }
            }
        
        
        
            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) {
                    if (!keepFreezes && freezesRemaining <= 0) {
                        freezesRemaining = 0;
                        isFrozen = false;
                    } else {
                        // If we're keeping freezes, just ensure we're not in frozen state
                        isFrozen = false;
                    }
                
                    highestLevelScore = 0; // Reset highest score
                    highestScoreLevel = currentLevelIndex;
                    strikes = 0;
                    updateStrikesDisplay();   

                    // Reset the game state
                    score = 0;
                    highestScore = 0; // Reset the highest score
                    currentTime = 60;
                    gameActive = true;
                    isPaused = false;
                    const pauseButton = document.getElementById('pauseButton');
                    if (pauseButton) {
                        pauseButton.textContent = 'Pause'; // Reset button text to 'Pause'
                    }

                    lastClickedColor = null;
                    colorComboCount = 0;
                    colorComboMultiplier = MIN_MULTIPLIER;
                    updateCanvasGlow(null); // Reset glow when game is paused
                    saveGameState();
                    updateProgressBar(); // Ensure the progress bar resets

                    // Reset boost variables
                    isBoostActive = false;
                    boostedNumber = null;

                    
                    // 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(); // Update freeze button display
    

                    // Update level and target score
                    updateLevelAndTargetScore();

                
                  
                  
                  // Clear and re-initialize numbers
                    numbers.length = 0; // Clear the array
                    initializeNumbers(); // Re-initialize numbers
                  
            
                // Clear any existing intervals or timeouts
                initGame(); // Restart game loop
                updateProgressBar(); //Update Progress Bar
            }
        
        
        
        
        
        
        
        
        
        
        
            document.getElementById('restartLevelButton').addEventListener('click', function() {
                gameLostDueToTimeOut = false; // Reset the flag when the game is restarted
                restartGame(); // Existing call to restart the game
            });


          
              // 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>


</body>

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