<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Infinite Craft Clone</title>
    <style>
        /* ----------------------------
           Reset and Basic Styles
        ----------------------------- */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            height: 100vh;
            background-color: var(--background-color);
            color: var(--text-color);
            overflow: hidden;
            position: relative;
            transition: background-color 0.3s, color 0.3s;
        }

        /* Light and Dark Mode Variables */
        :root {
            --background-color: #121212;
            --sidebar-color: #1e1e1e;
            --element-bg-color: #2d2d2d;
            --element-hover-bg: #6200ea;
            --text-color: #e0e0e0;
            --border-color: #333;
            --search-bg: #2c2c2c;
            --modal-bg: #1e1e1e;
            --button-bg: #6200ea;
            --button-hover-bg: #3700b3;
            --card-bg: #1e1e1e;
            --link-color: #bb86fc;
            --warning-color: #cf6679;
            --canvas-bg-color: radial-gradient(circle at center, #1e1e1e, #2c2c2c); /* Dark Mode Canvas */
            --galaxy-stars: #ffffff;
            --galaxy-nebula: #6a1b9a;
        }

        body.light-mode {
            --background-color: #f0f0f0;
            --sidebar-color: #ffffff;
            --element-bg-color: #e0e0e0;
            --element-hover-bg: #6200ea;
            --text-color: #121212;
            --border-color: #ccc;
            --search-bg: #ffffff;
            --modal-bg: #ffffff;
            --button-bg: #6200ea;
            --button-hover-bg: #3700b3;
            --card-bg: #ffffff;
            --link-color: #6200ea;
            --warning-color: #cf6679;
            --canvas-bg-color: radial-gradient(circle at center, #ffffff, #f0f0f0); /* Light Mode Canvas */
            --galaxy-stars: #000000;
            --galaxy-nebula: #ff4081;
        }

        /* ----------------------------
           Sidebar Styles (Moved to Right)
        ----------------------------- */
        #sidebar {
            width: 320px;
            background-color: var(--sidebar-color);
            padding: 20px;
            overflow-y: auto;
            border-left: 1px solid var(--border-color);
            transition: width 0.3s;
            display: flex;
            flex-direction: column;
            gap: 15px;
            position: relative;
        }
        #sidebar h2 {
            color: var(--text-color);
            text-align: center;
            font-size: 1.8em;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }
        #search-bar {
            padding: 10px 15px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            font-size: 1em;
            outline: none;
            background-color: var(--search-bg);
            color: var(--text-color);
            transition: border-color 0.3s;
        }
        #search-bar::placeholder {
            color: #b0b0b0;
        }
        #search-bar:focus {
            border-color: #6200ea;
        }
        #discoveries-counter {
            color: #b0b0b0;
            font-size: 1em;
            text-align: center;
            margin-top: 10px;
        }
        #elements-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-auto-rows: auto;
            gap: 10px;
        }
        .element {
            background-color: var(--element-bg-color);
            color: var(--text-color);
            padding: 12px 20px;
            border-radius: 8px;
            cursor: grab;
            text-align: center;
            transition: background-color 0.3s, transform 0.2s, box-shadow 0.3s, opacity 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1em;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            opacity: 1;
            animation: fadeIn 0.5s ease forwards;
        }
        .element.hidden {
            display: none;
        }
        .element:hover {
            background-color: var(--element-hover-bg);
            transform: translateY(-2px);
            box-shadow: 0 6px 10px rgba(0,0,0,0.4);
        }
        .element.newly-discovered {
            animation: highlight 2s ease;
        }
        @keyframes highlight {
            0%, 100% {
                box-shadow: 0 0 10px #03dac5;
            }
            50% {
                box-shadow: 0 0 20px #03dac5;
            }
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }

        /* ----------------------------
           Buttons Styles (Settings)
        ----------------------------- */
        .icon-button {
            position: fixed; /* Changed from absolute to fixed */
            top: 10px; /* Adjusted for actual top corner */
            left: 10px; /* Adjusted for actual left corner */
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.8em;
            color: var(--text-color);
            transition: color 0.3s;
            padding: 0; /* Removed padding */
            z-index: 1000; /* Ensured it's in front */
            /* Removed display: flex; align-items: center; justify-content: center; */
        }
        .icon-button:hover {
            color: #6200ea;
        }

        /* ----------------------------
           Game Area Styles with Enhanced Galaxy Background
        ----------------------------- */
        #game-area {
            flex: 1;
            position: relative;
            /* Enhanced Galaxy Background */
            background: radial-gradient(circle at bottom, var(--galaxy-nebula) 0%, #000000 70%);
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            transition: background-color 0.3s;
            /* Adding stars and nebula effects */
            background-image: 
                radial-gradient(2px 2px at 20% 30%, var(--galaxy-stars) 0%, transparent 80%),
                radial-gradient(1px 1px at 80% 60%, var(--galaxy-stars) 0%, transparent 80%),
                radial-gradient(1.5px 1.5px at 50% 80%, var(--galaxy-stars) 0%, transparent 80%),
                linear-gradient(45deg, rgba(255, 255, 255, 0.1) 25%, transparent 25%),
                linear-gradient(-45deg, rgba(255, 255, 255, 0.1) 25%, transparent 25%);
            background-repeat: no-repeat;
            background-size: 100% 100%, 100% 100%, 100% 100%, 50px 50px, 50px 50px;
            animation: galaxyAnimation 60s linear infinite;
        }

        @keyframes galaxyAnimation {
            from { background-position: 0 0, 0 0, 0 0, 0 0, 0 0; }
            to { background-position: 100px 100px, -100px 100px, 100px -100px, 100px 100px, -100px -100px; }
        }

        #canvas {
            width: 100%;
            height: 100%;
            background: var(--canvas-bg-color);
            border: 2px solid var(--border-color);
            border-radius: 15px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 8px 16px rgba(0,0,0,0.5);
            transition: background 0.5s ease, border-color 0.3s;
            background-size: 400% 400%;
            animation: gradientAnimation 20s ease infinite;
        }

        @keyframes gradientAnimation {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        /* ----------------------------
           Draggable Item Styles
        ----------------------------- */
        .draggable {
            position: absolute;
            padding: 10px 15px;
            background-color: #6200ea;
            color: #ffffff;
            border-radius: 50px;
            cursor: grab;
            transition: transform 0.2s, opacity 0.2s, box-shadow 0.3s;
            user-select: none;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2em;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            z-index: 1;
        }
        .draggable.dragging {
            opacity: 0.7;
            cursor: grabbing;
            transform: scale(1.05);
            box-shadow: 0 6px 10px rgba(0,0,0,0.4);
            z-index: 2;
        }

        /* ----------------------------
           Overlay for Canvas Interactions
        ----------------------------- */
        #canvas::after {
            content: '';
            position: absolute;
            width: 150%;
            height: 150%;
            top: -25%;
            left: -25%;
            background: rgba(255,255,255,0);
            pointer-events: none;
            transition: background 0.3s;
        }
        #canvas:hover::after {
            background: rgba(255,255,255, 0.05);
        }

        /* ----------------------------
           Result Modal Styles
        ----------------------------- */
        #result-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            visibility: hidden;
            opacity: 0;
            transition: opacity 0.3s, visibility 0.3s;
            z-index: 1500;
        }
        #result-content {
            background-color: var(--modal-bg);
            padding: 30px 40px;
            border-radius: 15px;
            text-align: center;
            max-width: 400px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.5);
            animation: popIn 0.3s ease-out;
        }
        @keyframes popIn {
            from { transform: scale(0.8); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        #result-content h3 {
            margin-bottom: 20px;
            color: var(--link-color);
            font-size: 1.5em;
        }
        #result-content p {
            font-size: 1.3em;
            color: var(--text-color);
            margin-bottom: 25px;
        }
        #close-modal {
            padding: 10px 20px;
            background-color: #03dac5;
            color: #1e1e1e;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            font-size: 1em;
        }
        #close-modal:hover {
            background-color: #018786;
        }

        /* ----------------------------
           Options Modal Styles
        ----------------------------- */
        #options-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.95);
            display: flex;
            align-items: center;
            justify-content: center;
            visibility: hidden;
            opacity: 0;
            transition: opacity 0.3s, visibility 0.3s;
            z-index: 1600; /* Ensures it's above the settings button */
        }
        #options-content {
            background-color: var(--modal-bg);
            padding: 30px 40px;
            border-radius: 15px;
            text-align: center;
            max-width: 400px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease-out;
        }
        #options-content h3 {
            margin-bottom: 20px;
            color: var(--link-color);
            font-size: 1.5em;
        }
        .toggle-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .toggle-label {
            font-size: 1.1em;
            color: var(--text-color);
        }
        .toggle-switch {
            position: relative;
            width: 50px;
            height: 24px;
        }
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.4s;
            border-radius: 24px;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }
        .toggle-switch input:checked + .slider {
            background-color: #6200ea;
        }
        .toggle-switch input:checked + .slider:before {
            transform: translateX(26px);
        }
        #close-options-modal {
            padding: 10px 20px;
            background-color: #03dac5;
            color: #1e1e1e;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            font-size: 1em;
        }
        #close-options-modal:hover {
            background-color: #018786;
        }

        /* ----------------------------
           Responsive Design
        ----------------------------- */
        @media (max-width: 768px) {
            #sidebar {
                width: 280px;
            }
            .element {
                padding: 10px 15px;
                font-size: 1em;
            }
            #result-content, #options-content {
                padding: 20px 25px;
            }
            #result-content h3, #options-content h3 {
                font-size: 1.3em;
            }
            #result-content p {
                font-size: 1.1em;
            }
            #close-modal, #close-options-modal {
                padding: 10px 18px;
                font-size: 0.9em;
            }
        }

        @media (max-width: 480px) {
            #sidebar {
                width: 220px;
            }
            .element {
                padding: 8px 12px;
                font-size: 0.9em;
            }
            #canvas {
                border-radius: 10px;
            }
            #elements-container {
                grid-template-columns: repeat(2, 1fr);
            }
            .icon-button {
                font-size: 1.2em;
            }
        }

    </style>
</head>
<body>

    <!-- Settings Button (Top Left Corner) -->
    <button id="settings-button" class="icon-button" aria-label="Settings">⚙</button>

    <!-- Game Area -->
    <div id="game-area">
        <div id="canvas"></div>
    </div>

    <!-- Sidebar with Elements (Moved to Right) -->
    <div id="sidebar">
        <h2>Elements</h2>
        <input type="text" id="search-bar" placeholder="Search elements...">
        <div id="elements-container">
            <!-- Elements will be dynamically added here -->
        </div>
        <div id="discoveries-counter">Discoveries: 0</div>
    </div>

    <!-- Result Modal -->
    <div id="result-modal">
        <div id="result-content">
            <h3>New Item Created!</h3>
            <p id="result-text"></p>
            <button id="close-modal">Close</button>
        </div>
    </div>

    <!-- Options Modal -->
    <div id="options-modal">
        <div id="options-content">
            <h3>Settings</h3>
            <!-- Sound Toggle -->
            <div class="toggle-container">
                <span class="toggle-label">Sound Effects</span>
                <label class="toggle-switch">
                    <input type="checkbox" id="sound-toggle" checked>
                    <span class="slider"></span>
                </label>
            </div>
            <!-- Theme Toggle -->
            <div class="toggle-container">
                <span class="toggle-label">Dark Mode</span>
                <label class="toggle-switch">
                    <input type="checkbox" id="theme-toggle">
                    <span class="slider"></span>
                </label>
            </div>
            <button id="close-options-modal">Close</button>
        </div>
    </div>

    <script>
        // ----------------------------
        // Insert Your OpenAI API Key Here
        // ----------------------------
        const apiKey = '<TRUFFLEHOG_REDACTED_OPENAI>'; // <-- Replace with your actual OpenAI API key

        // ----------------------------
        // Predefined Elements with Emojis
        // ----------------------------
        const availableElements = [
            { name: 'Fire', emoji: '🔥' },
            { name: 'Water', emoji: '💧' },
            { name: 'Wind', emoji: '💨' },
            { name: 'Earth', emoji: '🌍' }
        ];

        let draggableId = 0; // Unique ID for each draggable item
        let discoveriesCount = 0; // Counter for discoveries
        let soundEnabled = true; // Sound toggle state
        let isDarkMode = true; // Theme state

        // DOM Elements
        const sidebar = document.getElementById('sidebar');
        const elementsContainer = document.getElementById('elements-container');
        const searchBar = document.getElementById('search-bar');
        const discoveriesCounter = document.getElementById('discoveries-counter');
        const canvas = document.getElementById('canvas');
        const resultModal = document.getElementById('result-modal');
        const resultText = document.getElementById('result-text');
        const closeModalBtn = document.getElementById('close-modal');
        const settingsButton = document.getElementById('settings-button');
        const optionsModal = document.getElementById('options-modal');
        const closeOptionsModalBtn = document.getElementById('close-options-modal');
        const soundToggle = document.getElementById('sound-toggle');
        const themeToggle = document.getElementById('theme-toggle');

        // Sound Effects Integration
        const sounds = {
            dragStart: new Audio('sounds/dragStart.mp3'),     // <-- Replace with your actual path
            combine: new Audio('sounds/combine.mp3'),         // <-- Replace with your actual path
            modalOpen: new Audio('sounds/modalOpen.mp3'),     // <-- Replace with your actual path
            modalClose: new Audio('sounds/modalClose.mp3')    // <-- Replace with your actual path
        };

        // Initialize Application
        window.onload = () => {
            // Load sound preferences
            const storedSound = localStorage.getItem('sound_enabled');
            if (storedSound !== null) {
                soundEnabled = storedSound === 'true';
                soundToggle.checked = soundEnabled;
            } else {
                soundEnabled = true;
                soundToggle.checked = true;
            }

            // Load theme preferences
            const storedTheme = localStorage.getItem('theme');
            if (storedTheme) {
                isDarkMode = storedTheme === 'dark';
                applyTheme();
                themeToggle.checked = !isDarkMode; // If darkMode is true, toggle is unchecked for Light Mode
            } else {
                isDarkMode = true;
                applyTheme();
                themeToggle.checked = false;
            }

            // Load Elements into Sidebar
            loadElements();

            // Event listeners for combining elements within the canvas
            canvas.addEventListener('dragover', (e) => e.preventDefault());
            canvas.addEventListener('drop', handleDropOnCanvas);

            // Event listener for searching elements
            searchBar.addEventListener('input', handleSearch);

            // Event listeners for modals and buttons
            closeModalBtn.addEventListener('click', closeResultModal);
            settingsButton.addEventListener('click', openOptionsModal);
            closeOptionsModalBtn.addEventListener('click', closeOptionsModal);
            soundToggle.addEventListener('change', toggleSound);
            themeToggle.addEventListener('change', toggleTheme);
        };

        // Sound Management Functions
        function playSound(sound) {
            if (soundEnabled && sounds[sound]) {
                try {
                    sounds[sound].currentTime = 0;
                    sounds[sound].play();
                } catch (error) {
                    console.error('Error playing sound:', error);
                }
            }
        }

        function toggleSound() {
            soundEnabled = soundToggle.checked;
            localStorage.setItem('sound_enabled', soundEnabled);
        }

        // Theme Management Functions
        function applyTheme() {
            if (isDarkMode) {
                document.body.classList.remove('light-mode');
            } else {
                document.body.classList.add('light-mode');
            }
            localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
        }

        function toggleTheme() {
            isDarkMode = !isDarkMode;
            applyTheme();
            playSound('modalOpen'); // Optional: Play sound when theme changes
        }

        // Load Elements into Sidebar
        function loadElements() {
            availableElements.forEach(element => {
                addElementToSidebar(element);
            });
        }

        // Adds an element to the sidebar
        function addElementToSidebar(element, isNew = false) {
            if (isNew) {
                const exists = availableElements.some(el => el.name === element.name && el.emoji === element.emoji);
                if (exists) {
                    return; // Don't add duplicates
                }
            }
            const elemDiv = document.createElement('div');
            elemDiv.classList.add('element');
            if (isNew) elemDiv.classList.add('newly-discovered');
            elemDiv.setAttribute('draggable', 'true');
            elemDiv.innerHTML = `<span style="margin-right:8px;">${element.emoji}</span>${element.name}`;
            elemDiv.addEventListener('dragstart', dragStart);
            elementsContainer.appendChild(elemDiv);

            if (isNew) {
                setTimeout(() => {
                    elemDiv.classList.remove('newly-discovered');
                }, 2000); // Remove animation class after animation duration
            }
        }

        // Drag Start Handler
        function dragStart(e) {
            const data = {
                name: e.target.textContent.trim(),
                emoji: e.target.querySelector('span') ? e.target.querySelector('span').textContent.trim() : ''
            };
            e.dataTransfer.setData('application/json', JSON.stringify(data));
            setTimeout(() => {
                e.target.classList.add('dragging');
            }, 0);
            playSound('dragStart');
        }

        // Drag End Handler to remove dragging class
        document.addEventListener('dragend', (e) => {
            const elements = document.querySelectorAll('.dragging');
            elements.forEach(el => el.classList.remove('dragging'));
        });

        // Handle Drop on Canvas for Adding or Combining Elements
        async function handleDropOnCanvas(e) {
            e.preventDefault();
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const draggedItem = JSON.parse(data);
                const rect = canvas.getBoundingClientRect();
                const dropX = e.clientX - rect.left;
                const dropY = e.clientY - rect.top;

                // Find if there's an existing draggable under the drop position
                const elementsUnderDrop = document.elementsFromPoint(e.clientX, e.clientY);
                const target = elementsUnderDrop.find(el => el.classList && el.classList.contains('draggable') && el.parentElement === canvas);

                if (target) {
                    const targetData = JSON.parse(target.getAttribute('data-item'));
                    // Combine draggedItem and targetData
                    const elementsToCombine = [draggedItem, targetData];
                    const newItem = await combineElements(elementsToCombine);

                    if (newItem) {
                        // Parse the new item to extract emoji and name
                        const parsedItem = parseNewItem(newItem);

                        if (parsedItem) {
                            // Check if the item already exists
                            const exists = availableElements.some(el => el.name === parsedItem.name && el.emoji === parsedItem.emoji);

                            if (!exists) {
                                // Add new item to sidebar and elements list
                                addElementToSidebar(parsedItem, true);
                                availableElements.push(parsedItem);
                                discoveriesCount++;
                                updateDiscoveriesCounter();
                                // Show result modal
                                showResultModal(newItem);
                                playSound('combine');
                            }
                        }

                        // Remove the original elements from canvas
                        if (target) canvas.removeChild(target);
                        const lastDraggable = document.getElementById(`draggable-${draggableId - 1}`);
                        if (lastDraggable) canvas.removeChild(lastDraggable);
                    }
                } else {
                    // Simply place the dragged item without combining
                    createDraggableElement(`${draggedItem.emoji} ${draggedItem.name}`, dropX, dropY);
                }
            }
        }

        // Handle Search Functionality
        function handleSearch(e) {
            const query = e.target.value.toLowerCase();
            const elements = document.querySelectorAll('.element');
            elements.forEach(el => {
                const name = el.textContent.trim().toLowerCase();
                if (name.includes(query)) {
                    el.classList.remove('hidden');
                } else {
                    el.classList.add('hidden');
                }
            });
        }

        // Create Draggable Element in Canvas
        function createDraggableElement(content, x, y) {
            const draggable = document.createElement('div');
            draggable.classList.add('draggable');
            draggable.innerHTML = content;
            draggable.style.left = `${x - 40}px`; // Adjust for centering
            draggable.style.top = `${y - 20}px`;
            draggable.setAttribute('draggable', 'true');
            draggable.setAttribute('id', `draggable-${draggableId++}`);
            draggable.setAttribute('data-item', JSON.stringify({
                name: content.split(' ').slice(1).join(' '),
                emoji: content.split(' ')[0]
            }));

            // Drag Event Listeners for Combining with Other Canvas Items
            draggable.addEventListener('dragstart', (event) => {
                event.dataTransfer.setData('text/plain', event.target.id);
                setTimeout(() => {
                    draggable.classList.add('dragging');
                }, 0);
                playSound('dragStart');
            });

            draggable.addEventListener('dragend', (event) => {
                draggable.classList.remove('dragging');
                const rect = canvas.getBoundingClientRect();
                const newX = event.clientX - rect.left - 40;
                const newY = event.clientY - rect.top - 20;
                draggable.style.left = `${newX}px`;
                draggable.style.top = `${newY}px`;
            });

            canvas.appendChild(draggable);
        }

        // Close Result Modal
        function closeResultModal() {
            resultModal.style.visibility = 'hidden';
            resultModal.style.opacity = '0';
            playSound('modalClose');
        }

        // Show Result Modal
        function showResultModal(newItem) {
            resultText.textContent = newItem;
            resultModal.style.visibility = 'visible';
            resultModal.style.opacity = '1';
            playSound('modalOpen');
        }

        // Parse New Item to Extract Emoji and Name
        function parseNewItem(newItem) {
            const regex = /^([\p{Emoji_Presentation}\p{Emoji}\uFE0F]+)\s+([\p{L}\s]+)$/u;
            const match = newItem.match(regex);
            if (match) {
                return {
                    name: match[2],
                    emoji: match[1]
                };
            } else {
                console.warn('Failed to parse new item:', newItem);
                return null;
            }
        }

        // Update Discoveries Counter
        function updateDiscoveriesCounter() {
            discoveriesCounter.textContent = `Discoveries: ${discoveriesCount}`;
        }

        // Attempt to Combine Elements by Calling OpenAI API
        async function combineElements(elements) {
            const elementNames = elements.map(el => el.name);
            const prompt = `Combine the following elements: ${elementNames.join(', ')}. What is the resulting item? Provide just the name of the new item with an appropriate emoji, e.g., "🪨 Boulder". Keep the result simple and logical.`;

            try {
                const response = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'gpt-3.5-turbo',
                        messages: [
                            { role: 'system', content: 'You are an assistant that combines elements to create new items in a crafting system. Respond with only an emoji followed by the item name, e.g., "🪨 Boulder". Do not include any equations or additional text. Keep the result simple and logical.' },
                            { role: 'user', content: prompt }
                        ],
                        max_tokens: 15,
                        temperature: 0.3
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error.message || `API Error: ${response.status}`);
                }

                const data = await response.json();
                const newItem = data.choices[0].message.content.trim();

                // Enhanced Validation: Allow multiple emojis
                const emojiRegex = /^([\p{Emoji_Presentation}\p{Emoji}\uFE0F]+)\s+[\p{L}\s]+$/u;
                if (emojiRegex.test(newItem)) {
                    return newItem;
                } else {
                    console.warn('Generated item failed regex validation:', newItem);
                    return null;
                }

            } catch (error) {
                console.error(error);
                alert(`Error: ${error.message}`);
                return null;
            }
        }

        // Enable Combining Existing Canvas Items by Dragging One Over Another
        canvas.addEventListener('drop', async (e) => {
            e.preventDefault();
            const draggedId = e.dataTransfer.getData('text/plain');
            const draggedElement = document.getElementById(draggedId);

            if (draggedElement) {
                const rect = canvas.getBoundingClientRect();
                const dropX = e.clientX - rect.left;
                const dropY = e.clientY - rect.top;

                // Find if there's an existing draggable under the drop position
                const elementsUnderDrop = document.elementsFromPoint(e.clientX, e.clientY);
                const target = elementsUnderDrop.find(el => el.classList && el.classList.contains('draggable') && el.parentElement === canvas && el.id !== draggedId);

                if (target) {
                    const targetData = JSON.parse(target.getAttribute('data-item'));
                    const draggedData = JSON.parse(draggedElement.getAttribute('data-item'));
                    // Combine draggedData and targetData
                    const elementsToCombine = [draggedData, targetData];
                    const newItem = await combineElements(elementsToCombine);

                    if (newItem) {
                        // Parse the new item to extract emoji and name
                        const parsedItem = parseNewItem(newItem);

                        if (parsedItem) {
                            // Check if the item already exists
                            const exists = availableElements.some(el => el.name === parsedItem.name && el.emoji === parsedItem.emoji);

                            if (!exists) {
                                // Add new item to sidebar and elements list
                                addElementToSidebar(parsedItem, true);
                                availableElements.push(parsedItem);
                                discoveriesCount++;
                                updateDiscoveriesCounter();
                                // Show result modal
                                showResultModal(newItem);
                                playSound('combine');
                            }
                        }

                        // Remove the combined elements from canvas
                        if (target) canvas.removeChild(target);
                        if (draggedElement) canvas.removeChild(draggedElement);
                    }
                }
            }
        });

        // Options Modal Functions
        function openOptionsModal() {
            optionsModal.style.visibility = 'visible';
            optionsModal.style.opacity = '1';
            playSound('modalOpen');
        }

        function closeOptionsModal() {
            optionsModal.style.visibility = 'hidden';
            optionsModal.style.opacity = '0';
            playSound('modalClose');
        }

    </script>
</body>
</html>

Add sound effect when you press on an element, and when you discover one. Get the sound effects from the web.