const analyse = document.getElementById('analyse');
const openDialer = document.getElementById('openDialer');
const append = document.getElementById('append');
let analyseTab = null;

append.addEventListener('change', () =>  {
    localStorage.setItem('append', append.checked ? '1' : '0');
});
append.checked = localStorage.getItem('append') === '1';

analyse.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (analyseTab) {
            analyse.innerText='Analyser la page';
            try {
                chrome.tabs.sendMessage(analyseTab, { action: 'air_call_analyse_cancel' });
            } catch (e) {
                console.error(e);
            }
            analyseTab = null;
        } else {
            if (tabs.length === 0) {
                console.error("No active tab found.");
                return;
            }
            analyseTab = tabs[0].id;
            chrome.tabs.sendMessage(analyseTab, { action: 'air_call_analyse', append: append.checked });
            analyse.innerText='Annuler';
        }
    });
});
openDialer.addEventListener('click', () => {
    chrome.runtime.sendMessage({ action: "openDialer" });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'air_call_list_end') {
        analyse.innerText='Analyser la page';
        analyseTab = null;
    }
});
