<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokémon TCG Pack Opener</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }

        body {
            background-color: #f0f0f0;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .controls {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-bottom: 20px;
        }

        select, button {
            padding: 10px;
            font-size: 16px;
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        button {
            background-color: #ff5555;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #ff3333;
        }

        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .cards-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            padding: 20px;
        }

        .card {
            background-color: white;
            border-radius: 10px;
            padding: 10px;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            cursor: pointer;
            position: relative;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card img {
            width: 100%;
            height: auto;
            border-radius: 5px;
        }

        .card h3 {
            margin: 10px 0;
            font-size: 14px;
        }

        .card p {
            color: #666;
            font-size: 12px;
        }

        .reverse-holo-badge {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: #ffd700;
            color: #000;
            padding: 2px 5px;
            border-radius: 3px;
            font-size: 10px;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 18px;
        }

        .error {
            color: #ff0000;
            text-align: center;
            margin: 10px 0;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 90%;
            max-height: 90%;
            overflow: auto;
        }

        .modal-content img {
            max-width: 100%;
            height: auto;
        }

        .close-modal {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            color: white;
            cursor: pointer;
        }

        .pack-info {
            text-align: center;
            margin: 10px 0;
            font-size: 14px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Pokémon TCG Pack Opener</h1>
        </div>
        <div id="error" class="error"></div>
        <div class="controls">
            <select id="setSelect">
                <option value="">Select a Set</option>
            </select>
            <button id="openPack" disabled>Open Pack</button>
        </div>
        <div id="packInfo" class="pack-info"></div>
        <div id="cardsContainer" class="cards-container"></div>
    </div>

    <div id="cardModal" class="modal">
        <span class="close-modal">&times;</span>
        <div class="modal-content" id="modalContent"></div>
    </div>

    <script>
        class PokemonTCGPackOpener {
            constructor() {
                this.setSelect = document.getElementById('setSelect');
                this.openPackButton = document.getElementById('openPack');
                this.cardsContainer = document.getElementById('cardsContainer');
                this.errorElement = document.getElementById('error');
                this.packInfoElement = document.getElementById('packInfo');
                this.modal = document.getElementById('cardModal');
                this.modalContent = document.getElementById('modalContent');
                this.baseEnergyCards = null;
                
                this.init();
            }

            async init() {
                this.addEventListeners();
                await this.loadSets();
                await this.loadBaseEnergy();
            }

            async fetchData(url) {
                try {
                    const response = await fetch(url);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return await response.json();
                } catch (error) {
                    throw new Error('Failed to fetch data: ' + error.message);
                }
            }

            async loadBaseEnergy() {
                try {
                    const data = await this.fetchData(
                        'https://api.pokemontcg.io/v2/cards?q=supertype:energy subtypes:basic set.id:base1'
                    );
                    this.baseEnergyCards = data.data;
                } catch (error) {
                    console.error('Error loading base energy cards:', error);
                }
            }

            async loadSets() {
                try {
                    this.errorElement.textContent = '';
                    const data = await this.fetchData('https://api.pokemontcg.io/v2/sets');
                    
                    const sortedSets = data.data.sort((a, b) => 
                        new Date(b.releaseDate) - new Date(a.releaseDate)
                    );

                    sortedSets.forEach(set => {
                        const option = document.createElement('option');
                        option.value = set.id;
                        option.textContent = `${set.name} (${set.releaseDate})`;
                        this.setSelect.appendChild(option);
                    });
                } catch (error) {
                    this.errorElement.textContent = 'Error loading sets. Please try again.';
                    console.error('Error:', error);
                }
            }

            addEventListeners() {
                this.setSelect.addEventListener('change', () => {
                    this.openPackButton.disabled = !this.setSelect.value;
                    this.updatePackInfo();
                });

                this.openPackButton.addEventListener('click', () => this.openPack());

                document.querySelector('.close-modal').addEventListener('click', () => {
                    this.modal.classList.remove('active');
                });

                this.modal.addEventListener('click', (e) => {
                    if (e.target === this.modal) {
                        this.modal.classList.remove('active');
                    }
                });
            }

            async updatePackInfo() {
                if (!this.setSelect.value) {
                    this.packInfoElement.textContent = '';
                    return;
                }

                try {
                    const data = await this.fetchData(`https://api.pokemontcg.io/v2/sets/${this.setSelect.value}`);
                    const set = data.data;
                    this.packInfoElement.textContent = 
                        `${set.name} - Released: ${set.releaseDate} - Total Cards: ${set.total}`;
                } catch (error) {
                    console.error('Error fetching set info:', error);
                }
            }

            async openPack() {
                if (!this.setSelect.value) return;

                this.openPackButton.disabled = true;
                this.cardsContainer.innerHTML = '<div class="loading">Opening pack...</div>';
                this.errorElement.textContent = '';

                try {
                    const setCardsData = await this.fetchData(
                        `https://api.pokemontcg.io/v2/cards?q=set.id:${this.setSelect.value}`
                    );

                    if (!setCardsData.data.length) {
                        throw new Error('No cards found in this set');
                    }

                    const pack = this.generatePackContents(setCardsData.data);
                    this.displayCards(pack);
                } catch (error) {
                    this.errorElement.textContent = 'Error opening pack. Please try again.';
                    console.error('Error:', error);
                }

                this.openPackButton.disabled = false;
            }

            generatePackContents(setCards) {
    const pack = [];

    // 1. Find energy cards from the current set only
    const setEnergyCards = setCards.filter(card => 
        card.supertype === 'Energy'
    );

    // Add one energy if the set contains energy cards
    if (setEnergyCards.length > 0) {
        const randomEnergy = setEnergyCards[Math.floor(Math.random() * setEnergyCards.length)];
        pack.push(randomEnergy);
    }

    // 2. Add one rare card
    const rareCards = setCards.filter(card => 
        ['Rare', 'Rare Holo', 'Rare Ultra', 'Rare Secret'].includes(card.rarity)
    );
    if (rareCards.length > 0) {
        const randomRare = rareCards[Math.floor(Math.random() * rareCards.length)];
        pack.push(randomRare);
    }

    // 3. Add common and uncommon cards (6 commons, 3 uncommons)
    const commonCards = setCards.filter(card => 
        card.rarity === 'Common' && card.supertype !== 'Energy'
    );
    const uncommonCards = setCards.filter(card => 
        card.rarity === 'Uncommon' && card.supertype !== 'Energy'
    );

    // Add commons
    for (let i = 0; i < 6; i++) {
        if (commonCards.length > 0) {
            const randomIndex = Math.floor(Math.random() * commonCards.length);
            pack.push(commonCards[randomIndex]);
        }
    }

    // Add uncommons
    for (let i = 0; i < 3; i++) {
        if (uncommonCards.length > 0) {
            const randomIndex = Math.floor(Math.random() * uncommonCards.length);
            pack.push(uncommonCards[randomIndex]);
        }
    }

    // 4. Make one random card (excluding the rare) reverse holoa
    if (pack.length > 1) {
        const reverseHoloIndex = Math.floor(Math.random() * (pack.length - 1)) + 1;
        pack[reverseHoloIndex] = { ...pack[reverseHoloIndex], isReverseHolo: true };
    }

    return pack;
}
            displayCards(cards) {
                this.cardsContainer.innerHTML = '';
                
                cards.forEach(card => {
                    const cardElement = document.createElement('div');
                    cardElement.className = 'card';
                    
                    let cardInfo = `
                        <img src="${card.images.small}" alt="${card.name}">
                        <h3>${card.name}</h3>
                        <p>${card.set.name}</p>
                        <p>${card.supertype}${card.rarity ? ` - ${card.rarity}` : ''}</p>
                    `;

                    if (card.isReverseHolo) {
                        cardInfo += '<span class="reverse-holo-badge">Reverse Holo</span>';
                    }

                    cardElement.innerHTML = cardInfo;

                    cardElement.addEventListener('click', () => {
                        this.showCardDetails(card);
                    });

                    this.cardsContainer.appendChild(cardElement);
                });
            }

            showCardDetails(card) {
                this.modalContent.innerHTML = `
                    <img src="${card.images.large}" alt="${card.name}">
                    <h2>${card.name}</h2>
                    <p>Set: ${card.set.name}</p>
                    <p>${card.supertype}${card.rarity ? ` - ${card.rarity}` : ''}</p>
                    ${card.isReverseHolo ? '<p>Reverse Holo</p>' : ''}
                    ${card.number ? `<p>Number: ${card.number}/${card.set.printedTotal}</p>` : ''}
                    ${card.tcgplayer?.prices ? `
                        <h3>Market Prices:</h3>
                        <pre>${JSON.stringify(card.tcgplayer.prices, null, 2)}</pre>
                    ` : ''}
                `;
                this.modal.classList.add('active');
            }
        }

        // Initialize the pack opener
        new PokemonTCGPackOpener();
    </script>
</body>
</html>

Please update thi script so that for eah set it doesn't just go with the same ones, but randomly slects an energy from that set.