import countries from './Countries.js';

document.addEventListener('DOMContentLoaded', () => {
    let selectedCountryCode = 'LB';
    let currentCountryIndex = 0;
    const countriesPerLoad = 15;
    let currentFilter = '';

    function populateCountryDropdown(filter = '') {
        const dropdownMenu = document.querySelector('#dropdownMenu ul');
        dropdownMenu.innerHTML = '';
        const filteredCountries = countries.filter(country =>
            country.name.toLowerCase().includes(filter.toLowerCase())
        );

        dropdownMenu.insertAdjacentHTML('beforeend', `
<li class="flex items-center">
        <img src="https://upload.wikimedia.org/wikipedia/commons/d/d4/World_Flag_%282004%29.svg" class="text-white w-6 h-6 ml-2" alt="World icon">
    <button type="button" class="p-1.5 countryOption" value="all">
        All Countries
    </button>
</li>

        `);

        const startIndex = currentCountryIndex;
        const endIndex = Math.min(currentCountryIndex + countriesPerLoad, filteredCountries.length);

        for (let i = startIndex; i < endIndex; i++) {
            const country = filteredCountries[i];
            const isActive = country.code === selectedCountryCode ? 'bg-blue-500' : '';
            const listItem = `
                <li class="flex items-center">
                    <img class="w-6 h-6 ml-2" src="${country.flagUrl}" alt="${country.name} Flag">
                    <button type="button" class="p-1.5 whitespace-nowrap countryOption ${isActive}" value="${country.code}">${country.name}</button>
                </li>`;
            dropdownMenu.insertAdjacentHTML('beforeend', listItem);
        }

        currentCountryIndex = endIndex;
    }
	
    function loadMoreCountries(filter) {
        const dropdownMenu = document.querySelector('#dropdownMenu ul');
        const filteredCountries = countries.filter(country =>
            country.name.toLowerCase().includes(filter.toLowerCase())
        );

        const startIndex = currentCountryIndex;
        const endIndex = Math.min(currentCountryIndex + countriesPerLoad, filteredCountries.length);

        for (let i = startIndex; i < endIndex; i++) {
            const country = filteredCountries[i];
            const isActive = country.code === selectedCountryCode ? 'bg-blue-500' : '';
            const listItem = `
                <li class="flex items-center">
                    <img class="w-6 h-6 ml-2" src="${country.flagUrl}" alt="${country.name} Flag">
                    <button type="button" class="p-1.5 whitespace-nowrap countryOption ${isActive}" value="${country.code}">${country.name}</button>
                </li>`;
            dropdownMenu.insertAdjacentHTML('beforeend', listItem);
        }

        currentCountryIndex = endIndex;
    }

    const dropdownMenu = document.querySelector('#dropdownMenu ul');
    dropdownMenu.addEventListener('scroll', () => {
        const scrollTop = dropdownMenu.scrollTop;
        const scrollHeight = dropdownMenu.scrollHeight;
        const clientHeight = dropdownMenu.clientHeight;

        if (scrollTop + clientHeight >= scrollHeight - 50) {
            loadMoreCountries(currentFilter);
        }
    });


document.querySelector('#dropdownMenu').addEventListener('scroll', function() {
    const dropdownMenu = document.querySelector('#dropdownMenu');
    if (dropdownMenu.scrollTop + dropdownMenu.clientHeight >= dropdownMenu.scrollHeight) {
        loadMoreCountries(currentFilter);
    }
});

document.addEventListener('click', (event) => {
    if (event.target.classList.contains('countryOption')) {
        const countryCode = event.target.value;
        updateDropdownButton(countryCode);
        document.querySelector('#dropdownMenu').classList.add('hidden');
    }
});

function updateDropdownButton(countryCode) {
    if (countryCode === 'all') {
        const worldFlagIcon = `<img src="https://upload.wikimedia.org/wikipedia/commons/d/d4/World_Flag_%282004%29.svg" class="w-5 h-5 mr-2" alt="World icon">`;
        const buttonText = `${worldFlagIcon} All <svg class="w-5 h-5 ml-2 -mr-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>`;
        document.querySelector('#dropdownButton').innerHTML = buttonText;
    } else {
        const selectedCountry = countries.find(country => country.code === countryCode);
        if (selectedCountry) {
            const flagIcon = `<img class="w-5 h-5 mr-2" src="${selectedCountry.flagUrl}" alt="${selectedCountry.name} Flag">`;
            const buttonText = `${flagIcon}${selectedCountry.code.toUpperCase()}<svg class="w-5 h-5 ml-2 -mr-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>`;
            document.querySelector('#dropdownButton').innerHTML = buttonText;
        }
    }
    selectedCountryCode = countryCode;
}


    function copyToClipboard(text) {
        const textField = document.createElement('textarea');
        textField.innerText = text;
        document.body.appendChild(textField);
        textField.select();
        document.execCommand('copy');
        textField.remove();
    }

    async function searchInAllCountries(appName, entity) {
        for (const country of countries) {
            const apiUrl = `https://itunes.apple.com/search?term=${appName}&country=${country.code}&entity=${entity}&limit=25`;
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();
                const results = data.results;
                if (results.length > 0) {
                    displayAppResults(results);
                    break;
                }
            } catch (error) {
                console.error(`Error fetching apps in ${country.name}:`, error);
            }
        }
    }

function handleFetchError(response) {
    if (!response.ok) {
        if (response.status === 403) {
            window.location.href = '/403.html';
        } else {

            console.error(`HTTP error! Status: ${response.status}`);
        }
        throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response;
}



async function fetchData(entity) {
    const appName = document.querySelector('#appNameInput').value;
    if (selectedCountryCode === 'all') {
        await searchInAllCountries(appName, entity);
    } else {
        const apiUrl = `https://itunes.apple.com/search?term=${appName}&country=${selectedCountryCode}&entity=${entity}&limit=25`;
        try {
            const response = await fetch(apiUrl);
            handleFetchError(response);
            const data = await response.json();
            const results = data.results;
            displayAppResults(results, appName); // Pass appName to displayAppResults
        } catch (error) {
            console.error('Error fetching apps:', error);
        }
    }
}

function displayAppResults(results, appName) {
    const appResultsContainer = document.querySelector('#appResults');
    appResultsContainer.innerHTML = '';

    if (results.length === 0) {
        const noResultsMessage = `
<blockquote class="p-2 my-4 border-s-4  border-red-500 bg-gray-700 text-gray-200 text-center">
    <p>We couldn't find any apps matching "<strong class="text-white p-1">${appName}</strong>".</p>
    <p>Please check the app name or try changing the country.</p>
</blockquote>



        `;
        appResultsContainer.insertAdjacentHTML('beforeend', noResultsMessage);
    } else {
        results.forEach(app => {
            const highResImageUrl = app.artworkUrl512.replace('512x512bb.jpg', '1024x1024bb.png');
            const appCard = `
                <div class="bg-gray-700 rounded-lg shadow-md p-2 flex items-center space-x-4 w-full">
                    <img class="app-icon w-16 md:w-32 lg:w-36 rounded-xl" src="${app.artworkUrl512}" alt="${app.trackName} Icon" data-high-res="${highResImageUrl}" style="cursor:pointer;">
                    <div class="flex flex-col">
                        <h4 class="text-sm md:text-lg text-white font-bold">${app.trackName}</h4>
                        <div class="flex items-center space-x-2">
                            <p class="text-xs md:text-lg font-semibold text-gray-300">${app.bundleId}</p>
                            <button class="text-xs text-gray-200 p-1 whitespace-nowrap rounded-lg focus:outline-none copyBundleId">
                                <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M16 1h-3.278A1.992 1.992 0 0 0 11 0H7a1.993 1.993 0 0 0-1.722 1H2a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2Zm-3 14H5a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2Zm0-4H5a1 1 0 0 1 0-2h8a1 1 0 1 1 0 2Zm0-5H5a1 1 0 0 1 0-2h2V2h4v2h2a1 1 0 1 1 0 2Z"/>
                                </svg>
                                Copy
                            </button>
                        </div>
                        <p class="text-xs text-gray-200">Category: ${app.primaryGenreName}</p>
                        <p class="text-xs text-gray-200"><a href="${app.sellerUrl}" target="_blank" class="text-blue-600">${app.sellerName}</a></p>
                        <p class="text-xs text-gray-300">Price: ${app.price || 'Free'}</p>
                        <a class="text-xs text-blue-600" href="${app.trackViewUrl}" target="_blank">View on App Store</a>
                    </div>
                </div>`;
            appResultsContainer.insertAdjacentHTML('beforeend', appCard);
        });

        document.querySelectorAll('.app-icon').forEach(img => {
            img.addEventListener('click', () => {
                const highResImageUrl = img.dataset.highRes;
                window.open(highResImageUrl, '_blank');
            });
        });

        document.querySelectorAll('.copyBundleId').forEach(button => {
            button.addEventListener('click', () => {
                const bundleId = button.previousElementSibling.textContent;
                copyToClipboard(bundleId);

                button.textContent = 'Copied';
                button.classList.remove('text-blue-600');
                button.classList.add('text-blue-400', 'cursor-default');

                setTimeout(() => {
                    button.textContent = 'Copy';
                    button.classList.remove('text-blue-400', 'cursor-default');
                    button.classList.add('text-blue-600');
                }, 3000);
            });
        });
    }
}



    populateCountryDropdown();
    updateDropdownButton(selectedCountryCode);

    document.addEventListener('click', (event) => {
        if (event.target.classList.contains('countryOption')) {
            const countryCode = event.target.value;
            updateDropdownButton(countryCode);
            document.querySelector('#dropdownMenu').classList.add('hidden');
        }
    });

    document.querySelector('#dropdownButton').addEventListener('click', () => {
        document.querySelector('#dropdownMenu').classList.toggle('hidden');
    });

    document.querySelector('#appSearchForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        await fetchData('software');
    });

    document.querySelector('#iphone-button').addEventListener('click', async () => {
        await fetchData('software');
    });

    document.querySelector('#ipad-button').addEventListener('click', async () => {
        await fetchData('iPadSoftware');
    });

    document.querySelector('#macbook-button').addEventListener('click', async () => {
        await fetchData('macSoftware');
    });

    document.querySelector('#countrySearchInput').addEventListener('input', (event) => {
        currentFilter = event.target.value;
        currentCountryIndex = 0;
        populateCountryDropdown(currentFilter);
    });
});

const iphoneButton = document.getElementById('iphone-button');
const ipadButton = document.getElementById('ipad-button');
const macbookButton = document.getElementById('macbook-button');

function handleButtonClick(event) {

    iphoneButton.classList.remove('active-button');
    ipadButton.classList.remove('active-button');
    macbookButton.classList.remove('active-button');


    event.target.classList.add('active-button');
}
iphoneButton.addEventListener('click', handleButtonClick);
ipadButton.addEventListener('click', handleButtonClick);
macbookButton.addEventListener('click', handleButtonClick);