let interactionCount = 0;

function loadClickedProfiles() {
    const storedProfiles = localStorage.getItem('clickedProfiles');
    return storedProfiles ? JSON.parse(storedProfiles) : [];
}

function saveClickedProfiles(profiles) {
    localStorage.setItem('clickedProfiles', JSON.stringify(profiles));
}

const clickedProfiles = loadClickedProfiles(); 
interactionCount = clickedProfiles.length; 
document.getElementById("interactionCountDisplay").innerText = interactionCount;

function fetchInteractionCount() {
    fetch('/get_interaction')
        .then(response => response.json())
        .then(data => {
            if (data.interaction_count !== undefined) {
                interactionCount = data.interaction_count;
                document.getElementById("interactionCountDisplay").innerText = interactionCount;
            }
        })
        .catch(err => console.error('Erreur lors de la récupération des interactions:', err));
}

function saveInteractionCount() {
    fetch('/update_interaction', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ interaction_count: interactionCount }),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Nombre d\'interactions mis à jour:', interactionCount);
        }
    })
    .catch(err => console.error('Erreur lors de la mise à jour des interactions:', err));
}

async function run_bot(insta_username) {
    Swal.fire({
        title: 'CLIASO',
        html: `<p>Exécution du bot Instagram en arrière-plan pour ${insta_username}.....</p><p>Veuillez patienter.</p>`,
        allowOutsideClick: false,
        didOpen: async () => {
            Swal.showLoading();
            try {
                /*if (!clickedProfiles.includes(insta_username)) {
                    clickedProfiles.push(insta_username); 
                    saveClickedProfiles(clickedProfiles); 
                    
                    interactionCount++; 
                    document.getElementById("interactionCountDisplay").innerText = interactionCount;

                    saveInteractionCount();
                } else {
                    console.log(`Bot déjà lancé pour : ${insta_username}`);
                }
                */
                
                interactionCount++; 
                document.getElementById("interactionCountDisplay").innerText = interactionCount;
                saveInteractionCount();
                
                const consoleBody = document.getElementById("console-body");

                const eventSource = new EventSource(`/launch_bot?insta_username=${insta_username}`);
    
                eventSource.onmessage = (event) => {
                    const log = event.data;
    
                    consoleBody.style.backgroundColor = "rgb(31 41 55)";

                    const logElement = document.createElement("p");
                    logElement.textContent = log;
                    consoleBody.appendChild(logElement);
    
                    consoleBody.scrollTop = consoleBody.scrollHeight;
                };
    
                eventSource.onerror = () => {
                    console.error("Erreur de connexion au flux SSE.");
                    eventSource.close();
                };
    
                eventSource.onopen = () => {
                    console.log("Connexion au flux SSE ouverte.");
                };
    
                eventSource.onclose = () => {
                    console.log("Connexion au flux SSE fermée.");
                    eventSource.close();
                };
                
            } catch (error) {
                console.error("Une erreur est survenue :", error);
                Swal.update({
                    title: 'Erreur',
                    html: `<p>Une erreur est survenue : ${error.message}</p>`,
                    icon: 'error'
                });
            } finally {
                setTimeout(() => {
                    Swal.close();
                    window.scrollTo({
                        top: document.body.scrollHeight,
                        behavior: 'smooth'
                    });
                }, 5000);
            }
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    //localStorage.clear();
    fetchInteractionCount();
});
