<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pokémon TCG Random Card Picker</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; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            overflow: auto; /* Enable scroll if needed */
            background-color: rgba(0,0,0,0.8); /* Black w/ opacity */
        }

        #setModalContent {
            background-color: #fff;
            margin: 5% auto; /* 5% from top and centered */
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 1200px; /* Could be more or less, depending on screen size */
            border-radius: 10px;
        }

        #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;
            max-height: 70vh;
            overflow-y: auto;
        }

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

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

        .setCard img {
            width: 100%;
            height: auto;
            border-radius: 8px;
        }

        .selectedSetInfo {
            margin: 20px 0;
        }

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

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

        #cardContainer {
            display: none;
            margin-top: 30px;
        }

        #cardImage {
            width: 300px;
            height: auto;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 10px;
            margin-bottom: 15px;
        }

        .card-details {
            font-size: 18px;
            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: 600px) {
            #cardImage {
                width: 90%;
            }

            .setCard {
                width: 45%;
            }
        }
    </style>
</head>
<body>

    <h1>Pokémon TCG Random Card Picker</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>

    <!-- Pick Card Button -->
    <button id="pickButton" disabled>Pick a Pokémon Card</button>

    <!-- Card Display Container -->
    <div id="cardContainer">
        <img id="cardImage" src="" alt="Pokémon Card">
        <div class="card-details" id="cardDetails"></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 pickButton = document.getElementById('pickButton');
        const cardContainer = document.getElementById('cardContainer');
        const cardImage = document.getElementById('cardImage');
        const cardDetails = document.getElementById('cardDetails');
        const statusMessage = document.getElementById('statusMessage');

        let selectedSetId = '';
        let selectedSetNameText = '';

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

        // Function to Close Set Selection Modal
        function closeSetModal() {
            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', closeSetModal);

        // 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'); // Adjust pageSize as needed
                if (!response.ok) throw new Error('Failed to fetch sets.');
                const data = await response.json();
                const sets = data.data;

                // Sort sets by release date (optional)
                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;
                    pickButton.disabled = false;
                    closeSetModal();
                });

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

        // Function to Fetch a Random Card from Selected Set
        async function fetchRandomCard() {
            if (!selectedSetId) {
                alert("Please select a set first.");
                return;
            }

            try {
                statusMessage.textContent = "Loading card...";
                statusMessage.className = "loading";
                cardContainer.style.display = "none";
                cardDetails.innerHTML = "";
                cardImage.src = '';

                // First, get the total number of cards in the set
                const totalResponse = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${selectedSetId}"&pageSize=1`);
                if (!totalResponse.ok) throw new Error('Failed to fetch total card count.');
                const totalData = await totalResponse.json();
                const totalCards = totalData.totalCount;

                if (totalCards === 0) throw new Error("No cards found in the selected set.");

                // Determine page size and total pages
                const pageSize = 250; // Maximum allowed by API is 250
                const totalPages = Math.ceil(totalCards / pageSize);

                // Generate a random page number
                const randomPage = Math.floor(Math.random() * totalPages) + 1;

                // Fetch the random page of cards
                const cardsResponse = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${selectedSetId}"&page=${randomPage}&pageSize=${pageSize}`);
                if (!cardsResponse.ok) throw new Error('Failed to fetch cards from selected set.');
                const cardsData = await cardsResponse.json();
                const cards = cardsData.data;

                if (cards.length === 0) throw new Error("No cards found on the selected page.");

                // Select a random card from the fetched page
                const randomIndex = Math.floor(Math.random() * cards.length);
                const randomCard = cards[randomIndex];

                // Verify that the card has an image
                if (!randomCard.images || (!randomCard.images.large && !randomCard.images.small)) {
                    throw new Error("Selected card does not have an image.");
                }

                // Update the UI with card details
                cardImage.src = randomCard.images.large || randomCard.images.small;
                cardImage.alt = randomCard.name;

                // Handle image load errors
                cardImage.onerror = function() {
                    this.src = 'https://via.placeholder.com/300x420?text=Image+Not+Available';
                    this.alt = 'Image Not Available';
                };

                cardDetails.innerHTML = `
                    <strong>Name:</strong> ${randomCard.name} <br>
                    <strong>Set:</strong> ${randomCard.set.name} <br>
                    <strong>Rarity:</strong> ${randomCard.rarity || 'N/A'} <br>
                    <strong>Types:</strong> ${randomCard.types ? randomCard.types.join(', ') : 'N/A'} <br>
                    <strong>Supertype:</strong> ${randomCard.supertype || 'N/A'} <br>
                    <strong>Subtype:</strong> ${randomCard.subtypes ? randomCard.subtypes.join(', ') : 'N/A'}
                `;
                cardContainer.style.display = "block";
                statusMessage.textContent = "";
            } catch (error) {
                console.error(error);
                statusMessage.textContent = error.message || "Failed to load card. Please try again.";
                statusMessage.className = "error";
            }
        }

        // Event Listener for Pick Button
        pickButton.addEventListener('click', fetchRandomCard);

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

</body>
</html>

Please improve this script to be able to open up packs with the right amount of cards in a pack depending on the set, nd the right stuff in place. Etc, energy cards first, then normal cards, then a reverse card, and then a regular rare, or a rare card.