document.addEventListener('DOMContentLoaded', function () {
    const fillButton = document.getElementById('fillButton');
    const fillButtonManual = document.getElementById('fillButtonManual');
    const statusDiv = document.getElementById('status');

    const barContainer = document.getElementById('bar');
    let isRunning = false; // Add this flag to prevent multiple runs

    // Listen for messages from content script
    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
        if (request.action === 'updateProgress') {
            // Only update if progress actually changed significantly
            if (Math.abs(request.progress - currentPercent) > 5) {
                createProgressBar("ascii-progress-bar-1", request.progress, 500);
            }
        } else if (request.action === 'showProgress') {
            if (!isRunning) {
                barContainer.style.display = 'block';
                resetProgress(); // Use the new reset function
                updateLoadingHash();
                isRunning = true;
            }
        } else if (request.action === 'hideProgress') {
            barContainer.style.display = 'none';
            stopLoadingHash();
            isRunning = false;
        } else if (request.action === 'updateStatus') {
            statusDiv.textContent = request.message;
            statusDiv.style.color = request.isError ? 'red' : '#00ff88';
        } else if (request.action === 'playSound') {
            const audio = new Audio("./progressbar/finish-him-off.mp3");
            audio.play();
        }

    });



    fillButton.addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling form...';

                // Execute the fill script in the current tab
                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillForm
                });

                statusDiv.textContent = 'Form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    fillButtonManual.addEventListener('click', async function () {
        if (isRunning) {
            statusDiv.textContent = 'Already running, please wait...';
            return;
        }

        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                isRunning = true;
                barContainer.style.display = 'block';
                resetProgress();
                updateLoadingHash();
                statusDiv.textContent = 'Starting all steps...';
                statusDiv.style.color = 'white';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillFormManual
                });

                statusDiv.textContent = 'All steps completed successfully!';
                statusDiv.style.color = '#00ff88';
                isRunning = false;

            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
            barContainer.style.display = 'none';
            stopLoadingHash();
            isRunning = false;
        }
    });

    document.getElementById('fillDiagButton').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling diagnostics form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillDiagForm
                });

                statusDiv.textContent = 'Diagnostics form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('fillRepairButton').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling repair form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillRepairForm
                });

                statusDiv.textContent = 'Repair form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });


    document.getElementById('fillnextNext').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling Next form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillNextForm
                });

                statusDiv.textContent = 'Next form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('fillCheckPayment').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling Next form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillCheckPaymentForm
                });

                statusDiv.textContent = 'Next form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });


    document.getElementById('fillZipRecived').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling repair form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillZipRecivedForm
                });

                statusDiv.textContent = 'Repair form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('fillworksDone').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling repair form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillworksDoneForm
                });

                statusDiv.textContent = 'Repair form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('fillfinishStep').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling repair form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillfinishStepForm
                });

                statusDiv.textContent = 'Repair form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('fillcloseStep').addEventListener('click', async function () {
        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {
                statusDiv.textContent = 'Filling repair form...';

                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: fillcloseStepForm
                });

                statusDiv.textContent = 'Repair form filled successfully!';
            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
        }
    });

    document.getElementById('runAllSteps').addEventListener('click', async function () {
        if (isRunning) {
            statusDiv.textContent = 'Already running, please wait...';
            return;
        }

        try {
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (tab.url.includes('crm.evotor.ru/auth/asc/requests')) {

                isRunning = true;
                barContainer.style.display = 'block';
                resetProgress();
                updateLoadingHash();
                statusDiv.textContent = 'Starting all steps...';
                statusDiv.style.color = 'white';
                // Inject ALL functions together
                await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    function: async function () {
                        // Define all functions here
                        async function fillDiagForm() {
                            try {
                                console.log('=== Starting diagnostics form fill ===');

                                // Function to select autocomplete with exact text verification
                                async function selectAutocompleteWithVerification(selector, expectedText, maxAttempts = 5) {
                                    for (let attempt = 3; attempt <= maxAttempts; attempt++) {
                                        console.log(`Attempt ${attempt} to select: "${expectedText}"`);

                                        try {
                                            const input = document.querySelector(`${selector} input`);
                                            if (!input) {
                                                console.log(`Input not found for selector: ${selector}`);
                                                await new Promise(resolve => setTimeout(resolve, 500));
                                                continue;
                                            }

                                            // Clear any existing selection first
                                            const clearBtn = document.querySelector(`${selector} .ng-value-icon`);
                                            if (clearBtn) {
                                                clearBtn.click();
                                                await new Promise(resolve => setTimeout(resolve, 200));
                                            }

                                            input.focus();
                                            input.click();

                                            // Open dropdown
                                            input.dispatchEvent(new KeyboardEvent('keydown', {
                                                key: 'ArrowDown', code: 'ArrowDown', keyCode: 40, which: 40, bubbles: true
                                            }));

                                            await new Promise(resolve => setTimeout(resolve, 300));

                                            // Select with Enter
                                            input.dispatchEvent(new KeyboardEvent('keydown', {
                                                key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                            }));

                                            await new Promise(resolve => setTimeout(resolve, 500));

                                            // Verify exact text selection
                                            const selectedValue = document.querySelector(`${selector} .ng-value-label`);
                                            if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                                                console.log(`✓ Selection verified: "${expectedText}"`);
                                                return true;
                                            } else {
                                                const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                                                console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                                                // Try alternative selection method if first attempt fails
                                                if (attempt > 1) {
                                                    console.log('Trying alternative selection method...');
                                                    // Type the text to search for exact match
                                                    input.focus();
                                                    input.value = expectedText;
                                                    input.dispatchEvent(new Event('input', { bubbles: true }));
                                                    await new Promise(resolve => setTimeout(resolve, 500));

                                                    input.dispatchEvent(new KeyboardEvent('keydown', {
                                                        key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                                    }));

                                                    await new Promise(resolve => setTimeout(resolve, 500));

                                                    // Verify again
                                                    const retrySelectedValue = document.querySelector(`${selector} .ng-value-label`);
                                                    if (retrySelectedValue && retrySelectedValue.textContent.trim() === expectedText) {
                                                        console.log(`✓ Selection verified with search: "${expectedText}"`);
                                                        return true;
                                                    }
                                                }
                                            }

                                        } catch (error) {
                                            console.log(`Error in attempt ${attempt}:`, error);
                                        }

                                        if (attempt < maxAttempts) {
                                            await new Promise(resolve => setTimeout(resolve, 1000));
                                        }
                                    }

                                    console.log(`Failed to select "${expectedText}" after all attempts`);
                                    return false;
                                }

                                // Step 1: Click "Добавить" button
                                console.log('Step 1: Clicking Добавить button');
                                const addButton = document.querySelector('a.info__no-data-btn.link');
                                if (addButton) {
                                    addButton.click();
                                    await new Promise(resolve => setTimeout(resolve, 1000));
                                } else {
                                    console.log('Add button not found in fillDiagForm');
                                    return;
                                }

                                // Step 2: Select diagnostics result - "Дефект обнаружен"
                                console.log('Step 2: Selecting diagnostics result');
                                await selectAutocompleteWithVerification(
                                    'evo-autocomplete[formcontrolname="diagnosticsResult"]',
                                    'Дефект обнаружен'
                                );

                                // Step 3: Select component - "Модуль эквайринга"
                                console.log('Step 3: Selecting component');
                                await selectAutocompleteWithVerification(
                                    'evo-autocomplete[formcontrolname="componentId"]',
                                    'Модуль эквайринга'
                                );

                                // Step 4: Select defect - "Заблокирован Модуль эквайринга"
                                console.log('Step 4: Selecting defect');
                                await selectAutocompleteWithVerification(
                                    'evo-autocomplete[formcontrolname="defectId"]',
                                    'Заблокирован Модуль эквайринга'
                                );

                                // Step 5: Fill comment
                                console.log('Step 5: Filling comment');
                                const textarea = document.querySelector('evo-textarea[formcontrolname="comment"] textarea');
                                if (textarea) {
                                    textarea.value = 'TAMPER';
                                    textarea.dispatchEvent(new Event('input', { bubbles: true }));
                                    await new Promise(resolve => setTimeout(resolve, 300));
                                }

                                // Step 6: Click Save button with retry logic
                                console.log('Step 6: Clicking Save button');
                                let saveAttempts = 0;
                                const maxSaveAttempts = 3;

                                while (saveAttempts < maxSaveAttempts) {
                                    saveAttempts++;

                                    const saveButton = Array.from(document.querySelectorAll('span.evo-button__content'))
                                        .find(span => span.textContent.trim() === 'Сохранить')
                                        ?.closest('button');

                                    if (saveButton && !saveButton.disabled) {
                                        console.log(`Save button found and enabled! Clicking... (attempt ${saveAttempts})`);
                                        saveButton.click();
                                        break;
                                    } else if (saveButton) {
                                        console.log(`Save button found but disabled (attempt ${saveAttempts})`);
                                    } else {
                                        console.log(`Save button not found (attempt ${saveAttempts})`);
                                    }

                                    if (saveAttempts < maxSaveAttempts) {
                                        await new Promise(resolve => setTimeout(resolve, 1000));
                                    }
                                }

                                console.log('=== Diagnostics form filling completed ===');

                            } catch (error) {
                                console.error('Error filling diagnostics form:', error);
                            }
                        }

                        async function fillRepairForm() {
                            try {
                                console.log('=== Starting repair form fill ===');

                                // Function to select autocomplete with exact text verification
                                async function selectAutocompleteWithVerification(selector, expectedText, maxAttempts = 5) {
                                    for (let attempt = 3; attempt <= maxAttempts; attempt++) {
                                        console.log(`Attempt ${attempt} to select: "${expectedText}"`);

                                        try {
                                            const input = document.querySelector(`${selector} input`);
                                            if (!input) {
                                                console.log(`Input not found for selector: ${selector}`);
                                                await new Promise(resolve => setTimeout(resolve, 500));
                                                continue;
                                            }

                                            // Clear any existing selection first
                                            const clearBtn = document.querySelector(`${selector} .ng-value-icon`);
                                            if (clearBtn) {
                                                clearBtn.click();
                                                await new Promise(resolve => setTimeout(resolve, 200));
                                            }

                                            input.focus();
                                            input.click();

                                            // Open dropdown
                                            input.dispatchEvent(new KeyboardEvent('keydown', {
                                                key: 'ArrowDown', code: 'ArrowDown', keyCode: 40, which: 40, bubbles: true
                                            }));

                                            await new Promise(resolve => setTimeout(resolve, 300));

                                            // Select with Enter
                                            input.dispatchEvent(new KeyboardEvent('keydown', {
                                                key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                            }));

                                            await new Promise(resolve => setTimeout(resolve, 500));

                                            // Verify exact text selection
                                            const selectedValue = document.querySelector(`${selector} .ng-value-label`);
                                            if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                                                console.log(`✓ Selection verified: "${expectedText}"`);
                                                return true;
                                            } else {
                                                const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                                                console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                                                // Try alternative selection method if first attempt fails
                                                if (attempt > 1) {
                                                    console.log('Trying alternative selection method...');
                                                    // Type the text to search for exact match
                                                    input.focus();
                                                    input.value = expectedText;
                                                    input.dispatchEvent(new Event('input', { bubbles: true }));
                                                    await new Promise(resolve => setTimeout(resolve, 500));

                                                    input.dispatchEvent(new KeyboardEvent('keydown', {
                                                        key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                                    }));

                                                    await new Promise(resolve => setTimeout(resolve, 500));

                                                    // Verify again
                                                    const retrySelectedValue = document.querySelector(`${selector} .ng-value-label`);
                                                    if (retrySelectedValue && retrySelectedValue.textContent.trim() === expectedText) {
                                                        console.log(`✓ Selection verified with search: "${expectedText}"`);
                                                        return true;
                                                    }
                                                }
                                            }

                                        } catch (error) {
                                            console.log(`Error in attempt ${attempt}:`, error);
                                        }

                                        if (attempt < maxAttempts) {
                                            await new Promise(resolve => setTimeout(resolve, 1000));
                                        }
                                    }

                                    console.log(`Failed to select "${expectedText}" after all attempts`);
                                    return false;
                                }

                                // Step 1: Click "Добавить" button with retry logic
                                console.log('Step 1: Attempting to click Добавить button');

                                let addButtonFound = false;
                                for (let attempt = 1; attempt <= 3; attempt++) {
                                    console.log(`Attempt ${attempt} to find Добавить button`);

                                    const addButton = document.querySelector('a.info__no-data-btn.link');
                                    if (addButton) {
                                        console.log('Add button found! Clicking...');
                                        addButton.click();
                                        addButtonFound = true;
                                        break;
                                    } else {
                                        console.log('Add button not found, waiting 1 second...');
                                        await new Promise(resolve => setTimeout(resolve, 1000));
                                    }
                                }

                                if (!addButtonFound) {
                                    console.log('Add button not found after 3 attempts');
                                    return;
                                }

                                await new Promise(resolve => setTimeout(resolve, 1000));

                                // Step 2: Select sample work - "Разблокировка Модуля эквайринга"
                                console.log('Step 2: Selecting sample work');
                                await selectAutocompleteWithVerification(
                                    'evo-autocomplete[formcontrolname="sampleWorkId"]',
                                    'Разблокировка Модуля эквайринга'
                                );

                                // Step 3: Click Save button with retry logic
                                console.log('Step 3: Clicking Save button');
                                let saveAttempts = 0;
                                const maxSaveAttempts = 3;

                                while (saveAttempts < maxSaveAttempts) {
                                    saveAttempts++;

                                    const saveButton = Array.from(document.querySelectorAll('span.evo-button__content'))
                                        .find(span => span.textContent.trim() === 'Сохранить')
                                        ?.closest('button');

                                    if (saveButton && !saveButton.disabled) {
                                        console.log(`Save button found and enabled! Clicking... (attempt ${saveAttempts})`);
                                        saveButton.click();
                                        break;
                                    } else if (saveButton) {
                                        console.log(`Save button found but disabled (attempt ${saveAttempts})`);
                                    } else {
                                        console.log(`Save button not found (attempt ${saveAttempts})`);
                                    }

                                    if (saveAttempts < maxSaveAttempts) {
                                        await new Promise(resolve => setTimeout(resolve, 1000));
                                    }
                                }

                                console.log('=== Repair form filling completed ===');

                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillNextForm() {
                            try {
                                console.log('=== Starting Nexttt form fill ===');

                                // Step 1: Click "Добавить" button
                                console.log('Step 1: Clicking Подтвердить работы');

                                let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить работы') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 300));


                                // Step 3: Click Save button
                                console.log('Step 3: Clicking Save button');


                                console.log('=== Repair form filling completed ===');

                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillCheckPaymentForm() {
                            try {
                                console.log('Step 1: Clicking  Подтвердить оплату ');

                                let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить оплату') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 300));
                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillZipRecivedForm() {
                            try {
                                // Step 1: Click "ЗИП получен" button
                                console.log('Step 1: Clicking  ЗИП получен ');

                                let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'ЗИП получен') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 300));
                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillworksDoneForm() {
                            try {
                                // Step 1: Click "ЗИП получен" button
                                console.log('Step 1: Clicking  Работы выполнены ');

                                let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Работы выполнены') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 300));
                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillfinishStepForm() {
                            try {

                                // Step 1: Fill comment
                                console.log('Step 5: Filling comment');
                                const textarea = document.querySelector('evo-textarea[formcontrolname="comment"] textarea');
                                textarea.value = 'TAMPER';
                                textarea.dispatchEvent(new Event('input', { bubbles: true }));

                                await new Promise(resolve => setTimeout(resolve, 200));

                                // Step 2: Click "Подтвердить" button
                                console.log('Step 2: Clicking  Подтвердить ');

                                let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 400));
                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function fillcloseStepForm() {
                            try {
                                console.log('=== Starting Детали заявки fill ===');

                                // Step 1: Click "Разблокировать модуль эквайринга" link
                                console.log('Step 1: Clicking Разблокировать модуль эквайринга');
                                let a1 = 0, i1 = setInterval(() => { a1++; const l = document.querySelector('crm-asc-request-required-action-acquiring-unlock a.link.link-bold'); l && l.textContent.trim() === 'Разблокировать модуль эквайринга' ? (console.log(`Clicking on attempt ${a1}`), l.click(), clearInterval(i1)) : console.log(`Attempt ${a1}: Link not found`), a1 >= 3 && (console.log('Done'), clearInterval(i1)) }, 1000);

                                await new Promise(resolve => setTimeout(resolve, 3000));

                                // Step 2: Download
                                console.log('Step 2: Clicking Скачать акт выполненных работ');
                                let a2 = 0, i2 = setInterval(() => { a2++; const s = document.querySelectorAll('span.evo-icon-button__label'); let t = null; for (let e of s) e.textContent.includes('акт выполненных работ') && (t = e.closest('button')); t ? (console.log(`Clicking on attempt ${a2}`), t.click(), clearInterval(i2)) : console.log(`Attempt ${a2}: Button not found`), a2 >= 3 && (console.log('Done'), clearInterval(i2)) }, 500);

                                await new Promise(resolve => setTimeout(resolve, 2000));

                                // Step 3: Click "Закрыть заявку" button
                                console.log('Step 3: Clicking Закрыть заявку');
                                let a3 = 0, i3 = setInterval(() => { a3++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Закрыть заявку') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a3}`), b.click(), clearInterval(i3)) : b ? console.log(`Attempt ${a3}: Button disabled`) : console.log(`Attempt ${a3}: Button not found`), a3 >= 3 && (console.log('Done'), clearInterval(i3)) }, 500);

                            } catch (error) {
                                console.error('Error filling repair form:', error);
                            }
                        }

                        async function runAllSteps() {
                            function updateProgress(progress, message = '') {
                                chrome.runtime.sendMessage({
                                    action: 'updateProgress',
                                    progress: progress,
                                    message: message
                                });
                            }

                            function play() {
                                chrome.runtime.sendMessage({
                                    action: 'playSound',
                                });
                            }
                            try {
                                console.log('=== Starting All Steps Sequentially ===');
                                updateProgress(10, 'Starting diagnostics...');

                                console.log('Progress: 10% - Starting diagnostics...');
                                await fillDiagForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 20% - Starting repair...');
                                updateProgress(20, 'Starting diagnostics...');
                                await fillRepairForm();
                                await new Promise(resolve => setTimeout(resolve, 3000));

                                console.log('Progress: 30% - Starting repair...');
                                updateProgress(30, 'Starting diagnostics...');
                                await fillNextForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 40% - Starting repair...');
                                updateProgress(40, 'Starting diagnostics...');
                                await fillCheckPaymentForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 50% - Starting repair...');
                                updateProgress(50, 'Starting diagnostics...');
                                await fillZipRecivedForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 60% - Starting repair...');
                                updateProgress(61, 'Starting diagnostics...');
                                await fillworksDoneForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 70% - Starting repair...');
                                updateProgress(72, 'Starting diagnostics...');
                                await fillfinishStepForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 80% - Starting repair...');
                                updateProgress(87, 'Starting diagnostics...');
                                await fillcloseStepForm();
                                await new Promise(resolve => setTimeout(resolve, 1000));

                                console.log('Progress: 100% - All steps completed!');
                                updateProgress(100, 'Starting diagnostics...');
                                console.log('=== All Steps Completed Successfully ===');
                                play();
                                // const audio = new Audio("./progressbar/finish-him-off.mp3");
                                // audio.play();

                            } catch (error) {
                                console.error('Error in runAllSteps:', error);
                            }
                        }

                        // Execute runAllSteps
                        return await runAllSteps();
                    }
                });

                isRunning = false;
                statusDiv.style.color = '#00ff88';
                statusDiv.textContent = 'All steps completed successfully!';

            } else {
                statusDiv.textContent = 'Please navigate to CRM page first';
                statusDiv.style.color = 'red';
            }
        } catch (error) {
            statusDiv.textContent = 'Error: ' + error.message;
            statusDiv.style.color = 'red';
            barContainer.style.display = 'none';
            stopLoadingHash();
            isRunning = false;
        }
    });







    async function fillForm() {
        try {

            // Function to find input by formcontrolname
            function findInputByFormControlName(formControlName) {
                const evoInput = document.querySelector(`evo-input[formcontrolname="${formControlName}"]`);
                if (!evoInput) return null;
                const input = evoInput.querySelector('input.evo-input__field:not([disabled])');
                return input;
            }

            // Function to safely fill a field
            function fillField(formControlName, value) {
                const input = findInputByFormControlName(formControlName);
                if (input) {
                    if (!input.value || input.value.trim() === '') {
                        input.value = value;
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                        input.dispatchEvent(new Event('change', { bubbles: true }));
                        return true;
                    } else {
                        console.log(`Field ${formControlName} already has value: ${input.value}`);
                        return false;
                    }
                } else {
                    console.log(`Field ${formControlName} not found`);
                    return false;
                }
            }

            // Function to select service type with verification
            async function selectServiceType(expectedText = 'Не гарантийный', maxAttempts = 5) {
                for (let attempt = 1; attempt <= maxAttempts; attempt++) {
                    console.log(`Attempt ${attempt} to select: ${expectedText}`);

                    try {
                        const input = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] input');
                        if (!input) {
                            console.log('Input not found');
                            await new Promise(resolve => setTimeout(resolve, 500));
                            continue;
                        }

                        input.focus();
                        input.click();

                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'ArrowDown',
                            code: 'ArrowDown',
                            keyCode: 40,
                            which: 40,
                            bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 300));

                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'Enter',
                            code: 'Enter',
                            keyCode: 13,
                            which: 13,
                            bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 500));

                        // Verify selection
                        const selectedValue = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] .ng-value-label');
                        if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                            console.log('✓ Service type selection verified successfully');
                            return true;
                        } else {
                            const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                            console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                            // Clear selection and retry
                            if (selectedValue) {
                                const clearBtn = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] .ng-value-icon');
                                if (clearBtn) {
                                    clearBtn.click();
                                    await new Promise(resolve => setTimeout(resolve, 200));
                                }
                            }
                        }

                    } catch (error) {
                        console.log(`Error in attempt ${attempt}:`, error);
                    }

                    if (attempt < maxAttempts) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }

                console.log('Failed to select the correct service type after all attempts');
                return false;
            }

            // Fill fields using formcontrolname
            fillField('legalName', 'ООО "Сбербанк-Сервис"');
            fillField('inn', '7736663049');
            fillField('kpp', '771501001');
            fillField('legalAddress', '127018, город Москва, ул Двинцев, д. 12 к. 1, помещ. 1/1');
            fillField('contactName', 'ООО "Сбербанк-Сервис"');
            fillField('phone', '0000000000');
            fillField('email', 'a@a.com');

            // Handle textarea separately if it has a different structure
            const textarea = document.querySelector('textarea');
            if (textarea && (!textarea.value || textarea.value.trim() === '')) {
                textarea.value = 'TAMPER';
                textarea.dispatchEvent(new Event('input', { bubbles: true }));
                textarea.dispatchEvent(new Event('change', { bubbles: true }));
            }

            // Use the improved selection function
            await selectServiceType('Не гарантийный', 3);

            // Wait a bit before trying to click the button
            await new Promise(resolve => setTimeout(resolve, 700));

            // Click "Оформить" button with retry logic
            let attempts = 0;
            const maxAttempts = 3;
            const interval = 500;

            const clickInterval = setInterval(() => {
                attempts++;

                const buttons = document.querySelectorAll('button span.evo-button__content');
                let targetButton = null;

                for (let span of buttons) {
                    if (span.textContent.trim() === 'Оформить') {
                        targetButton = span.closest('button');
                        break;
                    }
                }

                if (targetButton && !targetButton.disabled) {
                    console.log(`Attempt ${attempts}: "Оформить" button is enabled! Clicking...`);
                    targetButton.click();
                    clearInterval(clickInterval);
                } else if (targetButton) {
                    console.log(`Attempt ${attempts}: "Оформить" button found but disabled`);
                } else {
                    console.log(`Attempt ${attempts}: "Оформить" button not found`);
                }

                if (attempts >= maxAttempts) {
                    console.log('Max attempts reached. Stopping.');
                    clearInterval(clickInterval);
                }
            }, interval);

        } catch (error) {
            console.error('Error filling form:', error);
        }
    }

    async function fillFormManual() {

        function updateProgress(progress, message = '') {
            chrome.runtime.sendMessage({
                action: 'updateProgress',
                progress: progress,
                message: message
            });
        }

        try {
            updateProgress(10, 'Starting form fill...');

            // Function to find input by formcontrolname
            function findInputByFormControlName(formControlName) {
                const evoInput = document.querySelector(`evo-input[formcontrolname="${formControlName}"]`);
                if (!evoInput) return null;
                const input = evoInput.querySelector('input.evo-input__field:not([disabled])');
                return input;
            }

            // Function to safely fill a field
            function fillField(formControlName, value) {
                const input = findInputByFormControlName(formControlName);
                if (input) {
                    if (!input.value || input.value.trim() === '') {
                        input.value = value;
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                        input.dispatchEvent(new Event('change', { bubbles: true }));
                        return true;
                    } else {
                        console.log(`Field ${formControlName} already has value: ${input.value}`);
                        return false;
                    }
                } else {
                    console.log(`Field ${formControlName} not found`);
                    return false;
                }
            }

            updateProgress(20, 'Filling basic fields...');

            // Function to select service type with verification
            async function selectServiceType(expectedText = 'Не гарантийный', maxAttempts = 5) {
                for (let attempt = 1; attempt <= maxAttempts; attempt++) {
                    console.log(`Attempt ${attempt} to select: ${expectedText}`);

                    try {
                        const input = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] input');
                        if (!input) {
                            console.log('Input not found');
                            await new Promise(resolve => setTimeout(resolve, 500));
                            continue;
                        }

                        input.focus();
                        input.click();

                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'ArrowDown',
                            code: 'ArrowDown',
                            keyCode: 40,
                            which: 40,
                            bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 300));

                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'Enter',
                            code: 'Enter',
                            keyCode: 13,
                            which: 13,
                            bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 500));

                        // Verify selection
                        const selectedValue = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] .ng-value-label');
                        if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                            console.log('✓ Service type selection verified successfully');
                            return true;
                        } else {
                            const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                            console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                            // Clear selection and retry
                            if (selectedValue) {
                                const clearBtn = document.querySelector('evo-autocomplete[formcontrolname="serviceTypeId"] .ng-value-icon');
                                if (clearBtn) {
                                    clearBtn.click();
                                    await new Promise(resolve => setTimeout(resolve, 200));
                                }
                            }
                        }

                    } catch (error) {
                        console.log(`Error in attempt ${attempt}:`, error);
                    }

                    if (attempt < maxAttempts) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }

                console.log('Failed to select the correct service type after all attempts');
                return false;
            }

            updateProgress(50, 'Selecting service type...');

            // Fill fields using formcontrolname
            fillField('legalName', 'ООО "Сбербанк-Сервис"');
            fillField('inn', '7736663049');
            fillField('kpp', '771501001');
            fillField('legalAddress', '127018, город Москва, ул Двинцев, д. 12 к. 1, помещ. 1/1');
            fillField('contactName', 'ООО "Сбербанк-Сервис"');
            fillField('phone', '0000000000');
            fillField('email', 'a@a.com');

            // Handle textarea separately if it has a different structure
            const textarea = document.querySelector('textarea');
            if (textarea && (!textarea.value || textarea.value.trim() === '')) {
                textarea.value = 'TAMPER';
                textarea.dispatchEvent(new Event('input', { bubbles: true }));
                textarea.dispatchEvent(new Event('change', { bubbles: true }));
            }

            // Use the improved selection function
            await selectServiceType('Не гарантийный', 3);

            updateProgress(80, 'Clicking submit button...');
            updateProgress(100, 'Form completed!');
            // updateStatus('Form filled successfully!');

        } catch (error) {
            console.error('Error filling form:', error);
            updateProgress(0, 'Error occurred');
        }
    }



    async function fillDiagForm() {
        try {
            console.log('=== Starting diagnostics form fill ===');

            // Function to select autocomplete with exact text verification
            async function selectAutocompleteWithVerification(selector, expectedText, maxAttempts = 5) {
                for (let attempt = 1; attempt <= maxAttempts; attempt++) {
                    console.log(`Attempt ${attempt} to select: "${expectedText}"`);

                    try {
                        const input = document.querySelector(`${selector} input`);
                        if (!input) {
                            console.log(`Input not found for selector: ${selector}`);
                            await new Promise(resolve => setTimeout(resolve, 500));
                            continue;
                        }

                        // Clear any existing selection first
                        const clearBtn = document.querySelector(`${selector} .ng-value-icon`);
                        if (clearBtn) {
                            clearBtn.click();
                            await new Promise(resolve => setTimeout(resolve, 200));
                        }

                        input.focus();
                        input.click();

                        // Open dropdown
                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'ArrowDown', code: 'ArrowDown', keyCode: 40, which: 40, bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 300));

                        // Select with Enter
                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 500));

                        // Verify exact text selection
                        const selectedValue = document.querySelector(`${selector} .ng-value-label`);
                        if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                            console.log(`✓ Selection verified: "${expectedText}"`);
                            return true;
                        } else {
                            const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                            console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                            // Try alternative selection method if first attempt fails
                            if (attempt > 1) {
                                console.log('Trying alternative selection method...');
                                // Type the text to search for exact match
                                input.focus();
                                input.value = expectedText;
                                input.dispatchEvent(new Event('input', { bubbles: true }));
                                await new Promise(resolve => setTimeout(resolve, 500));

                                input.dispatchEvent(new KeyboardEvent('keydown', {
                                    key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                }));

                                await new Promise(resolve => setTimeout(resolve, 500));

                                // Verify again
                                const retrySelectedValue = document.querySelector(`${selector} .ng-value-label`);
                                if (retrySelectedValue && retrySelectedValue.textContent.trim() === expectedText) {
                                    console.log(`✓ Selection verified with search: "${expectedText}"`);
                                    return true;
                                }
                            }
                        }

                    } catch (error) {
                        console.log(`Error in attempt ${attempt}:`, error);
                    }

                    if (attempt < maxAttempts) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }

                console.log(`Failed to select "${expectedText}" after all attempts`);
                return false;
            }

            // Step 1: Click "Добавить" button
            console.log('Step 1: Clicking Добавить button');
            const addButton = document.querySelector('a.info__no-data-btn.link');
            if (addButton) {
                addButton.click();
                await new Promise(resolve => setTimeout(resolve, 1000));
            } else {
                console.log('Add button not found');
                return;
            }

            // Step 2: Select diagnostics result - "Дефект обнаружен"
            console.log('Step 2: Selecting diagnostics result');
            await selectAutocompleteWithVerification(
                'evo-autocomplete[formcontrolname="diagnosticsResult"]',
                'Дефект обнаружен'
            );

            // Step 3: Select component - "Модуль эквайринга"
            console.log('Step 3: Selecting component');
            await selectAutocompleteWithVerification(
                'evo-autocomplete[formcontrolname="componentId"]',
                'Модуль эквайринга'
            );

            // Step 4: Select defect - "Заблокирован Модуль эквайринга"
            console.log('Step 4: Selecting defect');
            await selectAutocompleteWithVerification(
                'evo-autocomplete[formcontrolname="defectId"]',
                'Заблокирован Модуль эквайринга'
            );

            // Step 5: Fill comment
            console.log('Step 5: Filling comment');
            const textarea = document.querySelector('evo-textarea[formcontrolname="comment"] textarea');
            if (textarea) {
                textarea.value = 'TAMPER';
                textarea.dispatchEvent(new Event('input', { bubbles: true }));
                await new Promise(resolve => setTimeout(resolve, 300));
            }

            // Step 6: Click Save button with retry logic
            console.log('Step 6: Clicking Save button');
            let saveAttempts = 0;
            const maxSaveAttempts = 3;

            while (saveAttempts < maxSaveAttempts) {
                saveAttempts++;

                const saveButton = Array.from(document.querySelectorAll('span.evo-button__content'))
                    .find(span => span.textContent.trim() === 'Сохранить')
                    ?.closest('button');

                if (saveButton && !saveButton.disabled) {
                    console.log(`Save button found and enabled! Clicking... (attempt ${saveAttempts})`);
                    saveButton.click();
                    break;
                } else if (saveButton) {
                    console.log(`Save button found but disabled (attempt ${saveAttempts})`);
                } else {
                    console.log(`Save button not found (attempt ${saveAttempts})`);
                }

                if (saveAttempts < maxSaveAttempts) {
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }

            console.log('=== Diagnostics form filling completed ===');

        } catch (error) {
            console.error('Error filling diagnostics form:', error);
        }
    }

    async function fillRepairForm() {
        try {
            console.log('=== Starting repair form fill ===');

            // Function to select autocomplete with exact text verification
            async function selectAutocompleteWithVerification(selector, expectedText, maxAttempts = 5) {
                for (let attempt = 1; attempt <= maxAttempts; attempt++) {
                    console.log(`Attempt ${attempt} to select: "${expectedText}"`);

                    try {
                        const input = document.querySelector(`${selector} input`);
                        if (!input) {
                            console.log(`Input not found for selector: ${selector}`);
                            await new Promise(resolve => setTimeout(resolve, 500));
                            continue;
                        }

                        // Clear any existing selection first
                        const clearBtn = document.querySelector(`${selector} .ng-value-icon`);
                        if (clearBtn) {
                            clearBtn.click();
                            await new Promise(resolve => setTimeout(resolve, 200));
                        }

                        input.focus();
                        input.click();

                        // Open dropdown
                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'ArrowDown', code: 'ArrowDown', keyCode: 40, which: 40, bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 300));

                        // Select with Enter
                        input.dispatchEvent(new KeyboardEvent('keydown', {
                            key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                        }));

                        await new Promise(resolve => setTimeout(resolve, 500));

                        // Verify exact text selection
                        const selectedValue = document.querySelector(`${selector} .ng-value-label`);
                        if (selectedValue && selectedValue.textContent.trim() === expectedText) {
                            console.log(`✓ Selection verified: "${expectedText}"`);
                            return true;
                        } else {
                            const actualText = selectedValue ? selectedValue.textContent.trim() : 'nothing selected';
                            console.log(`✗ Selection failed. Expected: "${expectedText}", Got: "${actualText}"`);

                            // Try alternative selection method if first attempt fails
                            if (attempt > 1) {
                                console.log('Trying alternative selection method...');
                                // Type the text to search for exact match
                                input.focus();
                                input.value = expectedText;
                                input.dispatchEvent(new Event('input', { bubbles: true }));
                                await new Promise(resolve => setTimeout(resolve, 500));

                                input.dispatchEvent(new KeyboardEvent('keydown', {
                                    key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true
                                }));

                                await new Promise(resolve => setTimeout(resolve, 500));

                                // Verify again
                                const retrySelectedValue = document.querySelector(`${selector} .ng-value-label`);
                                if (retrySelectedValue && retrySelectedValue.textContent.trim() === expectedText) {
                                    console.log(`✓ Selection verified with search: "${expectedText}"`);
                                    return true;
                                }
                            }
                        }

                    } catch (error) {
                        console.log(`Error in attempt ${attempt}:`, error);
                    }

                    if (attempt < maxAttempts) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }

                console.log(`Failed to select "${expectedText}" after all attempts`);
                return false;
            }

            // Step 1: Click "Добавить" button
            console.log('Step 1: Clicking Добавить button');
            const addButton = document.querySelector('a.info__no-data-btn.link');
            if (addButton) {
                addButton.click();
                await new Promise(resolve => setTimeout(resolve, 1000));
            } else {
                console.log('Add button not found');
                return;
            }

            // Step 2: Select sample work - "Разблокировка Модуля эквайринга"
            console.log('Step 2: Selecting sample work');
            await selectAutocompleteWithVerification(
                'evo-autocomplete[formcontrolname="sampleWorkId"]',
                'Разблокировка Модуля эквайринга'
            );

            // Step 3: Click Save button with retry logic
            console.log('Step 3: Clicking Save button');
            let saveAttempts = 0;
            const maxSaveAttempts = 3;

            while (saveAttempts < maxSaveAttempts) {
                saveAttempts++;

                const saveButton = Array.from(document.querySelectorAll('span.evo-button__content'))
                    .find(span => span.textContent.trim() === 'Сохранить')
                    ?.closest('button');

                if (saveButton && !saveButton.disabled) {
                    console.log(`Save button found and enabled! Clicking... (attempt ${saveAttempts})`);
                    saveButton.click();
                    break;
                } else if (saveButton) {
                    console.log(`Save button found but disabled (attempt ${saveAttempts})`);
                } else {
                    console.log(`Save button not found (attempt ${saveAttempts})`);
                }

                if (saveAttempts < maxSaveAttempts) {
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }

            console.log('=== Repair form filling completed ===');

        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillNextForm() {
        try {
            console.log('=== Starting Nexttt form fill ===');

            // Step 1: Click "Добавить" button
            console.log('Step 1: Clicking Подтвердить работы');

            let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить работы') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 300));


            // Step 3: Click Save button
            console.log('Step 3: Clicking Save button');


            console.log('=== Repair form filling completed ===');

        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillCheckPaymentForm() {
        try {
            console.log('Step 1: Clicking  Подтвердить оплату ');

            let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить оплату') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 300));
        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillZipRecivedForm() {
        try {
            // Step 1: Click "ЗИП получен" button
            console.log('Step 1: Clicking  ЗИП получен ');

            let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'ЗИП получен') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 300));
        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillworksDoneForm() {
        try {
            // Step 1: Click "ЗИП получен" button
            console.log('Step 1: Clicking  Работы выполнены ');

            let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Работы выполнены') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 300));
        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillfinishStepForm() {
        try {

            // Step 1: Fill comment
            console.log('Step 5: Filling comment');
            const textarea = document.querySelector('evo-textarea[formcontrolname="comment"] textarea');
            textarea.value = 'TAMPER';
            textarea.dispatchEvent(new Event('input', { bubbles: true }));

            await new Promise(resolve => setTimeout(resolve, 200));

            // Step 2: Click "Подтвердить" button
            console.log('Step 2: Clicking  Подтвердить ');

            let a = 0, i = setInterval(() => { a++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Подтвердить') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a}`), b.click(), clearInterval(i)) : b ? console.log(`Attempt ${a}: Button disabled`) : console.log(`Attempt ${a}: Button not found`), a >= 3 && (console.log('Done'), clearInterval(i)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 400));
        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }

    async function fillcloseStepForm() {
        try {
            console.log('=== Starting Детали заявки fill ===');

            // Step 1: Click "Разблокировать модуль эквайринга" link
            console.log('Step 1: Clicking Разблокировать модуль эквайринга');
            let a1 = 0, i1 = setInterval(() => { a1++; const l = document.querySelector('crm-asc-request-required-action-acquiring-unlock a.link.link-bold'); l && l.textContent.trim() === 'Разблокировать модуль эквайринга' ? (console.log(`Clicking on attempt ${a1}`), l.click(), clearInterval(i1)) : console.log(`Attempt ${a1}: Link not found`), a1 >= 3 && (console.log('Done'), clearInterval(i1)) }, 1000);

            await new Promise(resolve => setTimeout(resolve, 3000));

            // Step 2: Download
            console.log('Step 2: Clicking Скачать акт выполненных работ');
            let a2 = 0, i2 = setInterval(() => { a2++; const s = document.querySelectorAll('span.evo-icon-button__label'); let t = null; for (let e of s) e.textContent.includes('акт выполненных работ') && (t = e.closest('button')); t ? (console.log(`Clicking on attempt ${a2}`), t.click(), clearInterval(i2)) : console.log(`Attempt ${a2}: Button not found`), a2 >= 3 && (console.log('Done'), clearInterval(i2)) }, 500);

            await new Promise(resolve => setTimeout(resolve, 2000));

            // Step 3: Click "Закрыть заявку" button
            console.log('Step 3: Clicking Закрыть заявку');
            let a3 = 0, i3 = setInterval(() => { a3++; const s = document.querySelectorAll('button span.evo-button__content'); let b = null; for (let t of s) if (t.textContent.trim() === 'Закрыть заявку') { b = t.closest('button'); break } b && !b.disabled ? (console.log(`Clicking on attempt ${a3}`), b.click(), clearInterval(i3)) : b ? console.log(`Attempt ${a3}: Button disabled`) : console.log(`Attempt ${a3}: Button not found`), a3 >= 3 && (console.log('Done'), clearInterval(i3)) }, 500);

        } catch (error) {
            console.error('Error filling repair form:', error);
        }
    }


    document.querySelectorAll('.copy-button').forEach(button => {
        button.addEventListener('click', function () {
            const text = this.getAttribute('data-text');

            // Create a temporary textarea to copy the text
            const tempTextArea = document.createElement('textarea');
            tempTextArea.value = text;
            document.body.appendChild(tempTextArea);

            // Select and copy the text
            tempTextArea.select();
            document.execCommand('copy');

            // Remove the temporary textarea from the DOM
            document.body.removeChild(tempTextArea);

            // Display a success message
            const status = document.getElementById('status');
            status.textContent = "Текст скопирован в буфер обмена!";
            status.style.color = 'green';
        });
    });



});