(() => {

    const initDialerPage = () => {

        let contacts = {};
        const transformDialer = () => {
            const style = document.createElement('style');
            style.innerHTML = `
                .FORCE_HIDE {
                    opacity: 0 !important;
                    pointer-events: none !important;
                }
            `;
            document.head.appendChild(style);

            [...document.querySelectorAll(`
                [data-test="navigation-menu-item-contacts"]:not(.FORCE_HIDE),
                [data-test="navigation-menu-item-power-dialer"]:not(.FORCE_HIDE),
                [data-test="add-contact"]:not(.FORCE_HIDE),
                [data-test="add-contact-button"]:not(.FORCE_HIDE),
                [data-test="contacts-import-button"]:not(.FORCE_HIDE),
                [data-test="contact-create-button"]:not(.FORCE_HIDE)
            `)].forEach((el) => {
                el.classList.add('FORCE_HIDE');
            });

            [...document.querySelectorAll(`
                [data-test="card-link"]:not(.OVERRIDED),
                [data-test="item-content-heading-title"]:not(.OVERRIDED),
                [data-test="call-info"] > div > div:first-child:not(.OVERRIDED)
            `)].forEach((el) => {
                const phone = el.innerHTML.replace(/\s/gm, '');
                const contact = contacts[phone];
                if (contact) {
                    el.classList.add('OVERRIDED');
                    if (contact.test) {
                        el.classList.add('OVERRIDED_TEST');
                        el.setAttribute('data-test-number', contact.phone);
                    }
                    el.innerText = contact.name;
                    el.setAttribute('title', `${contact.companyName ? `${contact.companyName} - ` : ''}${contact.name}${contact.function ? ` - ${contact.function}` : ''}`)
                }
            });
            [...document.querySelectorAll('.OVERRIDED_TEST')].forEach(el => {
                const phone = el.getAttribute('data-test-number');
                if (phone && contacts[phone]) {
                    const contact = contacts[phone];
                    if (el.innerText !== contact.name) {
                        el.innerText = contact.name;
                        el.setAttribute('title', `${contact.companyName ? `${contact.companyName} - ` : ''}${contact.name}${contact.function ? ` - ${contact.function}` : ''}`)
                    }
                }
            })
        };
        transformDialer();

        window.addEventListener('message', async event => {
            if (event.data?.name === 'apm_app_dial_start') {
                console.log('CUSTOM EVENT DIAL_START');
                do {
                    await new Promise(r => setTimeout(r, 200));
                } while (!document.querySelector('[data-test="start-call"]:not([disabled])'));
                document.querySelector('[data-test="start-call"]').click();
            }
            if (event.data?.name === 'apm_app_override_contact') {
                contacts = event.data?.value?.contacts ?? {};
                transformDialer();
            }
        })

        setInterval(transformDialer, 500);
    }

    const initAllPageBM = () => {

        const style = document.createElement('style');
        style.innerHTML = `
            .phone-aircalled {
                background: #090;
                border-radius: 100%;
                width: 24px;
                height: 24px;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                position: relative;
                color: #FFF !important;
            }
            .phone-aircalled i {
                color: #FFF !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            .bmc-field a:not([data-html="true"]) .phone-aircalled,
            [data-original-title="Téléphone"] .phone-aircalled {
                margin-left: -4px;
                margin-top: -4px;
            }
            
            .phone-aircalled-override {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                cursor: pointer;
                user-select: none;
            }
        `;
        document.head.appendChild(style);

        const extractPhonesFromIcon = (phoneIcon) => {
            const inners = (phoneIcon.getAttribute('data-original-title') ?? '').split('<br>');
            return inners.map(inner => {
                const div = document.createElement('div');
                div.innerHTML = inner;
                return div.innerText.trim();
            }).filter(v => !!v);
        };

        const findCompanyContacts = async (companyId) => {
            try {
                const csrf = JSON.parse(localStorage.getItem('ember_simple_auth-session')).authenticated.meta.csrf
                const result = await(await fetch(`https://ui.boondmanager.com/api/companies/${companyId}/contacts?keywords=&maxResults=500&order=&page=1&sort=&states=0&typesOf=`, {
                    "headers": {
                        "x-csrf-boondmanager": csrf,
                    },
                    "method": "GET",
                    "mode": "cors",
                    "credentials": "include"
                })).json();

                return result.data
                    .map(c => [
                        {
                            url: `https://ui.boondmanager.com/contacts/${c.id}/overview`,
                            function: c.attributes.function,
                            name: `${c.attributes.firstName} ${c.attributes.lastName} ${c.attributes.phone1 && c.attributes.phone2 ? ' (1)' : ''}`.trim(),
                            phone: c.attributes.phone1,
                        },
                        {
                            url: `https://ui.boondmanager.com/contacts/${c.id}/overview`,
                            function: c.attributes.function,
                            name: `${c.attributes.firstName} ${c.attributes.lastName} ${c.attributes.phone1 && c.attributes.phone2 ? ' (2)' : ''}`.trim(),
                            phone: c.attributes.phone2
                        }
                    ].filter(c => c.phone)
                    )
                    .flat()
                ;
            } catch (e) {
                console.error(e);
            }
            return [];
        }

        setInterval(() => {
            const list = [...document.querySelectorAll('.bmc-render-phone-icon:not(.disabled):not(.phone-aircalled)')];
            list.forEach(phoneEl => {
                try {
                    phoneEl.classList.add('phone-aircalled');
                    const overrideEl = document.createElement('div');
                    overrideEl.classList.add('phone-aircalled-override');
                    phoneEl.appendChild(overrideEl);

                    overrideEl.addEventListener('click', event => {
                        event.preventDefault();
                        event.stopPropagation();
                        event.stopImmediatePropagation();
                        const phones = extractPhonesFromIcon(phoneEl);

                        const contacts = phones.map((phone, i) => {
                            const contact = {
                                phone
                            }
                            const tr = phoneEl.parentElement.parentElement;
                            const a = tr.querySelector('a');
                            if (tr && a) {
                                if (document.location.pathname === '/companies') {
                                    contact.companyUrl = a.href;
                                } else {
                                    contact.url = a.href;
                                }
                                contact.name = a.innerText + (phones.length > 1 ? ` (${i+1})` : '');
                            }

                            console.log(contact);
                            return contact;
                        })

                        if (contacts.length === 1) {
                            window.postMessage({ action: 'air_call_call_contact', contact: contacts[0] }, '*');
                        } else if (contacts.length) {
                            window.postMessage({ action: 'air_call_list_number', list: contacts, append: false}, '*');
                        }
                    });
                } catch (e) {
                    console.error(e);
                }
            });

            try {
                const list2 = document.querySelectorAll('.bmc-field a:not([data-html="true"]) i.bmi-phone:not(.phone-aircalled)');
                list2.forEach(phoneEl => {
                    phoneEl.classList.add('phone-aircalled');
                    const overrideEl = document.createElement('div');
                    overrideEl.classList.add('phone-aircalled-override');
                    phoneEl.appendChild(overrideEl);

                    overrideEl.addEventListener('click', event => {
                        event.preventDefault();
                        event.stopPropagation();
                        event.stopImmediatePropagation();

                        const phone = phoneEl.parentElement.parentElement.parentElement.querySelector('input')?.value;
                        if (phone) {
                            const contact = {
                                phone,
                                name: document.head.querySelector('title').innerText,
                            };
                            if (document.location.pathname.indexOf('/companies/') === 0) {
                                contact.companyUrl = window.location.href;
                            } else {
                                contact.url = window.location.href;
                            }
                            console.log(contact);
                            window.postMessage({ action: 'air_call_call_contact', contact }, '*');
                        }
                    });
                });
                const list3 = document.querySelectorAll('.bmc-field [data-original-title="Téléphone"] i.bmi-phone:not(.phone-aircalled)');
                list3.forEach(phoneEl => {
                    phoneEl.classList.add('phone-aircalled');
                    const overrideEl = document.createElement('div');
                    overrideEl.classList.add('phone-aircalled-override');
                    phoneEl.appendChild(overrideEl);

                    overrideEl.addEventListener('click', event => {
                        event.preventDefault();
                        event.stopPropagation();
                        event.stopImmediatePropagation();

                        const phone = phoneEl.parentElement.parentElement.innerText;
                        if (phone) {
                            const contact = {
                                phone,
                            };
                            const a = phoneEl.parentElement.parentElement.parentElement.parentElement.querySelector('a');
                            if (a) {
                                contact.name = a.innerText;
                                if (a.href?.indexOf('https://ui.boondmanager.com/companies/') === 0) {
                                    contact.companyUrl = a.href;
                                } else {
                                    contact.url = a.href;
                                }
                            }
                            console.log(contact);
                            window.postMessage({ action: 'air_call_call_contact', contact }, '*');
                        }
                    });
                });

            } catch (e) {
                console.error(e);
            }
        }, 1000);

        let list = null;
        let buttons = null;

        async function endLoading() {
            do {
                await new Promise(r => setTimeout(r, 100));
            } while (!!document.querySelector('.bm-logo-loader-stroke'));
            await new Promise(r => setTimeout(r, 100));
        }

        async function prevButton() {
            console.log('Call PrevPage');
            buttons[0].click();
            await endLoading();
        }
        async function nextButton() {
            console.log('Call NextPage');
            buttons[1].click();
            await endLoading();
        }

        async function analyseList(rows) {
            rows = rows ?? [...list.querySelectorAll('tr')];
            return (await Promise.all(
                rows
                    .map(async row => {
                        const a = row.querySelector('a');
                        if (a) {
                            const phoneIcon = row.querySelector('.bmc-render-phone-icon');
                            if (phoneIcon) {
                                const phones = extractPhonesFromIcon(phoneIcon);
                                const result1 = phones.map((phone, i) => {
                                    if (phone) {
                                        const contact= {
                                            name: a.innerText + (phones.length > 1 ? ` (${i+1})` : ''),
                                            phone
                                        };
                                        if (document.location.pathname === '/companies') {
                                            contact.companyUrl = a.href;
                                        } else {
                                            contact.url = a.href;
                                        }
                                        if (document.location.pathname.indexOf('/companies') === 0) {
                                            contact.companyName = contact.name;
                                            contact.name += ' (Numéro principal)';
                                        }
                                        return contact;
                                    }
                                });
                                let result2 = [];
                                if (document.location.pathname.indexOf('/companies') === 0) {
                                    const companyId = [...a.href.matchAll(/\/companies\/([0-9]+)\//gi)]?.[0]?.[1];
                                    if (companyId) {
                                        result2 = (await findCompanyContacts(companyId)).map(c => ({
                                            ...c,
                                            companyUrl: a.href,
                                            companyName: a.innerText,
                                        }));
                                    }
                                }
                                return [ ...result1, ...result2 ];
                            }
                        }
                        return [];
                    })
            ))
                .flat()
            ;
        }

        let cancel = false;
        window.addEventListener('message', async (event) => {
            if (event.data?.action === 'air_call_analyse_cancel') {
                cancel = true;
            }
            if (event.data?.action === 'air_call_analyse') {
                cancel = false;
                let numbers = [];

                list = document.querySelector('.bmc-table-list');

                const checkeds = [...list.querySelectorAll('td:first-child input:checked')];
                if (checkeds.length) {
                    numbers = [ ...numbers, ...await analyseList(checkeds.map(c => c.parentNode.parentNode.parentNode))  ];
                } else {
                    buttons = [...document.querySelectorAll('.bmc-pagination button')];
                    if (list && buttons.length) {
                        // Aller a la premiere page;
                        while(!buttons[0].disabled) {
                            await prevButton();
                            if (cancel) {
                                cancel = false;
                                window.postMessage({ action: 'air_call_list_end' }, '*');
                                return;
                            }
                        }
                        console.log('Start Analyse');

                        numbers = [ ...numbers, ...await analyseList()  ];
                        while(!buttons[1].disabled) {
                            console.log('Newt page Analyse');
                            await nextButton();
                            numbers = [ ...numbers, ...await analyseList() ];
                            if (cancel) {
                                cancel = false;
                                window.postMessage({ action: 'air_call_list_end' }, '*');
                                return;
                            }
                        }
                    }
                }


                console.log('air_call_list_number', numbers);
                window.postMessage({ action: 'air_call_list_number', list: numbers, append: !!event.data.append}, '*');
                window.postMessage({ action: 'air_call_list_end' }, '*');
            }
        })

    };

    if (window.location.origin === 'https://workspace.aircall.io') {
        initDialerPage();
    } else if (window.location.origin === 'https://ui.boondmanager.com') {
        initAllPageBM();
    }

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        if (message.action === 'air_call_analyse') {
            console.log('Start analyse');
            window.postMessage({ action: 'air_call_analyse', append: message.append }, '*');
        }
        if (message.action === 'air_call_analyse_cancel') {
            console.log('Cancel analyse');
            window.postMessage({ action: 'air_call_analyse_cancel' }, '*');
        }
    });
    window.addEventListener('message', (event) => {
        // Vérifiez l'origine si nécessaire pour plus de sécurité
        if (event.data?.action === 'air_call_list_number') {
            chrome.runtime.sendMessage({
                action: 'air_call_list_number',
                list: event.data.list,
                append: event.data.append,
            });
        }
        if (event.data?.action === 'air_call_call_contact') {
            chrome.runtime.sendMessage({
                action: 'air_call_call_contact',
                contact: event.data.contact,
            });
        }
        if (event.data?.action === 'air_call_list_end') {
            chrome.runtime.sendMessage({
                action: 'air_call_list_end',
            });
        }
    });
})();

