<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pokémon TCG Pack Opener</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            text-align: center;
            padding: 20px;
        }

        h1 {
            color: #2a75bb;
            margin-bottom: 20px;
        }

        /* Set Selection Modal Styles */
        #setModal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.8);
        }

        #setModalContent {
            background-color: #fff;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 1200px;
            border-radius: 10px;
            max-height: 80vh;
            overflow-y: auto;
        }

        #closeModal {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        #closeModal:hover,
        #closeModal:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        /* Set Grid Styles */
        #setGrid {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 15px;
        }

        .setCard {
            width: 120px;
            cursor: pointer;
            border: 2px solid transparent;
            border-radius: 8px;
            transition: transform 0.2s, border-color 0.2s;
            flex: 0 0 auto;
        }

        .setCard:hover {
            transform: scale(1.05);
            border-color: #2a75bb;
        }

        .setCard img {
            width: 100%;
            height: auto;
            border-radius: 8px;
            max-height: 180px;
            object-fit: contain;
        }

        .selectedSetInfo {
            margin: 20px 0;
        }

        #openPackButton {
            background-color: #ffcb05;
            color: #2a75bb;
            border: none;
            padding: 15px 30px;
            font-size: 18px;
            cursor: pointer;
            border-radius: 8px;
            transition: background-color 0.3s;
            margin: 10px;
        }

        #openPackButton:hover {
            background-color: #f2b807;
        }

        /* Pack Display Container */
        #packContainer {
            display: none;
            margin-top: 30px;
        }

        #packContainer h2 {
            color: #2a75bb;
            margin-bottom: 20px;
        }

        #packCards {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 15px;
        }

        .pack-card {
            width: 150px;
            display: inline-block;
            margin: 10px;
            border: 2px solid #ccc;
            border-radius: 8px;
            box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.2s;
            vertical-align: top;
            background-color: #fff;
        }

        .pack-card:hover {
            transform: scale(1.05);
            border-color: #2a75bb;
        }

        .pack-card img {
            width: 100%;
            height: auto;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            max-height: 220px;
            object-fit: contain;
        }

        .pack-card-details {
            padding: 10px;
            text-align: left;
            font-size: 14px;
            color: #333;
        }

        .loading {
            font-size: 20px;
            color: #555;
            margin-top: 20px;
        }

        .error {
            font-size: 20px;
            color: red;
            margin-top: 20px;
        }

        /* Responsive Design */
        @media (max-width: 800px) {
            .setCard {
                width: 100px;
            }

            #packContainer h2 {
                font-size: 24px;
            }

            .pack-card {
                width: 45%;
            }
        }

        @media (max-width: 500px) {
            #setModalContent {
                width: 95%;
                margin: 10% auto;
            }

            .pack-card {
                width: 100%;
            }

            .setCard {
                width: 80px;
            }
        }
    </style>
</head>
<body>

    <h1>Pokémon TCG Pack Opener</h1>
    
    <!-- Button to Open Set Selection Modal -->
    <button id="openSetModalButton" style="background-color: #2a75bb; color: #fff; border: none; padding: 10px 20px; font-size: 16px; cursor: pointer; border-radius: 5px; transition: background-color 0.3s;">
        Select a Set
    </button>

    <!-- Set Selection Modal -->
    <div id="setModal">
        <div id="setModalContent">
            <span id="closeModal">&times;</span>
            <h2>Select a Pokémon TCG Set</h2>
            <div id="setGrid">
                <!-- Dynamically populated set cards will appear here -->
            </div>
        </div>
    </div>

    <!-- Display Selected Set Info -->
    <div class="selectedSetInfo" id="selectedSetInfo">
        <h3>Selected Set: <span id="selectedSetName">None</span></h3>
    </div>

    <!-- Open Pack Button -->
    <button id="openPackButton" disabled>Open a Pokémon Pack</button>

    <!-- Pack Display Container -->
    <div id="packContainer">
        <h2>Your Pack:</h2>
        <div id="packCards"></div>
    </div>

    <!-- Status Message -->
    <div id="statusMessage"></div>

    <script>
        const openSetModalButton = document.getElementById('openSetModalButton');
        const setModal = document.getElementById('setModal');
        const closeModal = document.getElementById('closeModal');
        const setGrid = document.getElementById('setGrid');
        const selectedSetInfo = document.getElementById('selectedSetInfo');
        const selectedSetName = document.getElementById('selectedSetName');
        const openPackButton = document.getElementById('openPackButton');
        const packContainer = document.getElementById('packContainer');
        const packCards = document.getElementById('packCards');
        const statusMessage = document.getElementById('statusMessage');

        let selectedSetId = '';
        let selectedSetNameText = '';
        let rarityGroups = {}; // To store cards categorized by rarity

        // Function to Open Set Selection Modal
        function openSetModal() {
            setModal.style.display = 'block';
        }

        // Function to Close Set Selection Modal
        function closeSetModalFunc() {
            setModal.style.display = 'none';
        }

        // When the user clicks the button, open the modal 
        openSetModalButton.addEventListener('click', openSetModal);

        // When the user clicks on <span> (x), close the modal
        closeModal.addEventListener('click', closeSetModalFunc);

        // When the user clicks anywhere outside of the modal, close it
        window.addEventListener('click', function(event) {
            if (event.target == setModal) {
                setModal.style.display = 'none';
            }
        });

        // Function to Fetch All Available Sets
        async function fetchSets() {
            try {
                statusMessage.textContent = "Loading sets...";
                statusMessage.className = "loading";
                const response = await fetch('https://api.pokemontcg.io/v2/sets?pageSize=250');
                if (!response.ok) throw new Error('Failed to fetch sets.');
                const data = await response.json();
                const sets = data.data;

                // Sort sets by release date
                sets.sort((a, b) => new Date(a.releaseDate) - new Date(b.releaseDate));

                populateSetGrid(sets);
                statusMessage.textContent = "";
            } catch (error) {
                console.error(error);
                statusMessage.textContent = "Failed to load sets. Please refresh the page.";
                statusMessage.className = "error";
            }
        }

        // Function to Populate the Set Grid in Modal
        function populateSetGrid(sets) {
            sets.forEach(set => {
                const setCard = document.createElement('div');
                setCard.className = 'setCard';
                setCard.title = set.name;

                const img = document.createElement('img');
                img.src = set.images.logo || 'https://via.placeholder.com/150?text=No+Image';
                img.alt = set.name;

                // Handle Image Load Errors
                img.onerror = function() {
                    this.src = 'https://via.placeholder.com/150?text=No+Image';
                };

                // Click Event to Select Set
                setCard.addEventListener('click', function() {
                    selectedSetId = set.id;
                    selectedSetNameText = set.name;
                    selectedSetName.textContent = set.name;
                    openPackButton.disabled = false;
                    closeSetModalFunc();
                    fetchAndCategorizeCards(set.id);
                });

                setCard.appendChild(img);
                setGrid.appendChild(setCard);
            });
        }

        // Function to Fetch and Categorize Cards by Rarity and Type
        async function fetchAndCategorizeCards(setId) {
            try {
                statusMessage.textContent = "Loading cards...";
                statusMessage.className = "loading";
                packContainer.style.display = "none";
                packCards.innerHTML = "";

                const allCards = [];
                let page = 1;
                const pageSize = 250;
                let totalPages = 1;

                // Initial Fetch to determine total pages
                const initialResponse = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${setId}"&page=${page}&pageSize=${pageSize}`);
                if (!initialResponse.ok) throw new Error('Failed to fetch cards.');
                const initialData = await initialResponse.json();
                allCards.push(...initialData.data);
                totalPages = Math.ceil(initialData.totalCount / pageSize);

                // Fetch remaining pages if any
                while (page < totalPages) {
                    page++;
                    const response = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${setId}"&page=${page}&pageSize=${pageSize}`);
                    if (!response.ok) throw new Error('Failed to fetch cards.');
                    const data = await response.json();
                    allCards.push(...data.data);
                }

                // Categorize cards by rarity and type
                rarityGroups = {
                    "Rare": [],
                    "Uncommon": [],
                    "Common": [],
                    "Energy": []
                };

                allCards.forEach(card => {
                    // Check if the card is an Energy card
                    if (card.types && card.types.includes('Energy')) {
                        rarityGroups["Energy"].push(card);
                        return;
                    }

                    let rarity = card.rarity || 'Common'; // Default to 'Common' if rarity is undefined

                    // Normalize rarity values
                    const rarityLower = rarity.toLowerCase();
                    if (rarityLower.includes('ultra') || rarityLower.includes('rare')) {
                        rarity = 'Rare';
                    } else if (rarityLower.includes('uncommon')) {
                        rarity = 'Uncommon';
                    } else if (rarityLower.includes('common') || rarityLower.includes('basic')) {
                        rarity = 'Common';
                    } else {
                        // Ignore cards that don't fit into the main categories
                        return;
                    }

                    if (rarityGroups[rarity]) {
                        rarityGroups[rarity].push(card);
                    }
                });

                // Adjust pack structure based on available rarities
                determinePackStructure();

                statusMessage.textContent = "";
            } catch (error) {
                console.error(error);
                statusMessage.textContent = "Failed to load cards. Please try again.";
                statusMessage.className = "error";
            }
        }

        // Function to Determine Pack Structure based on Available Rarities
        let packStructure = {
            "Rare": 1,
            "Uncommon": 3,
            "Common": 5,
            "Energy": 5
        };

        function determinePackStructure() {
            // Ensure that energy cards are always included
            if (!rarityGroups["Energy"] || rarityGroups["Energy"].length === 0) {
                console.warn("No Energy cards found in the selected set.");
                packStructure["Energy"] = 0;
            }

            // Check and adjust other rarities if necessary
            for (const rarity in packStructure) {
                if (rarity !== "Energy" && (!rarityGroups[rarity] || rarityGroups[rarity].length < packStructure[rarity])) {
                    console.warn(`Not enough cards in rarity category: ${rarity}. Redistributing to Common.`);
                    packStructure["Common"] += packStructure[rarity];
                    delete packStructure[rarity];
                }
            }
        }

        // Function to Open a Pack
        function openPack() {
            if (!selectedSetId) {
                alert("Please select a set first.");
                return;
            }

            // Reset any previous error messages
            statusMessage.textContent = "";
            statusMessage.className = "";

            const pack = [];

            try {
                // Check if enough cards are available in each category
                for (const [rarity, count] of Object.entries(packStructure)) {
                    if (rarity === "Energy") {
                        if (rarityGroups[rarity] && rarityGroups[rarity].length >= count) {
                            const selectedCards = getRandomCards(rarityGroups[rarity], count, pack);
                            pack.push(...selectedCards);
                        } else {
                            console.warn("Not enough Energy cards available.");
                        }
                    } else {
                        if (!rarityGroups[rarity] || rarityGroups[rarity].length < count) {
                            throw new Error(`Not enough cards in rarity category: ${rarity}`);
                        }
                        const selectedCards = getRandomCards(rarityGroups[rarity], count, pack);
                        pack.push(...selectedCards);
                    }
                }

                displayPack(pack);
            } catch (error) {
                console.error(error);
                statusMessage.textContent = error.message || "Failed to open pack. Please try again.";
                statusMessage.className = "error";
            }
        }

        // Function to Get Random Unique Cards from a Category
        function getRandomCards(cardArray, count, currentPack) {
            const availableCards = cardArray.filter(card => !currentPack.some(c => c.id === card.id));
            if (availableCards.length < count) {
                throw new Error(`Not enough unique cards in category:`);
            }

            const selected = [];
            for (let i = 0; i < count; i++) {
                const randomIndex = Math.floor(Math.random() * availableCards.length);
                const card = availableCards[randomIndex];
                selected.push(card);
                availableCards.splice(randomIndex, 1);
            }
            return selected;
        }

        // Function to Display the Pack
        function displayPack(pack) {
            packCards.innerHTML = ""; // Clear previous pack
            pack.forEach(card => {
                const cardDiv = document.createElement('div');
                cardDiv.className = 'pack-card';

                const img = document.createElement('img');
                img.src = card.images.large || card.images.small || 'https://via.placeholder.com/150?text=No+Image';
                img.alt = card.name;

                // Handle Image Load Errors
                img.onerror = function() {
                    this.src = 'https://via.placeholder.com/150?text=No+Image';
                };

                const detailsDiv = document.createElement('div');
                detailsDiv.className = 'pack-card-details';
                detailsDiv.innerHTML = `
                    <strong>${card.name}</strong><br>
                    <em>${card.set.name}</em><br>
                    <strong>Rarity:</strong> ${card.rarity || 'N/A'}
                `;

                cardDiv.appendChild(img);
                cardDiv.appendChild(detailsDiv);
                packCards.appendChild(cardDiv);
            });

            packContainer.style.display = "block";
            statusMessage.textContent = "";
        }

        // Event Listener for Open Pack Button
        openPackButton.addEventListener('click', openPack);

        // Fetch Sets on Page Load
        window.onload = fetchSets;
    </script>

</body>
</html>

Please identify the problem in this code that doesn't give me energy cards in the pack and fix it please :) Love you!