document.getElementById('terrainForm').addEventListener('submit', function (event) {
    event.preventDefault();
    const terrain = document.getElementById('terrainType').value;
    const queryParams = new URLSearchParams({
        terrain: terrain,
    });
    // Insert the loading.gif before making the fetch request
    let resultSection = document.getElementById('resultSection');
    resultSection.innerHTML = '';
    let imgElement = document.createElement('img');
    imgElement.src = 'img/checking.gif';
    imgElement.style.width = '500px';
    imgElement.style.height = '500px';
    imgElement.style.display = 'block';
    imgElement.style.marginLeft = 'auto';
    imgElement.style.marginRight = 'auto';
    resultSection.appendChild(imgElement);
    setTimeout(() => {
        fetch(`${window.BASE_URL}/gameplay/encounter?${queryParams}`)
            .then((response) => {
                if (!response.ok) {
                    throw response;
                }
                return response.json(); // we only get here if there is no error
            })
            .then((json) => {
                resultSection.innerHTML = ''; // Clear previous content
                if (Object.keys(json).length === 1) { // Short version of response
                    let name = json.name !== null ? json.name : 'No Encounter';
                    console.log(name);
                    setResultImage(name);
                } else { // Long version of the response
                    if (json.name === 'android') {
                        androidResultTable(json);
                    } else {
                        setCreatureTable(json);
                    }
                }
            })
            .catch((err) => {
                err.text().then(() => {
                    imgElement.src = 'img/404.jpg';
                });
            });
        function setResultImage(name) {
            let imgElement = document.createElement('img');
            imgElement.src = 'img/' + name + ".jpg";
            console.log(imgElement.src);
            imgElement.onerror = function () {
                this.src = 'img/404.jpg';
            };
            resultSection.appendChild(imgElement);
        }
        function formatDiceMnemonic(data) {
            return Array.isArray(data) ?
                data[0] + "d" + data[1] + (data[2] === 0 ? "" : "+" + data[2]) :
                data.toString();
        }
        function formatSpeedMnemonic(data){
            return data[0] + '/' + data[1] + '/' + data[2];
        }
        function androidResultTable(data) {
            let container = document.createElement('div');
            container.className = 'container android';  // Added 'android' class
            let creatureTitle = document.createElement('h2');
            creatureTitle.textContent = data.name.toUpperCase();
            container.appendChild(creatureTitle)
            let image = document.createElement('img');
            image.src = 'img/android.jpg';
            image.onerror = () => { image.src = 'img/404.jpg' };
            image.style.width = '275px';
            image.style.height = '275px';
            container.appendChild(image);
            let description = createDescriptionSection(data);
            container.appendChild(description);
            Object.entries(data).forEach(([key, value]) => {
                if (key === 'thinker' || key === 'worker' || key === 'warrior') {
                    let typeTitle = document.createElement('h2');
                    typeTitle.textContent = key.toUpperCase(); // Display the type (worker, warrior, thinker)
                    container.appendChild(typeTitle);
                    let profile = createProfileSection(value);
                    let abilities = createAbilitiesSection(value);
                    container.appendChild(profile);
                    container.appendChild(abilities);
                }
            });
            resultSection.appendChild(container);
        }
        function createProfileSection(data) {
            let profile = document.createElement('div');
            profile.className = 'creature_profile';
            let profileHTML = `
          
Profile
       
          
              | NUMBER |  ${formatDiceMnemonic(data.number)} | 
              | MORALE |  ${formatDiceMnemonic(data.morale)} | 
              | HIT DICE |  ${formatDiceMnemonic(data['hit dice'])} | 
              | ARMOUR |  ${data.armour} | 
              | ENVIRON |  ${data.environ.join(', ')} | 
            `;
            if(data['land speed']){
                profileHTML += `| LAND SPEED |  ${formatSpeedMnemonic(data['land speed'])} | 
`;
            }
            if(data['water speed']){
                profileHTML += `| WATER SPEED |  ${formatSpeedMnemonic(data['water speed'])} | 
`;
            }
            if(data['air speed']){
                profileHTML += `| AIR SPEED |  ${formatSpeedMnemonic(data['air speed'])} | 
`;
            }
            profileHTML += '
';
            profile.innerHTML = profileHTML;
            return profile;
        }
        function createAbilitiesSection(data) {
            // Abilities section
            let abilities = document.createElement('div');
            abilities.className = 'creature_abilities';
            abilities.innerHTML = `
              Abilities
              
                  | MS |  ${formatDiceMnemonic(data.ms)} | 
                  | IN |  ${formatDiceMnemonic(data.in)} | 
                  | DX |  ${formatDiceMnemonic(data.dx)} | 
                  | CH |  ${formatDiceMnemonic(data.ch)} | 
                  | CN |  ${formatDiceMnemonic(data.cn)} | 
                  | PS |  ${formatDiceMnemonic(data.ps)} | 
              
            `;
            return abilities;
        }
        function createAttacksSection(data) {
            // Attacks section
            let attacks = document.createElement('div');
            attacks.className = 'creature_attacks';
            let attacksHTML = 'Attacks
';
            let attacksTable = '';
            for (let attack in data.attacks) {
                let mnemonic_display;
                mnemonic_display = formatDiceMnemonic(data.attacks[attack]);
                if (mnemonic_display === "0d0") {
                    mnemonic_display = 'See Description';
                }
                attacksTable += `| ${attack} | ${mnemonic_display} | 
`
            }
            attacksTable += '
';
            attacks.innerHTML = attacksHTML + attacksTable;
            return attacks
        }
        function createMutationsSection(mutarray) {
            // Mutations section
            let mutations = document.createElement('div');
            mutations.className = 'creature_mutations';
            let mutationsHTML = 'Mutations
';
            let mutationsList = mutarray.reduce((result, mutation) => result + `${mutation}`, '');
            mutationsHTML += ``;
            mutations.innerHTML = mutationsHTML
            return mutations
        }
        function createDescriptionSection(data) {
            // Description section
            let description = document.createElement('div');
            description.className = 'creature_description';
            let descriptionHTML = `
              Description
              ${data.description}
            `;
            description.innerHTML = descriptionHTML;
            return description
        }
        function setCreatureTable(data) {
            let container = document.createElement('div');
            container.className = 'container';
            // Creature ID section
            let creatureId = document.createElement('div');
            creatureId.className = 'creature_id';
            creatureId.innerHTML = `
                ${data.name.toUpperCase()}
                
            `;
            let profile = createProfileSection(data);
            let abilities = createAbilitiesSection(data);
            let attacks = createAttacksSection(data);
            let mutations = createMutationsSection(data.mutations); // Notice the data difference
            let description = createDescriptionSection(data);
            container.appendChild(creatureId);
            container.appendChild(profile);
            container.appendChild(abilities);
            container.appendChild(attacks);
            container.appendChild(mutations);
            container.appendChild(description);
            resultSection.appendChild(container);
        }
    }, 1000);
});