document.addEventListener('DOMContentLoaded', function () {
    const settingsIcon = document.getElementById('settings-icon');
    const settingsForm = document.getElementById('settings-form');
    const saveApikeyButton = document.getElementById('save-apikey');
    const apikeyInput = document.getElementById('apikey-input');
    const hostInput = document.getElementById('host');
    const dropdownItems = document.querySelectorAll('#dropclick .dropdown-item');
    const helpButton = document.getElementById('info');
    const helpDiv = document.getElementById('moreinfo');
    const keyResp = document.getElementById('keyResp');
    const response = document.getElementById('response');
    const showerror = document.getElementById('showerror');
    const apiKeyStatusToggle = document.getElementById('apiKeyStatusToggle');

    settingsForm.style.display = 'none'; 
    settingsIcon.addEventListener('click', function () {
        settingsForm.style.display = settingsForm.style.display === 'none' ? 'block' : 'none';

        helpDiv.style.display = 'none'; 
        response.style.display = 'none';
        showerror.style.display = 'none';
    });

    helpDiv.style.display = 'none'; 
    helpButton.addEventListener('click', function () {
        helpDiv.style.display = helpDiv.style.display === 'none' ? 'block' : 'none';

        settingsForm.style.display = 'none';
        response.style.display = 'none';
        showerror.style.display = 'none';
        keyResp.innerHTML = '';
        updateApiKeyStatusToggle(); 
    });

    updateApiKeyStatusToggle();

    apiKeyStatusToggle.addEventListener('click', function() {
        if (localStorage.getItem('userApikey')) {
            localStorage.removeItem('userApikey');
            showAlert('API key removed successfully!', 'success');
        } 
        updateApiKeyStatusToggle(); 
    });

    function updateApiKeyStatusToggle() {
        if (localStorage.getItem('userApikey')) {
            apiKeyStatusToggle.innerHTML = `
                <a href="#"><span class="me-1">Key Active</span> 
                <img src="images/trash.svg" alt="Check" width="12" height="12" class="icon-white"></a>
            `;
            apiKeyStatusToggle.className = '';
            apiKeyStatusToggle.classList.add('badge', 'border', 'border-light', 'muted-border', 'text-muted', 'border-1');
        } else {
            apiKeyStatusToggle.innerHTML = '';
            apiKeyStatusToggle.className = '';
        }
    }



    const copyButton = document.getElementById('copyButton');
    const copyIconImg = document.createElement('img');
    copyIconImg.src = 'images/clipboard.svg'; 
    copyIconImg.alt = 'Copy'; 
    copyIconImg.width = 16; 
    copyIconImg.height = 16;
    copyIconImg.classList.add('icon-white');

    const checkIconImg = document.createElement('img');
    checkIconImg.src = 'images/check.svg';
    checkIconImg.alt = 'Check';
    checkIconImg.width = 16;
    checkIconImg.height = 16;
    checkIconImg.classList.add('icon-white');

    copyButton.appendChild(copyIconImg); 

    copyButton.addEventListener('click', function() {
        const contentText = content.textContent;
        navigator.clipboard.writeText(contentText).then(function() {
            copyButton.innerHTML = '';
            copyButton.appendChild(checkIconImg);
            copyButton.classList.add('text-success');
            
            setTimeout(function() {
                copyButton.innerHTML = '';
                copyButton.appendChild(copyIconImg);
                copyButton.classList.remove('text-success');
            }, 2000);
        }).catch(function(err) {
            console.error('Failed to copy text: ', err);
        });
    });

    saveApikeyButton.addEventListener('click', function () {
        const apikey = apikeyInput.value.trim();
        if (validateApiKey(apikey)) {
            const encodedApikey = btoa(apikey);
            localStorage.setItem('userApikey', encodedApikey);
            showAlert('API key saved successfully!', 'success');
        } else {
            showAlert('Please enter a valid API key. That does not look right.', 'danger');
        }
    });

    function validateApiKey(apikey) {
        const hexRegex = /^[0-9a-f]{80}$/i;
        return hexRegex.test(apikey);
    }

    function showAlert(message, type) {
        const wrapper = document.createElement('div');
        wrapper.innerHTML = [
            `<div class="alert alert-${type} alert-dismissible" role="alert">`,
            `   <div>${message}</div>`,
            `   <button type="button" class="btn-close custom-close" data-bs-dismiss="alert" aria-label="Close">`,
            `       <img src="images/close.svg" alt="Close" width="16" height="16" class="icon-dark">`,
            `   </button>`,
            '</div>'
        ].join('');

        keyResp.innerHTML = '';
        keyResp.append(wrapper);
    }

    function getApikey() {
        const storedKey = localStorage.getItem('userApikey');
        return storedKey ? atob(storedKey) : 'freeuser-chrome-ext31b';
    }

    function constructUrlWithApikey(endpoint) {
        const apikey = getApikey();
        return `https://api.hackertarget.com/${endpoint}&apikey=${apikey}`;
    }

    dropdownItems.forEach(function(item) {
        item.addEventListener('click', function() {
            // Hide all sections before showing the response
            settingsForm.style.display = 'none';
            helpDiv.style.display = 'none';
            response.style.display = 'none';
            showerror.style.display = 'none';

            const selectedTool = this.getAttribute('data-value');
            let host = hostInput.value.trim(); 

            // Strip 'www.' if selected tool is 'whois' and host starts with 'www.'
            if (selectedTool === 'whois' && host.startsWith('www.')) {
                host = host.substring(4);
                hostInput.value = host; 
            }
            if (host) {
                document.getElementById('pleasewait').style.display = 'block';
                const apiUrl = constructUrlWithApikey(`${selectedTool}/?q=${encodeURIComponent(host)}`);
                
                fetch(apiUrl)
                    .then(response => response.text())
                    .then(data => {
                        document.getElementById('content').textContent = data;
                        document.getElementById('pleasewait').style.display = 'none';
                        document.getElementById('response').style.display = 'block';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        document.getElementById('pleasewait').style.display = 'none';
                        document.getElementById('showerror').style.display = 'block';
                        document.getElementById('showerror').textContent = 'Failed to fetch data. Please try again later.';
                    });
            } else {
                keyResp.style.display = 'block';
                showAlert('Please enter a valid hostname or IP.', 'danger');
            }
        });
    });

    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        const tab = tabs[0];
        if (tab && tab.url) {
            try {
                const url = new URL(tab.url);
                hostInput.value = url.hostname;
            } catch (e) {
                console.error('Error parsing tab URL:', e);
            }
        }
    });

    function fetchUserIp() {
        fetch('https://api.hackertarget.com/myip/')
            .then(response => response.text())
            .then(data => {
                ipaddr.textContent = data;
            })
            .catch(error => {
                console.error('Error fetching IP address:', error);
                ipaddr.textContent = 'Unable to retrieve IP';
            });
    }

    fetchUserIp();
});
