(function ($) {
    const currencyMap = { 'USD': '$', 'EUR': '€', 'GBP': '£', 'TR': '₺' };
    /**
     * Init Functions
     */
    function flexyconsent_init() {
        $('body').addClass('flexyconsent');
    }
    /**
     * Start Page
     */
    function flexyconsent_startPage() {
        $('#continue').click(function () {
            $.ajax({
                url: flexyconsentData.endpoint + 'users',
                type: 'POST',
                data: JSON.stringify(
                    {
                        url: window.location.href,
                        type: 'cmp',
                        projectTypeId: 2,
                        source: 'wordpress'
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    response = response
                    if (response.statusCode == 0) {
                        var options = [];
                        options.push({ key: 'email', value: response.content.email });
                        options.push({ key: 'apiKey', value: response.content.apiKey });
                        options.push({ key: 'projectId', value: response.content.projectId });
                        // options.push({ key: 'script', value: response.content.pageCodeWithoutScript, decrypted: true });
                        options.push({ key: 'scriptSrc', value: response.content.pageCodeScriptUrl, decrypted: true });
                        options.push({ key: 'enabled', value: 'true' });
                        saveOptionsAndGoPage(options, "projectSettingsPage");
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    console.log(error);
                    flexyconsentResponse('alert-danger', error.statusText);
                }
            });
        });
    }

    /**
     * User Settings Page
     */
    function flexyconsent_userSettingsPage() {

        var userSettingsPage = $('#flexyconsent_user_settings_page');
        if (userSettingsPage.length > 0) {

            if (!isRealEmail())
                $('#deleteAccount').hide();

            $.ajax({
                url: flexyconsentData.endpoint + 'user/get',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    response = response
                    if (response.statusCode === 0) {
                        $('#email').text(isRealEmail() ? flexyconsentData.email : '-');
                        $('#full_name').text(response.fullName || '-');
                        $('#company_name').text(response.companyName || '-');
                        if (response.invoiceInfo) {
                            $('#invoice_info_col').show();
                            var invoiceInfo = response.invoiceInfo;       
                            if (!invoiceInfo.nameOnInvoice)
                                return;
                            $('#invoice_name').text(invoiceInfo.nameOnInvoice);
                            $('#account_type').text(invoiceInfo.business ? flexyconsentData.businessAccount : flexyconsentData.personalAccount);
                            $('#address').text(invoiceInfo.addressLine1 + " " + invoiceInfo.addressLine2);
                            $('#city').text(invoiceInfo.city);
                            $('#post_code').text(invoiceInfo.postCode);
                            $('#vat_number').text(invoiceInfo.vatNumber);

                            $('#country').text(flexyconsentData.loading);
                             $.ajax({
                                url: flexyconsentData.endpoint + 'countries',
                                type: 'POST',
                                data: JSON.stringify(
                                    {
                                        email: flexyconsentData.email,
                                        apiKey: flexyconsentData.apiKey
                                    }
                                ),
                                contentType: "application/json; charset=utf-8",
                                success: function (response) {
                                    if (response.statusCode === 0) {
                                        //response.countries
                                        var country = response.countries.find(function (country) {
                                            return country.id === invoiceInfo.countryId;
                                        });
                                        if (country)
                                            $('#country').text(country.name);
                                    } else {
                                        flexyconsentResponse('alert-danger', response.statusMessage);
                                    }
                                },
                                error: function (error) {
                                    flexyconsentResponse('alert-danger', error);
                                }
                            });
                        }

                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    flexyconsentResponse('alert-danger', error);
                }
            });

        }
    }
    /**
     * Update User Settings Page
     */
    function flexyconsent_updateUserSettingsPage() {
        var updateUserSettingsPage = $('#updateUserSettingsPage');

        if (updateUserSettingsPage.length > 0) {
            var emailInput = updateUserSettingsPage.find('#email');
            emailInput.val(isRealEmail() ? flexyconsentData.email : '');
            emailInput.prop('disabled', isRealEmail());
            $.ajax({
                url: flexyconsentData.endpoint + 'user/get',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    response = response
                    if (response.statusCode === 0) {
                        var invoiceInfo = response.invoiceInfo;
                        if (invoiceInfo) {
                            updateUserSettingsPage.find('#company-name').val(response.companyName);
                            updateUserSettingsPage.find('#full-name').val(response.fullName);
                            $('#business').prop('checked', invoiceInfo.business);
                            updateUserSettingsPage.find('#name-on-invoice').val(invoiceInfo.nameOnInvoice);
                            updateUserSettingsPage.find('#address-line-1').val(invoiceInfo.addressLine1);
                            updateUserSettingsPage.find('#address-line-2').val(invoiceInfo.addressLine2);
                            updateUserSettingsPage.find('#city').val(invoiceInfo.city);
                            updateUserSettingsPage.find('#postcode').val(invoiceInfo.postCode);
                            updateUserSettingsPage.find('#vatnumber').val(invoiceInfo.vatNumber);
                            updateUserSettingsPage.find('#id').val(invoiceInfo.id);
                            updateUserSettingsPage.find('#userId').val(invoiceInfo.userId);

                            $.ajax({
                                url: flexyconsentData.endpoint + 'countries',
                                type: 'POST',
                                data: JSON.stringify(
                                    {
                                        email: flexyconsentData.email,
                                        apiKey: flexyconsentData.apiKey
                                    }
                                ),
                                contentType: "application/json; charset=utf-8",
                                success: function (response) {
                                    if (response.statusCode === 0) {
                                        // var countriesBoxOptions = $('#countries').prop('options');
                                        // var selectedOption = countriesBoxOptions[1];
                                        // debugger;
                                        // response.countries.forEach(country => {
                                        //     if (selectedOption === undefined || country.id != selectedOption.value)
                                        //         countriesBoxOptions.add(new Option(country.name, country.id));
                                        // });

                                        const countryPicker = $('#countries')[0];
                                        response.countries.forEach(async function (country) {
                                            countryPicker.add(new Option(country.name, country.id));
                                        });
                                        countryPicker.value = invoiceInfo.countryId;
                                        countryPicker[0].style.display = 'none';
                                    } else {
                                        flexyconsentResponse('alert-danger', response.statusMessage);
                                    }
                                },
                                error: function (error) {
                                    flexyconsentResponse('alert-danger', error);
                                }
                            });

                            if (!isRealEmail() || invoiceInfo.nameOnInvoice === "" || invoiceInfo.addressLine1 === "" || invoiceInfo.city === "" || invoiceInfo.countryId === undefined || invoiceInfo.countryId === 0) {
                                flexyconsentResponseTop('alert-danger', flexyconsentData.enterUserInfoMessage);
                            }
                        }
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    flexyconsentResponse('alert-danger', error);
                }
            });

            /*$("#business").change(function() {  
                $('#company-name').prop('disabled', this.checked);
            });*/

            // $("#countries").focusin(function (e) {
            //     e.preventDefault();
            //     var countriesBoxOptions = $('#countries').prop('options');
            //     if (countriesBoxOptions.length > 2) return;
            //     $.ajax({
            //         url: flexyconsentData.endpoint + 'countries',
            //         type: 'POST',
            //         data: JSON.stringify(
            //             {
            //                 email: flexyconsentData.email,
            //                 apiKey: flexyconsentData.apiKey
            //             }
            //         ),
            //         contentType: "application/json; charset=utf-8",
            //         success: function (response) {
            //             if (response.statusCode === 0) {
            //                 var selectedOption = countriesBoxOptions[1];
            //                 // if (selectedOption !== undefined)
            //                 //countriesBoxOptions[0].style.display = 'none';
            //                 response.countries.forEach(country => {
            //                     if (selectedOption === undefined || country.id != selectedOption.value)
            //                         countriesBoxOptions.add(new Option(country.name, country.id));
            //                 });
            //             } else {
            //                 flexyconsentResponse('alert-danger', response.statusMessage);
            //             }
            //         },
            //         error: function (error) {
            //             flexyconsentResponse('alert-danger', error);
            //         }
            //     });
            // });

            updateUserSettingsPage.validate(
                {
                    rules: {
                        'email': {
                            required: true
                        },
                        'full-name': {
                            required: true
                        },
                        'name-on-invoice': {
                            required: true
                        },
                        'address-line-1': {
                            required: true
                        },
                        'city': {
                            required: true
                        },
                        'country': {
                            required: true
                        }
                    }
                });
            updateUserSettingsPage.on('submit', function (e) {
                if ($(this).valid()) {
                    e.preventDefault();

                    var updatedEmail = emailInput.val().trim();
                    var invoiceInfo = {
                        id: updateUserSettingsPage.find('#id').val(),
                        business: ($('#business').prop("checked")),
                        nameOnInvoice: updateUserSettingsPage.find('#name-on-invoice').val().trim(),
                        addressLine1: updateUserSettingsPage.find('#address-line-1').val().trim(),
                        addressLine2: updateUserSettingsPage.find('#address-line-2').val().trim(),
                        city: updateUserSettingsPage.find('#city').val().trim(),
                        country: { id: Number(updateUserSettingsPage.find('#countries').val()) },
                        postCode: updateUserSettingsPage.find('#postcode').val().trim(),
                        vatNumber: updateUserSettingsPage.find('#vatnumber').val().trim()
                    }

                    $.ajax({
                        url: flexyconsentData.endpoint + 'user/update',
                        type: 'POST',
                        data: JSON.stringify(
                            {
                                email: flexyconsentData.email,
                                apiKey: flexyconsentData.apiKey,
                                updatedEmail: isRealEmail() ? null : updatedEmail,
                                companyName: updateUserSettingsPage.find('#company-name').val().trim(),
                                fullName: updateUserSettingsPage.find('#full-name').val().trim(),
                                invoiceInfo: invoiceInfo,

                                domainName: window.location.hostname,
                                serviceId: 2
                            }
                        ),
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            response = response
                            if (response.statusCode === 0) {
                                if (isRealEmail()) {
                                    flexyconsentGoPage('userSettingsPage');
                                } else {
                                    var options = [];
                                    options.push({ key: 'email', value: updatedEmail });
                                    options.push({ key: 'apiKey', value: response.apiKey });
                                    saveOptionsAndGoPage(options, "userSettingsPage");
                                }
                            } else if (flexyconsentData.responseMessages[response.statusCode]) {
                                flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                            } else {
                                flexyconsentResponse('alert-danger', response.statusMessage);
                            }
                        },
                        error: function (error) {
                            flexyconsentResponse('alert-danger', error);
                        }
                    });
                }
            })
        }
    }
    /**
     * Update Email Page
     */
    function flexyconsent_updateEmailPage() {
        var updateEmailPage = $("#updateEmailPage");
        if (updateEmailPage.length > 0) {
            updateEmailPage.validate(
                {
                    rules: {
                        'new-email': {
                            required: true,
                            email: true
                        }
                    }
                });
            updateEmailPage.on('submit', function (e) {
                if ($(this).valid()) {
                    e.preventDefault();
                    var updatedEmail = $('#flexyconsent-new-mail-address').val();
                    $.ajax({
                        url: flexyconsentData.endpoint + 'user/updateemail',
                        type: 'POST',
                        data: JSON.stringify(
                            {
                                email: flexyconsentData.email,
                                apiKey: flexyconsentData.apiKey,
                                updatedEmail: updatedEmail,
                                projectType: 2
                            }
                        ),
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            response = response
                            if (response.statusCode === 7 || response.statusCode === 0) {
                                var options = [];
                                var nextPage = '';
                                if (response.statusCode === 7) {
                                    nextPage = 'updateEmailValidateKeyPage&email=' + updatedEmail;
                                    // nextPage =  wp_nonce_url($nextPage, 'verify_email_action' );
                                } else if (response.statusCode === 0) {
                                    nextPage = 'userSettingsPage';
                                    // options.push({ option: "flexyconsent_settings_startPage", key: 'flexyconsent_mail_address', value: updatedEmail })
                                    // options.push({ option: "flexyconsent_settings_validateKeyPage", key: 'flexyconsent_api_key', value: response.apiKey })
                                    options.push({ key: 'email', value: updatedEmail });
                                    options.push({ key: 'apiKey', value: response.apiKey });
                                }
                                $.ajax({
                                    url: flexyconsentData.resturl + 'flexyconsent/v1/option',
                                    type: 'POST',
                                    beforeSend: function (xhr) {
                                        xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
                                    },
                                    data: jQuery.param(
                                        {
                                            updates: options
                                        }
                                    ),
                                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                                    success: function (response) {
                                        // flexyconsentResponse('alert-success', response.statusMessage);
                                        flexyconsentGoPage(nextPage);
                                    },
                                    error: function (error) {
                                        console.log(error);
                                        if (error.responseText) {
                                            error = error.responseText;
                                        }
                                        flexyconsentResponse('alert-danger', error);
                                    }
                                });
                            } else if (flexyconsentData.responseMessages[response.statusCode]) {
                                flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                            } else {
                                flexyconsentResponse('alert-danger', response.statusMessage);
                            }
                        },
                        error: function (error) {
                            flexyconsentResponse('alert-danger', error);
                            console.log(error);
                        }
                    });
                }
            })
        }
    }
    /**
     * Update Email Validate Key Page
     */
    function flexyconsent_updateEmailValidateKeyPage() {
        var updateEmailValidateKeyPage = $("#updateEmailValidateKeyPage");
        if (updateEmailValidateKeyPage.length > 0) {
            updateEmailValidateKeyPage.validate(
                {
                    rules: {
                        'new-apikey': {
                            required: true,
                        }
                    }
                });
            updateEmailValidateKeyPage.on('submit', function (e) {
                if ($(this).valid()) {
                    e.preventDefault();
                    var updatedKey = $('#new-apikey').val();
                    var updatedEmail = decodeURIComponent(getParameterByName('email'));
                    $.ajax({
                        url: flexyconsentData.endpoint + 'user/updateemail',
                        type: 'POST',
                        data: JSON.stringify(
                            {
                                email: flexyconsentData.email,
                                apiKey: flexyconsentData.apiKey,
                                updatedEmail: updatedEmail,
                                updatedKey: updatedKey,
                            }
                        ),
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            response = response
                            if (response.statusCode === 7 || response.statusCode === 0) {
                                var options = [];
                                var nextPage = '';
                                if (response.statusCode === 7) {
                                    nextPage = 'updateEmailValidateKeyPage&email=' + updatedEmail;
                                } else if (response.statusCode === 0) {
                                    nextPage = 'dashboardPage';
                                    options.push({ key: 'email', value: updatedEmail });
                                    options.push({ key: 'apiKey', value: updatedKey });
                                }
                                $.ajax({
                                    url: flexyconsentData.resturl + 'flexyconsent/v1/option',
                                    type: 'POST',
                                    beforeSend: function (xhr) {
                                        xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
                                    },
                                    data: jQuery.param(
                                        {
                                            updates: options
                                        }
                                    ),
                                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                                    success: function (response) {
                                        // flexyconsentResponse('alert-success', response.statusMessage);
                                        flexyconsentGoPage(nextPage);
                                    },
                                    error: function (error) {
                                        console.log(error);
                                        if (error.responseText) {
                                            error = error.responseText;
                                        }
                                        flexyconsentResponse('alert-danger', error);
                                    }
                                });
                            }
                        },
                        error: function (error) {
                            flexyconsentResponse('alert-danger', error);
                            console.log(error);
                        }
                    });
                }
            })
        }
    }
    /**
     * Delete Account Page
     */
    function flexyconsent_deleteAccountPage() {
        var deleteAccountPage = $("#deleteAccountPage");
        if (deleteAccountPage.length > 0) {
            deleteAccountPage.validate(
                {
                    rules: {
                        'email-address': {
                            required: true,
                            email: true,
                            equalTo: '#email-address-validate'
                        }
                    },
                    messages: {
                        'email-address': {
                            equalTo: flexyconsentData.wrongEmailAddress
                        }
                    }
                }
            );
        }
        deleteAccountPage.on('submit', function (e) {
            if ($(this).valid()) {
                e.preventDefault();
                var email = $('#email-address').val();
                $.ajax({
                    url: flexyconsentData.endpoint + 'user/delete',
                    type: 'POST',
                    data: JSON.stringify(
                        {
                            email: email,
                            apiKey: flexyconsentData.apiKey,
                            projectId: flexyconsentData.projectId,
                            serviceId: 2
                        }
                    ),
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        response = response
                        let userMessage = flexyconsentData.responseMessages[response.statusCode];
                        if (userMessage)
                            userMessage = flexyconsent_convert_message(userMessage, response);

                        if (response.statusCode === 0 || response.statusCode === 25) {
                            var options = [];
                            options.push({ key: 'email', value: '' });
                            options.push({ key: 'apiKey', value: '' });
                            options.push({ key: 'projectId', value: '' });
                            options.push({ key: 'script', value: '' });
                            saveOptionsAndGoPage(options, 'startPage');
                        } else if (response.statusCode === 23) {
                            let url = flexyconsentReturnPage('subscriptionPage');
                            flexyconsentResponse('alert-warning', userMessage, url, flexyconsentData.subscription);
                        }
                        // else if (response.statusCode === 24 || response.statusCode === 25) {                                                      
                        //     //flexyconsentResponse('alert-warning', userMessage);
                        //     let url = flexyconsentData.endpoint.replace('/rest', '');
                        //     let hostName = flexyconsentData.endpoint.split('/')[2];
                        //     flexyconsentResponse('alert-warning', userMessage, url, hostName);
                        // } 
                        else if (response.statusCode === 24) {
                            //flexyconsentResponse('alert-warning', userMessage);
                            let url = flexyconsentData.endpoint.replace('/rest', '');
                            let hostName = flexyconsentData.endpoint.split('/')[2];
                            flexyconsentResponse('alert-warning', userMessage, url, hostName);
                        } else if (flexyconsentData.responseMessages[response.statusCode]) {
                            flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                        } else {
                            flexyconsentResponse('alert-danger', response.statusMessage);
                        }
                    },
                    error: function (error) {
                        flexyconsentResponse('alert-danger', error);
                        console.log(error);
                    }
                });
            }
            else {
                console.log('not valid!');
            }
        })
    }

    /**
     * Dashboard Page
     */
    function flexyconsent_dashboardPage() {
        var dashboardPage = $('#dashboardPage');
        if (dashboardPage.length === 0)
            return;

        const startDate = moment().subtract(29, 'days'), endDate = moment();

        const datePickerTxt = $('#date_range_picker span');
        const dataRangePicker = $('#date_range_picker');
        dataRangePicker.daterangepicker({
            opens: 'left',
            startDate: startDate,
            endDate: endDate,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'This Week': [moment().startOf('week'), moment()],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment()],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Year': [moment().startOf('year'), moment()],
                'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')],
                'Last 365 Days': [moment().subtract(364, 'days'), moment()],
            }
        }, function (start, end, label) {
            // console.log(label + ": " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            datePickerTxt.html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            loadDataStats(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
        });

        datePickerTxt.html(startDate.format('MMMM D, YYYY') + ' - ' + endDate.format('MMMM D, YYYY'));
        loadDataStats(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD'));


        function loadDataStats(startDate, endDate) {
            $.ajax({
                url: flexyconsentData.endpoint + 'cmp/data-stats',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectId: Number(flexyconsentData.projectId),
                        startDate: startDate,
                        endDate: endDate
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    response = response
                    if (response.userMessage) {
                        let responseUserMessage = flexyconsentData.userMessages[response.userMessage.messageId];
                        responseUserMessage = (responseUserMessage) ? responseUserMessage : response.userMessage.messageContent + '!';
                        flexyconsentResponseTop('alert-danger', responseUserMessage);
                    }
                    // var orderedStats = {};
                    if (response.statusCode === 0) {
                        const firstKey = Object.keys(response.Projects)[0];
                        const projectStats = response.Projects[firstKey];
                        // var stats = response.stats;
                        if (projectStats) {
                            statsOutput = '';
                            // $.each(response.stats, function (groupKey, groupValue) {
                            //     $.each(groupValue, function (key, value) {
                            //         // debugger;
                            //         // const map = new Map(Object.entries(groupValue));
                            //         let count = Object.keys(groupValue).length;
                            //         var width = 12 / count;
                            //         var color = 'stat-box-color' + count;
                            //         var fontSizeStyle = '';
                            //         if (value > 10000 && count > 5)
                            //             fontSizeStyle = ' style="font-size:32px"';

                            //         statsOutput += `<div class="col-lg-${width} my-2">
                            //                             <div class="stat-box ${color} d-flex flex-column flex-wrap">
                            //                                 <span class="key">${flexyconsentData[key]}</span>
                            //                                 <span class="value"${fontSizeStyle}>${value}</span>
                            //                             </div>
                            //                         </div>`;
                            //     });
                            // });
                            // dashboardPage.find('.row').html(statsOutput);

                            const stats = {
                                visitsTotal: {
                                    visitsTotal: projectStats['visitsTotal'].Total
                                },
                                visitorVisits: {
                                    visitsNewClient: projectStats['visitsNewClient'].Total,
                                    visitsExistingClient: projectStats['visitsExistingClient'].Total,
                                },
                                visitorConsentState: {
                                    visitsWithConsent: projectStats['visitsWithConsent'].Total,
                                    visitsWithoutConsent: projectStats['visitsWithoutConsent'].Total,
                                    visitsNoPreference: projectStats['visitsNoPreference'].Total,
                                },
                                pageViews: {
                                    pageViewsWithNoPreference: projectStats['pageViewsWithNoPreference'].Total,
                                    pageViewsWithConsent: projectStats['pageViewsWithConsent'].Total,
                                    pageViewsWithoutConsent: projectStats['pageViewsWithoutConsent'].Total,
                                    pageViewsTotal: projectStats['pageViewsTotal'].Total,
                                },
                                visitorPreferences: {
                                    consentNotRequired: projectStats['notRequired'].Total,
                                    consentRequests: projectStats['consentRequests'].Total,
                                    consentAccepts: projectStats['consentAccepts'].Total,
                                    consentRejects: projectStats['consentRejects'].Total,
                                    consentPartiallyAccepts: projectStats['consentPartiallyAccepts'].Total,
                                    // cancels: projectStats['consentCancels'].Total,
                                },
                            };

                            $('#flexyconsent_stats').html('');
                            for (const groupKey in stats) {
                                const groupValue = stats[groupKey];
                                const div1 = document.createElement('div');
                                div1.classList.add('row');
                                $('#flexyconsent_stats').append(div1);
                                let count = Object.keys(groupValue).length;
                                // const width = 12 / count;
                                const widthPercent = 100 / count;
                                const borderColor = 'border-color' + count;

                                for (const key in groupValue) {
                                    let value = groupValue[key];

                                    const div2 = document.createElement('div');
                                    // div2.classList.add('col-lg-' + width, 'px-2', 'py-2');
                                    div2.classList.add('px-2', 'py-2');
                                    div2.style.width = widthPercent + '%';
                                    div1.appendChild(div2);

                                    const card = document.createElement('div');
                                    card.classList.add('card', 'dashboard-card', borderColor);
                                    div2.appendChild(card);

                                    const div3 = document.createElement('div');
                                    div3.classList.add('stat-box', 'd-flex', 'flex-column', 'flex-wrap');
                                    card.appendChild(div3);

                                    const spanTitle = document.createElement('span');
                                    spanTitle.classList.add('title');
                                    // spanTitle.innerText = keyToTitle(key);
                                    // if(flexyconsentData[key] == undefined)
                                    //     debugger;
                                    // else
                                    spanTitle.innerText = flexyconsentData[key];
                                    div3.appendChild(spanTitle);

                                    const div4 = document.createElement('div');
                                    div4.classList.add('d-flex', 'justify-content-center');
                                    div3.appendChild(div4);

                                    const [val, ending, color] = numberToText(value);

                                    const spanValue = document.createElement('span');
                                    spanValue.classList.add('value');
                                    spanValue.innerText = val;
                                    div4.appendChild(spanValue);

                                    const spanValue2 = document.createElement('span');
                                    spanValue2.classList.add('value');
                                    if (color.length > 0)
                                        spanValue2.classList.add(color);
                                    spanValue2.innerText = ending;

                                    div4.appendChild(spanValue2);
                                }
                            }
                        }
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    flexyconsentResponse('alert-danger', error);
                    console.log(error);
                }
            });
        }


        const numberToText = num => {
            num = num.toString().replace(/[^0-9.]/g, '');
            if (num < 1000)
                return [num, "", ""];

            let si = [
                //		{ v: 1E3, s: "K", c: "text-success" },
                //		{ v: 1E6, s: "M", c: "text-warning" },
                //		{ v: 1E9, s: "B", c: "text-danger" },
                //		{ v: 1E12, s: "T", c: "text-danger" },
                //		{ v: 1E15, s: "P", c: "text-danger" },
                //		{ v: 1E18, s: "E", c: "text-danger" }
                { v: 1E3, s: "k", c: "text-success" },
                { v: 1E6, s: "m", c: "text-warning" },
                { v: 1E9, s: "b", c: "text-danger" },
                { v: 1E12, s: "T", c: "text-danger" },
                { v: 1E15, s: "P", c: "text-danger" },
                { v: 1E18, s: "E", c: "text-danger" }
            ];
            let index;
            for (index = si.length - 1; index > 0; index--) {
                if (num >= si[index].v) {
                    break;
                }
            }

            //	return (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[index].s;

            const value = (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1");
            const ending = si[index].s;
            const color = si[index].c;
            return [value, ending, color];
        };

        // visitsTotal -> Visits Total
        function keyToTitle(key) {
            let title = "";
            for (let i = 0; i < key.length; i++) {
                if (i === 0)
                    title = key[0].toUpperCase();
                else if (key[i] === key[i].toUpperCase())
                    title += " " + key[i];
                else
                    title += key[i];
            }
            return title;
        }
    }

    /**
     * Project Settings Page
     */
    function flexyconsent_projectSettingsPage() {
        var projectSettingsPage = $("#projectSettingsPage");
        if (projectSettingsPage.length === 0)
            return;

        const enabledCheckbox = document.getElementById('consent_enabled');

        //load project settings
        $.ajax({
            url: flexyconsentData.endpoint + 'project/get',
            type: 'POST',
            data: JSON.stringify(
                {
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                    project: flexyconsentData.projectId
                }
            ),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                if (response.statusCode === 0) {
                    if (response.pageCodeScriptUrl) {
                        if (flexyconsentData.projectScriptSrc !== response.pageCodeScriptUrl) {
                            saveOption('scriptSrc', response.pageCodeScriptUrl);
                        }
                    } else {
                        console.log('No page code!!');
                    }

                    const config = response.config;
                    $('#consent_enabled').prop('checked', config.cmpEnabled);
                    // $('#other_settings').collapse(response.config.cmpEnabled ? 'show' : 'hide');
                    // $('#other_settings').addClass(response.config.cmpEnabled ? 'show' : 'hide');
                    // if (!response.config.cmpEnabled) 
                    //     $('#other_settings').collapse('hide');
                    enabledCheckbox.dispatchEvent(new Event('change'));

                    // $('#name').val(response.project.projectName);
                    $('#domains').val(config.whiteListDomains.join('\n'));
                    $('#cookie_policy').val(config.cookiePolicyUrl);
                    $('#privacy_policy').val(config.privacyPolicyUrl);

                    const langSelector = document.getElementById('select_language');
                    response.availableLanguages.forEach(lang => {
                        const option = document.createElement('option');
                        option.value = lang.shortCode;
                        option.text = lang.name;

                        if (lang.shortCode === config.primaryLanguage) {
                            option.selected = "selected";
                            option.checked = true;
                            langSelector.value = option.shortCode;
                        }
                        langSelector.appendChild(option);
                    });
                    $('#use_client_info_for_language').prop('checked', config.useClientLanguage);

                    $('#advertising_eu').prop('checked', config.cmpAdvertisingSettings.eu);
                    $('#advertising_us').prop('checked', config.cmpAdvertisingSettings.us);
                    $('#advertising_ca').prop('checked', config.cmpAdvertisingSettings.ca);
                    $('#advertising_others').prop('checked', config.cmpAdvertisingSettings.others);

                    $('#google_consent_mode').prop('checked', config.cmpConsentModeV2.enabled);
                    $('#gcm_url_passthrough').prop('checked', config.cmpConsentModeV2.urlPassthrough);
                    $('#gcm_ads_data_redaction').prop('checked', config.cmpConsentModeV2.adsDataRedaction);
                    $('#gcm_google_signals').prop('checked', config.cmpConsentModeV2.googleSignals);
                    $('#gcm_ad_personalization_signals').prop('checked', config.cmpConsentModeV2.adPersonalizationSignals);
                    $('#gcm_restricted_data_processing').prop('checked', config.cmpConsentModeV2.restrictedDataProcessing);
                    $('#gcm_send_page_view').val(config.cmpConsentModeV2.sendPageView.toString());
                    $('#gcm_wait_for_update').val(config.cmpConsentModeV2.waitForUpdate);

                    // $('#gcm_settings').collapse(config.cmpConsentModeV2.enabled ? 'show' : 'hide');

                    const editorSettings = response.subscriptions[0].editorSettings;
                    if (editorSettings['ml'] === false) {
                        langSelector.disabled = true;
                        $('#use_client_info_for_language').prop('disabled', true);
                        langSelector.previousElementSibling.style.color = 'gray';
                    }
                    if (editorSettings['gcm2'] === false) {
                        $('#gcm_settings').collapse('hide');
                        $('#google_consent_mode').prop('disabled', true);
                    } else {
                        $('#google_consent_mode').on('change', function (event) {
                            $('#gcm_settings').collapse(event.target.checked ? 'show' : 'hide');
                        });
                        $('#gcm_settings').collapse(config.cmpConsentModeV2.enabled ? 'show' : 'hide');
                    }
                    if (editorSettings['ab'] === false) {
                        $('#auto_blocker').prop('disabled', true);
                    }

                    $('#auto_blocker').prop('checked', config.cmpAutoBlockerEnabled === "1");
                    $('#privacy_button').prop('checked', config.cmpDisplayConsentButton);

                    const customCss = config.customCss;
                    layoutPropertiesEnabled.checked = customCss.enabled;
                    $('#font_family').val(customCss.fontFamily || "");
                    $('#font_size').val(customCss.fontSize || "");
                    $('#custom_css').val(customCss.css || "");
                    $('#custom_logo').val(customCss.customLogo || "");

                    const src = 'https://panel.flexyconsent.com/consent/panel/views/consent_preview.jsp?pid=' + flexyconsentData.projectId + '&key=' + config.accessKey + '&rand=' + Math.random();
                    $('#preview_frame').attr('src', src);
                } else if (flexyconsentData.responseMessages[response.statusCode]) {
                    flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                } else {
                    flexyconsentResponse('alert-danger', response.statusMessage);
                }
            },
            error: function (error) {
                flexyconsentResponse('alert-danger', error);
                console.log(error);
            }
        });

        enabledCheckbox.addEventListener('change', function () {
            const statusElement = document.getElementById('status_text');
            if (enabledCheckbox.checked) {
                statusElement.classList.remove('text-danger');
                statusElement.classList.add('text-success');
                statusElement.innerText = flexyconsentData.enabledText;
                $('#other_settings').collapse('show');
            } else {
                statusElement.classList.remove('text-success');
                statusElement.classList.add('text-danger');
                statusElement.innerText = flexyconsentData.disabledText;
                $('#other_settings').collapse('hide');
            }
        });

        $('#trigger_customization').on('click', async function (event) {
            event.preventDefault();
            const collapseElement = this.nextElementSibling;
            var chevronRight = $('#trigger_customization').find('.fa-angle-right')[0];
            if (collapseElement.classList.contains('show')) {
                $(collapseElement).collapse('hide');
                chevronRight.style.transform = 'rotate(0deg)';
            } else {
                $(collapseElement).collapse('show');
                chevronRight.style.transform = 'rotate(90deg)';
            }
        });


        const layoutPropertiesEnabled = document.getElementById('layout_properties_enabled');
        layoutPropertiesEnabled.addEventListener('change', function () {
            const expandableContainer = document.getElementById('layout_properties_expandable');
            for (const layoutPropertyContainer of expandableContainer.children) {
                for (const layoutPropertyElement of layoutPropertyContainer.children) {
                    layoutPropertyElement.disabled = !layoutPropertiesEnabled.checked;
                    if (layoutPropertiesEnabled.checked)
                        layoutPropertyElement.classList.remove("text-muted");
                    else
                        layoutPropertyElement.classList.add("text-muted");
                }
            }
        });

        async function previewChanged(event) {
            const cmpDisplayPrivacyButton = document.getElementById('privacy_button').checked;

            const previewSettings = {
                useClientLanguage: document.getElementById('use_client_info_for_language').checked,
                primaryLanguage: document.getElementById('select_language').value,
                cmpConsentModeV2: {
                    enabled: document.getElementById('google_consent_mode').checked,
                    urlPassthrough: document.getElementById('gcm_url_passthrough').checked,
                    adsDataRedaction: document.getElementById('gcm_ads_data_redaction').checked,
                    googleSignals: document.getElementById('gcm_google_signals').checked,
                    adPersonalizationSignals: document.getElementById('gcm_ad_personalization_signals').checked,
                    restrictedDataProcessing: document.getElementById('gcm_restricted_data_processing').checked,
                    sendPageView: document.getElementById('gcm_send_page_view').value,
                    waitForUpdate: document.getElementById('gcm_wait_for_update').value
                },
                cmpAutoBlockerEnabled: document.getElementById('auto_blocker').checked,
                cmpDisplayConsentButton: cmpDisplayPrivacyButton,

                enabled: document.getElementById('layout_properties_enabled').checked,
                fontFamily: document.getElementById('font_family').value,
                fontSize: document.getElementById('font_size').value,
                css: document.getElementById('custom_css').value,
                customLogo: document.getElementById('custom_logo').value
            };

            $.ajax({
                url: flexyconsentData.endpoint + 'project/preview',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        project: Number(flexyconsentData.projectId),
                        previewSettings: previewSettings
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        const previewFrame = document.getElementById('preview_frame');
                        previewFrame.contentWindow.location.reload();
                    }
                },
                error: function (error) {
                    flexyconsentResponse('alert-danger', error);
                    console.log(error);
                }
            });
        }

        layoutPropertiesEnabled.addEventListener('change', previewChanged);
        $('#font_family').on('change', previewChanged);
        $('#font_size').on('change', previewChanged);
        $('#custom_css').on('change', previewChanged);
        $('#custom_logo').on('change', previewChanged);


        projectSettingsPage.on('submit', function (e) {
            if ($(this).valid()) {
                e.preventDefault();

                // const name = $('#name').val().trim();
                const domains = $('#domains').val().trim().split(/[\s\n, ]+/);
                const cookiePolicyUrl = $('#cookie_policy').val().trim();
                const privacyPolicyUrl = $('#privacy_policy').val().trim();
                const cmpEnabled = ($('#consent_enabled').prop("checked"));
                const selectedLanguage = $('#select_language').val();
                const useClientLanguage = $('#use_client_info_for_language').prop('checked');

                $.ajax({
                    url: flexyconsentData.endpoint + 'project/config',
                    type: 'POST',
                    data: JSON.stringify(
                        {
                            email: flexyconsentData.email,
                            apiKey: flexyconsentData.apiKey,
                            project: Number(flexyconsentData.projectId),
                            source: 'wordpress',

                            // projectName: name,
                            whiteListDomains: (domains) ? domains : [],
                            cookiePolicyUrl: cookiePolicyUrl,
                            privacyPolicyUrl: privacyPolicyUrl,
                            cmpEnabled: cmpEnabled,
                            primaryLanguage: selectedLanguage,
                            useClientLanguage: useClientLanguage,
                            cmpAdvertisingSettings: {
                                eu: $('#advertising_eu').prop('checked') ? 1 : 0,
                                us: $('#advertising_us').prop('checked') ? 1 : 0,
                                ca: $('#advertising_ca').prop('checked') ? 1 : 0,
                                others: $('#advertising_others').prop('checked') ? 1 : 0
                            },
                            cmpConsentModeV2: {
                                enabled: $('#google_consent_mode').prop('checked'),
                                urlPassthrough: $('#gcm_url_passthrough').prop('checked'),
                                adsDataRedaction: $('#gcm_ads_data_redaction').prop('checked'),
                                googleSignals: $('#gcm_google_signals').prop('checked'),
                                adPersonalizationSignals: $('#gcm_ad_personalization_signals').prop('checked'),
                                restrictedDataProcessing: $('#gcm_restricted_data_processing').prop('checked'),
                                sendPageView: $('#gcm_send_page_view').val(),
                                waitForUpdate: $('#gcm_wait_for_update').val(),
                            },
                            cmpAutoBlockerEnabled: $('#auto_blocker').prop('checked'),
                            cmpDisplayConsentButton: $('#privacy_button').prop('checked'),
                            customCss: {
                                enabled: $('#layout_properties_enabled').prop('checked'),
                                fontFamily: $('#font_family').val(),
                                fontSize: $('#font_size').val(),
                                css: $('#custom_css').val(),
                                customLogo: $('#custom_logo').val()
                            }
                        }
                    ),
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        if (response.statusCode == 0) {
                            const options = [
                                { key: 'enabled', value: cmpEnabled },
                            ];
                            saveOptionsAndGoPage(options, 'dashboardPage');
                        } else if (flexyconsentData.responseMessages[response.statusCode]) {
                            flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                        } else {
                            flexyconsentResponse('alert-danger', response.statusMessage);
                        }
                    },
                    error: function (error) {
                        console.log(error);
                        flexyconsentResponse('alert-danger', error);
                    }
                });
            }
        })
    }

    /**
     * Subscription Page
     */

    function flexyconsent_subscriptionPage() {
        var subscriptionPage = $("#subscriptionPage");
        if (subscriptionPage.length === 0)
            return;

        const paymentState = getParameterByName('state');
        if (paymentState !== null) {
            if (paymentState === "1") {
                flexyconsentResponseTop('alert-success', 'Payment successful');
            } else if (paymentState === "0") {
                flexyconsentResponseTop('alert-danger', 'Payment failed');
            } else if (paymentState === "2") {
                flexyconsentResponseTop('alert-warning', 'Payment expired');
            }
        }

        var pageViewExceededObj = JSON.parse(localStorage.getItem('spve'));
        if (!pageViewExceededObj || new Date() - new Date(pageViewExceededObj.dt) > 60 * 60 * 1000) {//1 hour
            $.ajax({
                url: flexyconsentData.endpoint + 'package/get-exceeded-subscriptions',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        pageViewExceededObj = { dt: new Date(), s: response.content };
                        localStorage.setItem('spve', JSON.stringify(pageViewExceededObj));
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponseTop('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponseTop('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    console.log(error);
                    flexyconsentResponseTop('alert-danger', error);
                }
            });
        }
        const modal = document.getElementById('modal_cancel_subscription');

        $.ajax({
            url: flexyconsentData.endpoint + 'package/list',
            type: 'POST',
            data: JSON.stringify(
                {
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                    project: Number(flexyconsentData.projectId),
                    projectTypeId: 2
                }
            ),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                if (response.statusCode === 0) {
                    const subscriptionsElement = document.getElementById('flexyconsent-subscriptions');
                    const subscriptionsContainer = subscriptionsElement.parentElement;
                    subscriptionsContainer.classList.remove('d-none');

                    if (!response.subscriptions) {
                        subscriptionsElement.innerHTML = '<div class="alert alert-info">No subscriptions available.</div>';
                    }

                    const subscriptions = response.subscriptions;
                    const packages = response.packages;
                    const domains = response.domains;

                    const trialSubscription = subscriptions.find(s => s.type === "Trial" && s.state === "1");
                    if (trialSubscription) {
                        subscriptions.splice(subscriptions.indexOf(trialSubscription), 1);
                        subscriptions.unshift(trialSubscription);
                    }

                    const freeSubscription = subscriptions.find(s => s.type === "Free" && s.state === "1");
                    if (freeSubscription) {
                        subscriptions.splice(subscriptions.indexOf(freeSubscription), 1);
                        subscriptions.unshift(freeSubscription);
                    }

                    subscriptions?.forEach(subscription => {
                        if (subscription.state === "0")
                            return;

                        const plan = packages.find(p => p.id === subscription.typeId);
                        if (plan.price > 0 && new Date(subscription.end) < new Date())
                            return;
                        if (subscription.type === "Trial" && new Date(subscription.end) < new Date())
                            return;

                        if (subscriptionsElement.children.length > 0) {
                            const lineDivider = document.createElement('hr');
                            lineDivider.classList.add('my-3');
                            subscriptionsElement.appendChild(lineDivider);
                        }
                        addSubscriptionElement(subscriptionsElement, subscription, packages, subscriptions.length, domains);
                    });

                    const btnSave = document.getElementById('btn_save');
                    btnSave.addEventListener('click', async (event) => {
                        event.preventDefault();
                        const selectedWebsites = {};
                        domains.forEach(domain => {
                            selectedWebsites[domain.id] = 0;
                        });
                        const websiteSelectors = subscriptionsElement.querySelectorAll('select[id^="websites_"]');
                        const websiteSelectorsKeys = Object.keys(websiteSelectors);
                        for (let i = 0; i < websiteSelectorsKeys.length; i++) {
                            const websiteSelector = websiteSelectors[websiteSelectorsKeys[i]];
                            const subscriptionId = parseInt(websiteSelector.id.split('_')[1]);
                            const selectedWebsiteId = parseInt(websiteSelector.value);
                            if (selectedWebsiteId > 0) {
                                if (selectedWebsites[selectedWebsiteId] > 0) {
                                    alert(flexyconsentData['websiteAlreadySelected']);
                                    return;
                                } else
                                    selectedWebsites[selectedWebsiteId] = subscriptionId;
                            }
                        }

                        $.ajax({
                            url: flexyconsentData.endpoint + 'package/update',
                            type: 'POST',
                            data: JSON.stringify({
                                email: flexyconsentData.email,
                                apiKey: flexyconsentData.apiKey,
                                domains: selectedWebsites,
                                projectTypeId: 2
                            }),
                            contentType: "application/json; charset=utf-8",
                            success: function (response) {
                                if (response.statusCode === 0) {
                                    flexyconsentResponseTop('alert-success', 'Updated successfully');
                                    // window.location.reload();
                                } else {
                                    flexyconsentResponseTop('alert-danger', 'Failed to update! ' + response.statusMessage);
                                    // alert("Error: " + response.statusMessage);
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error("Error updating websites:", error);
                                alert("Failed to update websites. Please try again later.");
                            }
                        });
                    });

                    btnSave.disabled = false;

                    const packagesContainer = document.getElementById('plans_container'); //class="collapse"
                    const subscription = { id: 0, typeId: -1 };
                    showBuyPackages(subscription, packages, packagesContainer);

                    const buyNewPlanBtn = document.getElementById('btn_buy_new_plan');
                    const chevronRight = buyNewPlanBtn.querySelector('i.fa-chevron-right');
                    buyNewPlanBtn.addEventListener('click', function () {
                        if ($(packagesContainer).hasClass('show')) {
                            $(packagesContainer).collapse('hide');
                            chevronRight.style.transform = 'rotate(0deg)';
                        } else {
                            $(packagesContainer).collapse('show');
                            chevronRight.style.transform = 'rotate(90deg)';
                        }
                    });
                } else {
                    alert("Failed to load subscriptions. Please try again later.");
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching subscription data:", error);
                subscriptionsElement.innerHTML = '<div class="alert alert-danger">Failed to load subscriptions. Please try again later.</div>';
            }
        });


        function addSubscriptionElement(subscriptionsElement, subscription, packages, numSubscriptions, domains) {
            const subscriptionElement = document.createElement('div');
            subscriptionElement.setAttribute('id', 'subscription_' + subscription.id);
            subscriptionElement.classList.add('p-2');
            subscriptionsElement.appendChild(subscriptionElement);

            const plan = packages.find(p => p.id === subscription.typeId);
            const duration = "(" + (plan.durationMonth === 1 ? flexyconsentData['monthly'] : flexyconsentData['annual']) + ")";

            const titleRow = document.createElement('div');
            titleRow.classList.add('d-flex', 'justify-content-between', 'align-items-center');
            subscriptionElement.appendChild(titleRow);

            const title = document.createElement('h6');
            title.classList.add('fw-bold');
            title.textContent = subscription.type + " " + duration;
            titleRow.appendChild(title);

            const websiteContainer = document.createElement('div');
            websiteContainer.classList.add('d-flex', 'align-items-center', 'mb-2');
            subscriptionElement.appendChild(websiteContainer);

            const websiteIcon = document.createElement('i');
            websiteIcon.classList.add('fa-solid', 'fa-globe', 'me-2');
            websiteContainer.appendChild(websiteIcon);

            const websiteLabel = document.createElement('span');
            websiteLabel.classList.add('card-text');
            websiteLabel.textContent = flexyconsentData['website'];
            websiteContainer.appendChild(websiteLabel);

            const websiteSelector = document.createElement('select');
            websiteSelector.classList.add('form-select', 'form-select-sm', 'w-auto', 'ms-3');
            websiteSelector.style.minWidth = '200px';
            websiteSelector.setAttribute('aria-label', 'Websites');
            websiteSelector.setAttribute('id', 'websites_' + subscription.id);
            websiteContainer.appendChild(websiteSelector);

            const option = document.createElement('option');
            option.value = "0";
            option.textContent = flexyconsentData['select'];
            // websiteSelector.insertBefore(option, websiteSelector.firstChild);
            websiteSelector.appendChild(option);

            const domain = domains.find(d => d.subscriptionId === subscription.id);
            if (domain) {
                for (let i = 0; i < domains.length; i++) {
                    const option = document.createElement('option');
                    option.value = domains[i].id;
                    option.textContent = domains[i].domainName;
                    websiteSelector.appendChild(option);
                }
                websiteSelector.value = domain.id;

                if (subscription.type === 'Trial')
                    option.remove();
            } else {
                let isSelected = false;
                for (let i = 0; i < domains.length; i++) {
                    const option = document.createElement('option');
                    option.value = domains[i].id;
                    option.textContent = domains[i].domainName;

                    if (!isSelected && !domains[i].isSelected && domains[i].st === subscription.typeId) {
                        option.selected = true;
                        isSelected = true;
                        domains[i].isSelected = true;
                    }
                    websiteSelector.appendChild(option);
                }

                if (isSelected && subscription.type === 'Trial')
                    option.remove();
            }

            if (pageViewExceededObj && pageViewExceededObj.s && pageViewExceededObj.s.includes(subscription.id)) {
                const domainLink = document.createElement('a');
                domainLink.href = "#" + subscriptionElement.getAttribute('id');
                domainLink.textContent = domain.domainName;
                domainLink.classList.add('alert-link');

                const planLink = document.createElement('a');
                planLink.href = "#" + subscriptionElement.getAttribute('id');
                planLink.textContent = subscription.type;
                planLink.classList.add('alert-link');

                let msg = flexyconsentData['pageviewLimitMsgForDomain'];
                msg = msg.replace('[domain]', domainLink.outerHTML).replace('[planName]', planLink.outerHTML);
                flexyconsentResponseTop('alert-danger', msg);
            }

            const periodContainer = document.createElement('div');
            periodContainer.classList.add('d-flex', 'align-items-center', 'mb-2');
            subscriptionElement.appendChild(periodContainer);

            const periodIcon = document.createElement('i');
            periodIcon.classList.add('fa-regular', 'fa-calendar', 'me-2');
            periodContainer.appendChild(periodIcon);

            const periodLabel = document.createElement('span');
            periodLabel.classList.add('card-text');
            periodLabel.textContent = flexyconsentData['subscriptionPeriod'] + ":";
            periodContainer.appendChild(periodLabel);

            const periodText = document.createElement('span');
            periodText.classList.add('card-text', 'ms-2');
            periodText.textContent = subscription.start + " - " + subscription.end;
            periodContainer.appendChild(periodText);


            const remainingContainer = document.createElement('div');
            remainingContainer.classList.add('d-flex', 'align-items-center', 'mb-2');
            subscriptionElement.appendChild(remainingContainer);

            const remainingIcon = document.createElement('i');
            remainingIcon.classList.add('fa-regular', 'fa-clock', 'me-2');
            remainingContainer.appendChild(remainingIcon);

            let remainTime = new Date(subscription.end) - new Date(), remainStr;
            if (remainTime < 0)
                remainTime = 0;
            const remainDays = Math.floor(remainTime / (1000 * 60 * 60 * 24));
            if (remainDays > 30) {
                const remainMonths = Math.floor(remainDays / 30);
                remainStr = flexyconsentData[remainMonths > 1 ? 'remainMonthsCount' : 'remainMonthCount'];
                remainStr = remainStr.replace('[monthCount]', remainMonths.toString());
            } else {
                remainStr = flexyconsentData[remainDays > 1 ? 'remainDaysCount' : 'remainDayCount'];
                remainStr = remainStr.replace('[dayCount]', remainDays.toString());
            }

            const text2 = document.createElement('span');
            text2.classList.add('card-text');
            if (subscription.nextTypeId === 0) {
                text2.textContent = flexyconsentData['subscriptionCancelMessage'];
                text2.classList.add('text-danger');
            } else if (subscription.nextTypeId === subscription.typeId) {
                text2.textContent = flexyconsentData['subscriptionRenewMessage'];
                text2.classList.add('text-muted');
            }
            text2.textContent += " " + remainStr;
            remainingContainer.appendChild(text2);


            const descriptionContainer = document.createElement('div');
            subscriptionElement.appendChild(descriptionContainer);

            const descriptionTitle = document.createElement('div');
            descriptionTitle.textContent = flexyconsentData['planFeatures'];
            descriptionTitle.role = 'button';
            descriptionTitle.classList.add('mt-2');
            descriptionContainer.appendChild(descriptionTitle);

            const chevronParent = document.createElement('span');
            chevronParent.innerHTML = '<i class="fa-solid fa-chevron-right"></i>';
            chevronParent.classList.add('ms-1');
            descriptionTitle.appendChild(chevronParent);

            const descriptionTextContainer = document.createElement('div');
            descriptionTextContainer.classList.add('collapse');
            descriptionContainer.appendChild(descriptionTextContainer);

            const descriptionText = document.createElement('div');
            descriptionText.classList.add('card-text', 'bg-light', 'p-2', 'rounded-3', 'text-muted');
            descriptionText.style.fontSize = '14px';
            let planName = (plan.name.split(' ')[0]).toLowerCase();
            planName = planName.replace('trial', 'plus');
            descriptionText.innerHTML = flexyconsentData[planName + 'PlanDescription'] || plan.description;
            descriptionTextContainer.appendChild(descriptionText);

            descriptionTitle.onclick = function () {
                const chevronRight = chevronParent.querySelector('i.fa-chevron-right');
                if ($(descriptionTextContainer).hasClass('show')) {
                    $(descriptionTextContainer).collapse('hide');
                    chevronRight.style.transform = 'rotate(0deg)';
                } else {
                    $(descriptionTextContainer).collapse('show');
                    chevronRight.style.transform = 'rotate(90deg)';
                }
            }

            const isFreePlan = Math.floor(plan.price) === 0;
            if (isFreePlan)
                return;

            if (subscription.id > 0 && subscription.nextTypeId > 0) {
                const btnCancel = document.createElement('a');
                btnCancel.classList.add('danger-cancel-link');
                btnCancel.textContent = flexyconsentData['cancelSubscription'];
                btnCancel.setAttribute('data-bs-toggle', 'modal');
                btnCancel.setAttribute('data-bs-target', '#modal_cancel_subscription');
                // btnCancelContainer.appendChild(btnCancel);
                titleRow.appendChild(btnCancel);
                btnCancel.addEventListener('click', event => {
                    event.preventDefault();

                    const subscriptionInfo = document.getElementById('modal_subscription_info');
                    subscriptionInfo.textContent = flexyconsentData['subscription'] + ": " + subscription.type + ' (' + subscription.start + ' - ' + subscription.end + ')';

                    const btnConfirm = document.getElementById('btn_cancel_subscription');
                    btnConfirm.onclick = async function () {
                        event.preventDefault();

                        btnConfirm.disabled = true;
                        btnConfirm.textContent = flexyconsentData['cancelling'];
                        const spinner = generateSpinner();
                        btnConfirm.appendChild(spinner);

                        $.ajax({
                            url: flexyconsentData.endpoint + 'payment/unsubscribe',
                            type: 'POST',
                            data: JSON.stringify({
                                email: flexyconsentData.email,
                                apiKey: flexyconsentData.apiKey,
                                subscriptionId: subscription.id
                            }),
                            contentType: "application/json; charset=utf-8",
                            success: function (response) {
                                const modalElement = document.getElementById('modal_cancel_subscription');
                                const modal2 = bootstrap.Modal.getOrCreateInstance(modalElement);
                                if (response.statusCode === 0) {
                                    text2.textContent = flexyconsentData['subscriptionCancelMessage'];
                                    text2.classList.remove('text-muted');
                                    text2.classList.add('text-danger');

                                    window.location.reload();
                                } else {
                                    removeSpinner(spinner);
                                    modal2.hide();
                                    flexyconsentResponseTop('alert-danger', response.statusMessage);
                                    console.error(response.statusMessage);
                                }
                            },
                            error: function (error) {
                                flexyconsentResponseTop('alert-danger', error);
                                console.log(error);
                                removeSpinner(spinner);
                            }
                        });
                    };
                });
            }
        }

        function showBuyPackages(subscription, packages, packagesContainer) {
            const tabHeader = document.createElement('ul');
            tabHeader.classList.add('nav', 'nav-tabs', 'nav-fill', 'px-3');
            packagesContainer.appendChild(tabHeader);

            const annualTabHeader = document.createElement('li');
            annualTabHeader.classList.add('nav-item');
            tabHeader.appendChild(annualTabHeader);

            const annualTabLink = document.createElement('a');
            annualTabLink.classList.add('nav-link', 'text-black', 'active', 'pe-auto');
            annualTabLink.textContent = flexyconsentData['annual'];

            annualTabHeader.appendChild(annualTabLink);


            const monthlyTabHeader = document.createElement('li');
            monthlyTabHeader.classList.add('nav-item');
            tabHeader.appendChild(monthlyTabHeader);

            const monthlyTabLink = document.createElement('a');
            monthlyTabLink.classList.add('nav-link', 'text-black');
            monthlyTabLink.textContent = flexyconsentData['monthly'];

            monthlyTabHeader.appendChild(monthlyTabLink);


            const tabContentContainer = document.createElement('div');
            tabContentContainer.classList.add('tab-content');
            packagesContainer.appendChild(tabContentContainer);

            const annualTabContent = document.createElement('div');
            annualTabContent.classList.add('tab-pane', 'fade', 'show', 'active');
            annualTabContent.id = 'annual';
            tabContentContainer.appendChild(annualTabContent);

            const subAnnualTabContent = document.createElement('div');
            subAnnualTabContent.classList.add('d-flex', 'row', 'justify-content-center', 'py-3');
            annualTabContent.appendChild(subAnnualTabContent);

            const monthlyTabContent = document.createElement('div');
            monthlyTabContent.classList.add('tab-pane', 'fade');
            monthlyTabContent.id = 'monthly';
            tabContentContainer.appendChild(monthlyTabContent);

            const subMonthlyTabContent = document.createElement('div');
            subMonthlyTabContent.classList.add('d-flex', 'row', 'justify-content-center', 'py-3');
            monthlyTabContent.appendChild(subMonthlyTabContent);

            annualTabLink.addEventListener('click', event => {
                event.preventDefault();
                annualTabLink.classList.add('active');
                monthlyTabLink.classList.remove('active');
                annualTabContent.classList.add('show', 'active');
                monthlyTabContent.classList.remove('show', 'active');
            });

            monthlyTabLink.addEventListener('click', event => {
                event.preventDefault();
                monthlyTabLink.classList.add('active');
                annualTabLink.classList.remove('active');
                monthlyTabContent.classList.add('show', 'active');
                annualTabContent.classList.remove('show', 'active');
            });

            const groups = {};
            // // packages = packages.sort((a, b) => a.duration - b.duration);
            packages.forEach(plan => {
                if (!plan.enabled)
                    return;

                if (parseFloat(plan.price) === 0)
                    return;

                plan.name = plan.name.split(' (')[0];
                plan.externalInfoLink = plan.externalInfoLink.trim();

                const tabPanelContent = plan.duration === 12 ? subAnnualTabContent : subMonthlyTabContent;

                const cardCol = document.createElement('div');
                cardCol.classList.add('col', 'card-col');
                tabPanelContent.appendChild(cardCol);

                const planCard = document.createElement('div');
                planCard.classList.add('plan-card');
                cardCol.appendChild(planCard);

                const planCardBody = document.createElement('div');
                planCardBody.classList.add('plan-card-body');
                planCard.appendChild(planCardBody);

                const headerText = document.createElement('span');
                headerText.classList.add('header-text');
                headerText.textContent = plan.name;
                planCardBody.appendChild(headerText);

                const priceContainer = document.createElement('div');
                priceContainer.classList.add('price-container');

                const priceElement = document.createElement('div');
                priceElement.classList.add('paid');

                let oldPriceContainer = null;
                if (plan.price > 0) {
                    let price = parseFloat(plan.price);
                    let oldPrice = 0;
                    let discountPercentage = 0;

                    if (plan.discountRate) {
                        price = Math.round(plan.price * (1 - plan.discountRate) * 100) / 100;
                        oldPrice = parseFloat(plan.price);
                        discountPercentage = Math.floor(plan.discountRate * 100);
                    }

                    if (plan.durationMonth === 12 && plan.otherGroupMemberId) {
                        const monthlyPlan = packages.find(p => p.id === plan.otherGroupMemberId);
                        if (monthlyPlan) {
                            if (oldPrice > 0) {
                                const twelveMonthsPrice = Math.round(monthlyPlan.price * 12 * 100) / 100;
                                oldPrice = Math.max(oldPrice, twelveMonthsPrice);
                            } else {
                                oldPrice = Math.round(monthlyPlan.price * 12 * 100) / 100;
                            }
                            discountPercentage = Math.floor((1 - price / oldPrice) * 100);
                        }
                    }
                    plan.price = price;

                    const priceParts = price.toFixed(2).split('.');
                    const currency = currencyMap[plan.currency] || plan.currency;
                    priceElement.innerHTML = `<span class="currency">${currency}</span>${priceParts[0]}<span class="cent">.${priceParts[1]}</span>`;

                    if (oldPrice > 0) {
                        const oldPriceElement = document.createElement('span');
                        oldPriceElement.classList.add('old-price');
                        oldPriceElement.innerHTML = `${currency}${oldPrice.toFixed(2)}`;

                        const discountSvg = `<svg width="20" height="35" viewBox="0 0 21 39" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill="#FF8300" clip-rule="evenodd" fill-rule="evenodd" d="M18.0808 0C16.5161 0 15.0277 0.67567 13.9977 1.8535L1.34101 16.3268C-0.480869 18.4102 -0.442043 21.5311 1.4311 23.5685L14.0068 37.247C15.034 38.3642 16.4822 39 17.9998 39H20.2725V0L18.0808 0ZM11.361 23.4843C13.5614 23.2888 15.1868 21.3465 14.9912 19.146C14.7957 16.9455 12.8534 15.3202 10.6529 15.5157C8.45245 15.7113 6.82711 17.6536 7.02263 19.8541C7.21815 22.0545 9.16049 23.6799 11.361 23.4843Z"></path></svg>`;
                        const discountElement = document.createElement('div');
                        let discountText = flexyconsentData['discountText'] || "[Number]% off";
                        discountText = discountText.replace('[Number]', discountPercentage.toString());
                        discountElement.innerHTML =
                            `<div class="discount-container">
                                <span class="d-flex">${discountSvg}</span>
                                <span class="discount-text t-body-2">${discountText}</span>
                            </div>`;

                        oldPriceContainer = document.createElement('div');
                        oldPriceContainer.classList.add('d-flex');
                        oldPriceContainer.appendChild(oldPriceElement);
                        oldPriceContainer.appendChild(discountElement);
                        priceContainer.appendChild(oldPriceContainer);
                    }

                } else if (plan.externalInfoLink) {
                    priceElement.innerHTML = `<span class="custom-price">Custom Price</span>`;
                } else {
                    priceElement.innerHTML = `<span class="free">Free</span>`;
                    plan.price = 0;
                }

                priceContainer.appendChild(priceElement);
                planCardBody.appendChild(priceContainer);

                const cardText = document.createElement('div');
                cardText.classList.add('card-text', 'mb-5', 'text-center', 'align-middle');
                let planName = (plan.name.split(' ')[0]).toLowerCase();
                plan.description = flexyconsentData[planName + 'PlanDescription'] || plan.description;
                cardText.innerHTML = plan.description;
                planCardBody.appendChild(cardText);

                const button = document.createElement('button');
                button.id = `btn_${plan.id}`;
                button.classList.add('btn', 'btn-subscribe');
                if (plan.id !== subscription.nextTypeId) {
                    button.classList.add('btn-success');
                    // setTextContentTranslationByElement(button, plan.externalInfoLink ? 'contactUs' : 'buy');
                    button.innerText = flexyconsentData[plan.externalInfoLink ? 'contactUs' : 'buy'] || (plan.externalInfoLink ? 'Contact Us' : 'Buy');
                } else {
                    button.classList.add('btn-secondary');
                    button.innerText = flexyconsentData['subscribed'];
                    button.disabled = true;
                }
                planCardBody.appendChild(button);
                button.addEventListener('click', event => {
                    event.preventDefault();

                    plan.subscriptionId = subscription.id;
                    const packageJson = JSON.stringify(plan);
                    if (plan.externalInfoLink) {
                        window.open(plan.externalInfoLink, "_blank");
                    } else {
                        localStorage.setItem("buying_package", packageJson);
                        flexyconsentGoPage('paymentPage');
                    }
                });
            });

            if (subAnnualTabContent.children.length === 0) {
                monthlyTabLink.click();
                annualTabHeader.style.display = 'none';
                monthlyTabHeader.style.display = 'none';
            } else if (subMonthlyTabContent.children.length === 0) {
                annualTabLink.click();
                monthlyTabHeader.style.display = 'none';
                annualTabHeader.style.display = 'none';
            }
        }
    }


    function flexyconsent_subscriptionPageOld() {
        var subscriptionPage = $("#subscriptionPage");
        if (subscriptionPage.length === 0)
            return;

        const paymentState = getParameterByName('state');
        if (paymentState !== null) {
            if (paymentState === "1") {
                flexyconsentResponseTop('alert-success', 'Payment successful');
            } else if (paymentState === "0") {
                flexyconsentResponseTop('alert-danger', 'Payment failed');
            } else if (paymentState === "2") {
                flexyconsentResponseTop('alert-warning', 'Payment expired');
            }
        }

        $.ajax({
            url: flexyconsentData.endpoint + 'package/list',
            type: 'POST',
            data: JSON.stringify(
                {
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                    project: Number(flexyconsentData.projectId),
                    projectTypeId: 2
                }
            ),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                if (response.statusCode === 0) {
                    if (response.subscriptions) {
                        let subscription;
                        if (response.subscriptions.length === 1)
                            subscription = response.subscriptions[0];
                        else if (response.subscriptions.length > 1) {
                            for (let i = 0; i < response.subscriptions.length; i++) {
                                if (new Date(response.subscriptions[i].end) < new Date())
                                    continue;

                                if (response.subscriptions[i].type === 'Trial') {
                                    subscription = response.subscriptions[i];
                                    break;
                                } else if (response.subscriptions[i].nextTypeId === 0) {
                                    continue; // Cancelled subscription
                                } else {
                                    subscription = response.subscriptions[i];
                                    break; // Active subscription
                                }
                            }
                        }

                        if (!subscription) {
                            flexyconsentResponseTop('alert-danger', 'No subscription found');
                            return;
                        }

                        let nextSubscriptionElement = '';
                        if (subscription.type === 'Trial')//
                            nextSubscriptionElement = `<p>${flexyconsentData.subscriptionTrialMessage.replace('[FreePlanName]', "Free")}</p>`;
                        else if (subscription.nextTypeId === 0)
                            nextSubscriptionElement = `<p class="text-danger">${flexyconsentData.subscriptionCancelMessage}</p>`;
                        else if (subscription.nextTypeId === subscription.typeId)
                            nextSubscriptionElement = `<p>${flexyconsentData.subscriptionRenewMessage}</p>`;
                        else {
                            const currentType = response.packages.find(p => p.id === subscription.typeId);
                            const nextType = response.packages.find(p => p.id === subscription.nextTypeId);

                            if (currentType.price < nextType.price) {
                                const text = flexyconsentData.subscriptionUpgradeMessage.replace('[Next Type]', nextType.name);
                                nextSubscriptionElement = `<p class="text-success">${text}</p>`;
                            } else {
                                const text = flexyconsentData.subscriptionDowngradeMessage.replace('[Next Type]', nextType.name);
                                nextSubscriptionElement = `<p class="text-primary">${text}</p>`;
                            }
                        }

                        $('#flexyconsent-current-package').append(
                            `<div class='subscription-card text-center mt-1'>
                                <div class='subscription-info'>
                                    <p>${flexyconsentData.currentPlan}: <span>${subscription.type}</span></p>
                                    <p>${flexyconsentData.period}: <span>${subscription.start} - ${subscription.end}</span></p>
                                    ${nextSubscriptionElement}
                                </div>
                            </div>`
                        );

                        if (subscription.type === 'Trial')
                            return;

                        $('#btn_monthly').on('click', function () {
                            $('#tab_panel_annual').removeClass('show active');
                            $('#tab_panel_monthly').addClass('show active');

                            $('#btn_monthly').addClass('active').addClass('btn-dark').removeClass('btn-light');
                            $('#btn_annual').removeClass('active').removeClass('btn-dark').addClass('btn-light');
                        });

                        $('#btn_annual').on('click', function () {
                            $('#tab_panel_monthly').removeClass('show active');
                            $('#tab_panel_annual').addClass('show active');

                            $('#btn_annual').addClass('active').addClass('btn-dark').removeClass('btn-light');
                            $('#btn_monthly').removeClass('active').removeClass('btn-dark').addClass('btn-light');
                        });


                        // $('#flexyconsent_plans_container').classList.remove('d-none');
                        const plansContainer = document.getElementById('flexyconsent_plans_container');
                        plansContainer.classList.remove('d-none');
                        response.packages.forEach(plan => {
                            if (!plan.enabled || plan.name === 'Trial')
                                return;

                            plan.name = plan.name.split(' (')[0];
                            plan.externalInfoLink = plan.externalInfoLink.trim();

                            const priceContainer = document.createElement('div');
                            priceContainer.classList.add('price-container', 'd-flex', 'flex-column', 'align-items-center', 'justify-content-center');

                            const priceElement = document.createElement('div');
                            priceElement.classList.add('paid');

                            let oldPriceContainer = null;
                            if (plan.price > 0) {
                                let currency = null;
                                if (plan.currency === 'USD')
                                    currency = '$';
                                else if (plan.currency === 'EUR')
                                    currency = '€';
                                else if (plan.currency === 'GBP')
                                    currency = '£';
                                else
                                    currency = plan.currency;

                                let price = parseFloat(plan.price);
                                let oldPrice = 0;
                                let discountPercentage = 0;

                                if (plan.discountRate) {
                                    // price = Math.round(plan.price * (1 - plan.discountRate));
                                    price = Math.round(plan.price * (1 - plan.discountRate) * 100) / 100;
                                    oldPrice = parseFloat(plan.price);
                                    discountPercentage = Math.floor(plan.discountRate * 100);
                                }

                                if (plan.durationMonth == 12 && plan.otherGroupMemberId) {
                                    const monthlyPlan = response.packages.find(p => p.id === plan.otherGroupMemberId);
                                    if (monthlyPlan) {
                                        if (oldPrice > 0) {
                                            const twelweMonthsPrice = Math.round(monthlyPlan.price * 12 * 100) / 100;
                                            oldPrice = Math.max(oldPrice, twelweMonthsPrice);
                                        } else {
                                            oldPrice = Math.round(monthlyPlan.price * 12 * 100) / 100;
                                        }
                                        discountPercentage = Math.floor((1 - price / oldPrice) * 100);
                                    }
                                }
                                plan.price = price;

                                const priceParts = price.toFixed(2).split('.');
                                priceElement.innerHTML = `<span class="currency">${currency}</span>${priceParts[0]}<span class="cent">.${priceParts[1]}</span>`;

                                if (oldPrice > 0) {
                                    const oldPriceElement = document.createElement('span');
                                    oldPriceElement.classList.add('old-price');
                                    oldPriceElement.innerHTML = `${currency}${oldPrice.toFixed(2)}`;

                                    const discountText = flexyconsentData.discountText.replace('[Number]', discountPercentage);

                                    const discountSvg = `<svg width="20" height="35" viewBox="0 0 21 39" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill="#FF8300" clip-rule="evenodd" fill-rule="evenodd" d="M18.0808 0C16.5161 0 15.0277 0.67567 13.9977 1.8535L1.34101 16.3268C-0.480869 18.4102 -0.442043 21.5311 1.4311 23.5685L14.0068 37.247C15.034 38.3642 16.4822 39 17.9998 39H20.2725V0L18.0808 0ZM11.361 23.4843C13.5614 23.2888 15.1868 21.3465 14.9912 19.146C14.7957 16.9455 12.8534 15.3202 10.6529 15.5157C8.45245 15.7113 6.82711 17.6536 7.02263 19.8541C7.21815 22.0545 9.16049 23.6799 11.361 23.4843Z"></path></svg>`;
                                    const discountElement = document.createElement('div');
                                    discountElement.innerHTML = `<div class="discount-container">
                                                                    <span class="d-flex">${discountSvg}</span>
                                                                    <span class="discount-text t-body-2">${discountText}</span>
                                                                </div>`;

                                    oldPriceContainer = document.createElement('div');
                                    oldPriceContainer.classList.add('d-flex');
                                    oldPriceContainer.appendChild(oldPriceElement);
                                    oldPriceContainer.appendChild(discountElement);
                                    priceContainer.appendChild(oldPriceContainer);
                                }

                            } else if (plan.externalInfoLink) {
                                priceElement.innerHTML = `<span class="custom-price">Custom Price</span>`;
                            } else {
                                // priceText.remove();
                                // return;
                                priceElement.innerHTML = `<span class="free">Free</span>`;
                                plan.price = 0;
                            }

                            priceContainer.appendChild(priceElement);

                            //Basic SA -> Basic
                            const planName = plan.name.split(' ')[0].toLowerCase();
                            const description = flexyconsentData[planName.toLowerCase() + 'PlanDescription'];

                            const tabPanelContent = $('#tab_panel_content_' + (plan.durationMonth === 12 ? 'annual' : 'monthly'));
                            tabPanelContent.append(
                                `<div class='col mb-4 card-col'>
                                    <div class='d-flex flex-column h-100'>
                                        <div class='plan-card flex-fill'>                                            
                                            <div class='plan-card-body d-flex flex-column'>
                                                <span class='header-text'>${plan.name}</span>
                                                ${priceContainer.outerHTML}
                                                <div class='card-text mb-5 text-center align-middle'>${description}</div>
                                                <button id='btn_${plan.id}' class='btn w-100 mt-auto btn-subscribe ${plan.id !== subscription.typeId ? 'btn-success' : 'btn-secondary'}' ${plan.id === subscription.typeId ? 'disabled' : ''}>
                                                    ${plan.id !== subscription.typeId ? (plan.externalInfoLink ? flexyconsentData.contactUs : flexyconsentData.subscribe) : flexyconsentData.subscribed}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>`
                            );

                            $('#btn_' + plan.id).on('click', function () {
                                if (plan.id === subscription.typeId)
                                    return; // Already subscribed

                                if (subscription.type !== 'Free') {
                                    if (subscription.nextTypeId === 0)
                                        alert("You can subscribe to a new plan only after ending your current subscription.");
                                    else
                                        alert("You need to cancel your current subscription before subscribing to a new plan.");
                                    return;
                                }

                                plan.subscriptionId = subscription.id;
                                const packageJson = JSON.stringify(plan);
                                if (plan.externalInfoLink) {
                                    window.open(plan.externalInfoLink, "_blank");
                                } else {
                                    localStorage.setItem("buying_package", packageJson);
                                    flexyconsentGoPage('paymentPage');
                                }

                            });
                        });
                    }
                } else if (flexyconsentData.responseMessages[response.statusCode]) {
                    flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                } else {
                    flexyconsentResponse('alert-danger', response.statusMessage);
                }
            },
            error: function (error) {
                flexyconsentResponse('alert-danger', error);
                console.log(error);
            }
        });
    }


    /**
     * Payment Page
     */
    function flexyconsent_paymentPage() {
        var paymentPage = $("#paymentPage");
        if (paymentPage.length === 0)
            return;

        if (!isRealEmail()) {
            flexyconsentGoPage('updateUserSettingsPage');
        }

        const plan = JSON.parse(localStorage.getItem("buying_package"));
        // const project = JSON.parse(localStorage.getItem("project"));

        if (!plan) {
            flexyconsentResponse('alert-danger', 'Invalid request');
            flexyconsentGoPage('subscriptionPage');
            return;
        }

        // if (plan.price === 0)
        //     $('#flexyconsent_title').text(flexyconsentData.paymentPageNewPlanTitle.replace('[PlanName]', plan.name));

        $('#flexyconsent_package_name').text(plan.name);
        // const planName = (plan.name.split(' ')[0]).toLowerCase();
        // const description = flexyconsentData[planName + 'PlanDescriptionn'] || plan.description;
        // $('#flexyconsent_description').html(description);
        $('#flexyconsent_description').html(plan.description);
        $('#flexyconsent_price').text(plan.price.toFixed(2));
        $('#flexyconsent_currency').text(plan.currency);

        if (plan.price > 0) {
            const btnPaypal = document.getElementById("flexyconsent_paypal");
            btnPaypal.classList.remove('d-none');
            btnPaypal.addEventListener('click', subscribe);

            const btnCreditCard = document.getElementById("flexyconsent_credit_card");
            btnCreditCard.classList.remove('d-none');
            btnCreditCard.addEventListener('click', subscribe);
        } else {
            // $('#flexyconsent_title').text(flexyconsentData.paymentPageNewPlanTitle.replace('[PlanName]', plan.name));
            // const btnFree = document.getElementById("flexyconsent_btn_free");
            // btnFree.classList.remove('d-none');
            // btnFree.addEventListener('click', subscribe);
            alert('Free plan selected! You will be redirected to the subscription page.');
            flexyconsentGoPage('subscriptionPage');
            return;
        }

        function subscribe() {
            if (document.getElementById('btn_spinner'))
                return;

            const spinner = generateSpinner();
            const button = this;
            // button.disabled = true;
            button.appendChild(spinner);
            $.ajax({
                url: flexyconsentData.endpoint + 'payment/pay',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectId: Number(flexyconsentData.projectId),
                        subscriptionTypeId: plan.id,
                        subscriptionId: plan.subscriptionId,
                        approveUrl: flexyconsentReturnPage('subscriptionPage'),
                        cancelUrl: flexyconsentReturnPage('subscriptionPage')
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        // flexyconsentResponse('alert-success', 'Subscription successful', flexyconsentData.redirectRoot + 'subscriptionPage', 'Go to subscription page');

                        if (plan.price > 0) {
                            window.location.href = response.content;
                        } else if (response.content) {
                            alert(response.content);
                        } else {
                            flexyconsentGoPage('subscriptionPage');
                        }
                    } else if (response.statusCode === 26) {
                        flexyconsentResponseTop('alert-warning', response.statusMessage);
                        flexyconsentGoPage('updateUserSettingsPage');
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }

                    // button.disabled = false;
                    spinner.remove();
                },
                error: function (error) {
                    flexyconsentResponseTop('alert-danger', error);
                    console.log(error);
                    button.disabled = false;
                    spinner.remove();
                }
            });
        }

        function unsubcribe() {
            $.ajax({
                url: flexyconsentData.endpoint + 'payment/unsubscribe',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectId: Number(flexyconsentData.projectId),
                        subscriptionId: plan.subscriptionId
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        // flexyconsentResponse('alert-success', 'Subscription successful', flexyconsentData.redirectRoot + 'subscriptionPage', 'Go to subscription page');
                        window.location.href = response.content;
                    } else if (response.statusCode === 26) {
                        flexyconsentResponseTop('alert-warning', response.statusMessage);
                        flexyconsentGoPage('updateUserSettingsPage');
                    } else if (flexyconsentData.responseMessages[response.statusCode]) {
                        flexyconsentResponse('alert-danger', flexyconsentData.responseMessages[response.statusCode]);
                    } else {
                        flexyconsentResponse('alert-danger', response.statusMessage);
                    }
                },
                error: function (error) {
                    flexyconsentResponseTop('alert-danger', error);
                    console.log(error);
                }
            });
        }
    }

    function generateSpinner() {
        const spinner = document.createElement('span');
        spinner.id = 'btn_spinner';
        spinner.setAttribute('role', 'status');
        spinner.setAttribute('aria-hidden', 'true');
        spinner.classList.add('spinner-border', 'spinner-border-sm', 'ms-2', 'text-light');
        spinner.started = new Date();
        return spinner;
    }

    function removeSpinner(spinner, ff) {
        var endDate = new Date();
        var msecs = endDate.getTime() - spinner.started.getTime();
        console.debug("msecs=" + msecs);
        if (msecs >= 2000) {
            spinner.remove();
            if (ff)
                ff();
        }
        else
            setTimeout(function () { removeSpinner(spinner, ff); }, 2001 - msecs);
    }



    async function flexyconsent_cookieManagerPage() {
        var cookieManagerPage = $("#cookieManagerPage");
        if (cookieManagerPage.length === 0)
            return;

        // Check if required DOM elements exist - UPDATED: Changed to select_domain
        const domainDropdown = document.getElementById('select_domain');
        const languageDropdown = document.getElementById('select_language');
        const container = document.getElementById('cookie_manager_container');

        if (!domainDropdown) {
            console.error('Domain dropdown not found - make sure element with ID "select_domain" exists');
            return;
        }

        if (!languageDropdown) {
            console.error('Language dropdown not found - make sure element with ID "select_language" exists');
            return;
        }

        if (!container) {
            console.error('Cookie manager container not found - make sure element with ID "cookie_manager_container" exists');
            return;
        }

        // try {
        //     await loadLanguageDropdown();
        // } catch (error) {
        //     console.error('Error loading languages:', error);
        // }

        // UPDATED: Load domains instead of projects
        try {
            let domains = null;
            $.ajax({
                url: flexyconsentData.endpoint + 'project-domain/list',
                type: 'POST',
                data: JSON.stringify(
                    {
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectTypeId: 2,
                        method: 1,
                        languages: true
                    }
                ),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        languageDropdown.innerHTML = '';
                        const langSelector = document.getElementById('select_language');
                        response.languages.forEach(lang => {
                            const option = document.createElement('option');
                            option.value = lang.shortCode;
                            option.text = lang.name;

                            // if (lang.shortCode === config.primaryLanguage) {
                            //     option.selected = "selected";
                            //     option.checked = true;
                            //     langSelector.value = option.shortCode;
                            // }
                            langSelector.appendChild(option);
                        });


                        // Clear existing options first to prevent duplicates
                        domainDropdown.innerHTML = '';

                        // Add domain options
                        let firstValidDomain = null;
                        if (response.domains.length > 0) {
                            response.domains.forEach(domain => {
                                const option = document.createElement('option');
                                option.value = domain.id;
                                option.text = domain.domainName;
                                domainDropdown.appendChild(option);

                                // Store first domain for default selection
                                if (!firstValidDomain) {
                                    firstValidDomain = domain;
                                }
                            });
                        } else {
                            console.error('No domains available');
                            flexyconsentResponseTop('alert-danger', 'No domains available');
                            return;
                        }

                        // Set first domain as default if no URL parameter is provided
                        const selectedDomainId = new URLSearchParams(window.location.search).get("id");
                        if (selectedDomainId) {
                            domainDropdown.value = selectedDomainId;
                        } else if (firstValidDomain) {
                            domainDropdown.value = firstValidDomain.id;
                        }

                        domainDropdown.dispatchEvent(new Event('change'));
                    } else {
                        console.error('Error loading domains: ' + response.statusMessage);
                        flexyconsentResponseTop('alert-danger', 'Failed to load domains: ' + response.statusMessage);
                        return;
                    }
                },
                error: function (error) {
                    console.error('Error loading domains:', error);
                    flexyconsentResponseTop('alert-danger', 'Failed to load domains: ' + error);
                    return;
                }
            });

            // UPDATED: Changed event listener to use domain instead of project
            domainDropdown.addEventListener('change', function () {
                domainDropdown.classList.remove('d-none');
                loadCookiesForDomain(domainDropdown.value);
                setCookieScanUrl(domainDropdown.options[domainDropdown.selectedIndex].text, 1);
            });

        } catch (error) {
            console.error('Error loading domains:', error);
            flexyconsentResponseTop('alert-danger', 'Failed to load domains: ' + error.message);
        }

        async function loadCookiesForDomain(domainId) {
            const container = document.getElementById('cookie_manager_container');
            container.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-3 text-muted">Loading cookies...</p></div>';

            try {
                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (responseBody) {
                        console.log('Current cookies loaded successfully:', responseBody);
                        if (responseBody.statusCode === 0) {
                            // Backend returns cookies in "resources" field directly
                            const cookies = responseBody.resources || [];

                            // Create the data structure expected by the frontend
                            const formattedResponse = {
                                value: {
                                    resources: cookies
                                }
                            };

                            // Store for global access
                            window.currentCookies = cookies.filter(resource => {
                                if (!resource) return false;
                                const cookieTypes = ['Essential', 'Personalization', 'Analytics', 'Marketing', 'Security', 'Other'];
                                return !resource.type ||
                                    resource.type === 'cookie' ||
                                    cookieTypes.includes(resource.type) ||
                                    (resource.name && resource.displayName);
                            });

                            window.currentData = formattedResponse;
                            window.currentDomainId = domainId; // Changed from currentProjectId to currentDomainId

                            displayEnhancedCookieManager(formattedResponse, domainId);
                        } else {
                            console.error('Error loading cookies:', responseBody.statusMessage);
                            flexyconsentResponseTop('alert-danger', 'Failed to load cookies: ' + responseBody.statusMessage);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to load cookies:', status, error);
                        flexyconsentResponseTop('alert-danger', 'Failed to load cookies: ' + error);
                    }
                });
            } catch (error) {
                console.error('Error loading cookies:', error);
                flexyconsentResponseTop('alert-danger', 'Error loading cookies: ' + error.message);
            }
        }

        function setCookieScanUrl(url, count) {
            if (count > 20)
                return;

            var domainDropdown = document.getElementById('select_domain'), vvx = document.getElementById('scanUrl');
            //console.log("sdfsfsdfsfsdfd " + url);
            if (vvx)
                vvx.value = 'https://' + domainDropdown.options[domainDropdown.selectedIndex].text + '/';
            else
                setTimeout(function () { setCookieScanUrl(url, count + 1); }, 200);
        }


        function filterAndSearch(allCookies, data, domainId) {
            const searchInput = document.querySelector('#cookie_manager_container input[placeholder="Search cookies..."]');
            const filterSelect = document.querySelector('#cookie_manager_container select');

            if (!searchInput || !filterSelect) {
                console.error('Search input or filter select not found');
                return;
            }

            const searchTerm = searchInput.value.toLowerCase();
            const filterType = filterSelect.value;

            let filteredCookies = allCookies.filter(cookie => {
                // Type filter
                if (filterType !== 'all' && cookie.type !== filterType) {
                    return false;
                }

                // Search filter - Updated search fields with multilingual description support
                if (searchTerm) {
                    const searchFields = [
                        cookie.name,
                        cookie.displayName,
                        cookie.vendor,
                        cookie.type
                    ].map(field => (field || '').toLowerCase());

                    // Add description search (check all language versions)
                    if (cookie.description) {
                        if (typeof cookie.description === 'object') {
                            // Search all language versions
                            Object.values(cookie.description).forEach(desc => {
                                if (desc) searchFields.push(desc.toLowerCase());
                            });
                        } else {
                            // Handle legacy string descriptions
                            searchFields.push(cookie.description.toLowerCase());
                        }
                    }

                    return searchFields.some(field => field.includes(searchTerm));
                }

                return true;
            });

            renderCookieTable(filteredCookies, data, domainId);
        }

        let currentSort = { key: null, direction: 'asc' };

        function sortTable(key) {
            const direction = currentSort.key === key && currentSort.direction === 'asc' ? 'desc' : 'asc';
            currentSort = { key, direction };

            // Update sort indicators
            document.querySelectorAll('th i.fa-sort, th i.fa-sort-up, th i.fa-sort-down').forEach(icon => {
                icon.className = 'fas fa-sort text-muted ms-1';
            });

            const header = document.querySelector(`th:nth-child(${getColumnIndex(key) + 1}) i:last-child`);
            if (header) {
                header.className = `fas fa-sort-${direction === 'asc' ? 'up' : 'down'} text-primary ms-1`;
            }

            // Re-render with sorting - Fixed selectors
            const searchInput = document.querySelector('#cookie_manager_container input[placeholder="Search cookies..."]');
            const filterSelect = document.querySelector('#cookie_manager_container select');

            // Get current filtered cookies
            const allCookies = window.currentCookies || [];
            let filteredCookies = allCookies.filter(cookie => {
                const filterType = filterSelect ? filterSelect.value : 'all';
                const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';

                if (filterType !== 'all' && cookie.type !== filterType) {
                    return false;
                }

                if (searchTerm) {
                    const searchFields = [
                        cookie.name,
                        cookie.displayName,
                        cookie.vendor,
                        cookie.type
                    ].map(field => (field || '').toLowerCase());

                    // Add description search (check all language versions)
                    if (cookie.description) {
                        if (typeof cookie.description === 'object') {
                            // Search all language versions
                            Object.values(cookie.description).forEach(desc => {
                                if (desc) searchFields.push(desc.toLowerCase());
                            });
                        } else {
                            // Handle legacy string descriptions
                            searchFields.push(cookie.description.toLowerCase());
                        }
                    }

                    return searchFields.some(field => field.includes(searchTerm));
                }

                return true;
            });

            renderCookieTable(filteredCookies, window.currentData, window.currentDomainId, key, direction);
        }

        function getColumnIndex(key) {
            const columns = ['displayName', 'name', 'type', 'retentionPeriod', 'actions'];
            return columns.indexOf(key);
        }

        function createCookieScannerSection(domainId) {
            const scannerContainer = document.createElement('div');
            scannerContainer.classList.add('card', 'mb-4');
            scannerContainer.id = 'cookie_scanner_section';

            scannerContainer.innerHTML = `
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-search me-2"></i>${flexyconsentData.cookieScanner}
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-robot me-2"></i>${flexyconsentData.automaticDetection}
                            </h6>
                            <p class="text-muted mb-3">
                                ${flexyconsentData.cookieScannerDescription}
                            </p>
                            <div class="mb-2">
                                <h6 class="text-success mb-2">
                                    ${flexyconsentData['scanFeatures']}
                                </h6>
                                <ul class="list-unstyled mb-0">
                                    <li class="mb-1">
                                        <i class="fas fa-cookie-bite text-primary me-2"></i>
                                        ${flexyconsentData.essentialCookies}
                                    </li>
                                    <li class="mb-1">
                                        <i class="fas fa-chart-line text-info me-2"></i>
                                        ${flexyconsentData.analyticsCookies}
                                    </li>
                                    <li class="mb-1">
                                        <i class="fas fa-bullhorn text-warning me-2"></i>
                                        ${flexyconsentData.marketingCookies}
                                    </li>
                                    <li class="mb-1">
                                        <i class="fas fa-user-cog text-secondary me-2"></i>
                                        ${flexyconsentData.personalizationCookies}
                                    </li>
                                    <li class="mb-0">
                                        <i class="fas fa-puzzle-piece text-success me-2"></i>
                                        ${flexyconsentData.thirdPartyCookies}
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center">
                                <div class="mb-4">
                                <th><i class="fas fa-cogs me-1"></i><strong>${flexyconsentData['scannerActions']}</strong></th>
                                </div>
                                <div class="d-grid gap-2">
                                    <button type="button" class="btn btn-success btn-lg" id="newScanBtn">
                                        <i class="fas fa-play me-2"></i>${flexyconsentData['startNewScan']}
                                    </button>
                                    <button type="button" class="btn btn-info" id="viewStatusBtn">
                                        <i class="fas fa-list me-2"></i>${flexyconsentData['viewStatus']}
                                    </button>
                                </div>

                                <div class="mt-3 pt-3 border-top">
                                    <small class="text-muted">
                                        <i class="fas fa-clock me-1"></i>
                                        ${flexyconsentData['scanTime']}
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            return scannerContainer;
        }

        function showIpModal() {
            // Create modal element
            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;
            modal.id = 'ipListModal';

            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-server me-2"></i>${flexyconsentData['ipListTitle']}
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <p class="text-muted">
                                    ${flexyconsentData['ipListDescription']}
                                </p>
                            </div>
                            <div class="mb-3">
                                <label for="ipListTextarea" class="form-label">
                                    <i class="fas fa-list me-1"></i>${flexyconsentData['ipAddressesStr']}
                                </label>
                                <textarea
                                    class="form-control font-monospace"
                                    id="ipListTextarea"
                                    rows="12"
                                    readonly
                                    style="font-size: 0.9em; line-height: 1.4;"
                                >79.137.17.189
178.32.101.196
51.254.152.157
188.165.5.60
87.98.166.59
176.31.11.245
94.23.146.169
217.182.28.236
188.165.30.212
178.32.43.167
188.165.128.184
79.137.17.188
164.132.128.233
178.32.102.33
164.132.128.232
54.37.60.131
94.23.120.181
51.254.238.200
178.32.40.154
79.137.17.187
51.210.174.175
147.135.189.8
178.33.37.237
51.38.17.124
137.74.105.15
137.74.105.12
193.70.78.212
46.105.228.180
188.165.164.148
149.202.132.28
46.105.246.246
79.137.24.177
217.182.6.61
178.32.102.74
51.68.74.30
79.137.17.191
79.137.17.185
94.23.120.174
94.23.120.178
176.31.9.177
137.74.105.13
46.105.246.245
141.94.41.69
164.132.88.84
51.210.238.3
5.135.237.225
5.135.20.151
91.134.170.84</textarea>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-primary" id="copyIpListBtn">
                                    <i class="fas fa-copy me-2"></i>${flexyconsentData['copyToClipboard']}
                                </button>

                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i>${flexyconsentData['close']}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            // Append modal to body
            document.body.appendChild(modal);

            // Initialize Bootstrap modal
            const bsModal = new bootstrap.Modal(modal);

            // Add event listeners after modal is shown
            modal.addEventListener('shown.bs.modal', () => {
                const copyBtn = document.getElementById('copyIpListBtn');
                const textarea = document.getElementById('ipListTextarea');

                // Copy to clipboard functionality
                copyBtn.addEventListener('click', async () => {
                    try {
                        // Always copy the full textarea value, regardless of selection
                        await navigator.clipboard.writeText(textarea.value);

                        // Show success feedback
                        const originalText = copyBtn.innerHTML;
                        copyBtn.innerHTML = '<i class="fas fa-check me-2"></i>' + (flexyconsentData['copied']);
                        copyBtn.classList.remove('btn-primary');
                        copyBtn.classList.add('btn-success');

                        setTimeout(() => {
                            copyBtn.innerHTML = originalText;
                            copyBtn.classList.remove('btn-success');
                            copyBtn.classList.add('btn-primary');
                        }, 2000);

                    } catch (err) {
                        // Fallback for older browsers - select all then copy
                        textarea.select();
                        document.execCommand('copy');

                        // Show success feedback
                        const originalText = copyBtn.innerHTML;
                        copyBtn.innerHTML = '<i class="fas fa-check me-2"></i>' + (flexyconsentData['copied']);
                        copyBtn.classList.remove('btn-primary');
                        copyBtn.classList.add('btn-success');

                        setTimeout(() => {
                            copyBtn.innerHTML = originalText;
                            copyBtn.classList.remove('btn-success');
                            copyBtn.classList.add('btn-primary');
                        }, 2000);
                    }
                });
            });

            // Show the modal
            bsModal.show();

            // Clean up modal when closed
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }

        function renderCookieTable(cookies, data, domainId, sortKey = null, sortDirection = 'asc') {
            const tbody = document.getElementById('cookiesTableBody');
            tbody.innerHTML = '';

            let sortedCookies = [...cookies];

            if (sortKey) {
                sortedCookies.sort((a, b) => {
                    let aVal = a[sortKey];
                    let bVal = b[sortKey];

                    // Handle boolean values
                    if (typeof aVal === 'boolean') {
                        aVal = aVal ? 1 : 0;
                        bVal = bVal ? 1 : 0;
                    }

                    // Handle string values
                    if (typeof aVal === 'string') {
                        aVal = aVal.toLowerCase();
                        bVal = bVal ? bVal.toLowerCase() : '';
                    }

                    if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
                    if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
                    return 0;
                });
            }

            if (sortedCookies.length === 0) {
                const row = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 5; // Updated column count
                cell.classList.add('text-center', 'text-muted', 'py-5');
                cell.innerHTML = `
            <div class="d-flex flex-column align-items-center">
                <i class="fas fa-cookie-bite fa-3x mb-3 text-muted"></i>
                <h5>${flexyconsentData['noCookiesFound']}</h5>
                <p class="mb-3">${flexyconsentData['addCookieNote']} </p>
                <button class="btn btn-primary" onclick="showAddCookieModal(arguments[0], arguments[1])">
                    <i class="fa fa-plus me-2"></i>${flexyconsentData['addCookie']}
                </button>
            </div>
        `;
                row.appendChild(cell);
                tbody.appendChild(row);
            } else {
                sortedCookies.forEach(cookie => {
                    const row = createEnhancedCookieRow(cookie, data, domainId);
                    tbody.appendChild(row);
                });
            }
        }

        function createEnhancedCookieRow(cookie, data, domainId) {
            const row = document.createElement('tr');
            row.classList.add('cookie-row');

            // Display Name cell (first column) with comprehensive badges
            const displayNameCell = document.createElement('td');
            const displayNameContainer = document.createElement('div');

            const displayNameSpan = document.createElement('span');
            displayNameSpan.textContent = cookie.displayName || 'N/A';
            displayNameSpan.classList.add('fw-bold');
            displayNameContainer.appendChild(displayNameSpan);

            // Vendor info
            if (cookie.vendor) {
                const vendorSpan = document.createElement('small');
                vendorSpan.classList.add('text-muted', 'd-block');
                vendorSpan.textContent = `by ${cookie.vendor}`;
                displayNameContainer.appendChild(vendorSpan);
            }

            // Add badge for custom/system cookies
            if (cookie.custom) {
                const customBadge = document.createElement('span');
                customBadge.classList.add('badge', 'bg-success', 'ms-2');
                customBadge.textContent = 'Custom';
                customBadge.style.fontSize = '0.7rem';
                displayNameContainer.appendChild(customBadge);
            } else {
                const systemBadge = document.createElement('span');
                systemBadge.classList.add('badge', 'bg-outline-secondary', 'text-secondary', 'border', 'border-secondary', 'ms-2');
                systemBadge.textContent = 'System';
                systemBadge.style.fontSize = '0.7rem';
                systemBadge.style.backgroundColor = 'transparent';
                displayNameContainer.appendChild(systemBadge);
            }

            displayNameCell.appendChild(displayNameContainer);
            row.appendChild(displayNameCell);

            // Name cell (second column)
            const nameCell = document.createElement('td');
            nameCell.textContent = cookie.name || '';
            nameCell.classList.add('font-monospace', 'small');
            row.appendChild(nameCell);

            // Type
            const typeCell = document.createElement('td');
            const typeSpan = document.createElement('span');
            typeSpan.textContent = cookie.type || 'unspecified';
            typeSpan.classList.add('badge', getTypeColor(cookie.type));
            typeCell.appendChild(typeSpan);
            row.appendChild(typeCell);

            // Retention Period
            const retentionCell = document.createElement('td');
            retentionCell.textContent = cookie.retentionPeriod || 'Session';
            if (cookie.retentionPeriod === 'Session') {
                retentionCell.classList.add('text-warning');
            }
            row.appendChild(retentionCell);

            // Actions
            const actionsCell = document.createElement('td');
            actionsCell.classList.add('text-nowrap');

            // View/Details button
            const viewButton = document.createElement('button');
            viewButton.classList.add('btn', 'btn-sm', 'btn-outline-info', 'me-1');
            viewButton.innerHTML = '<i class="fa fa-eye"></i>';
            viewButton.title = 'View Details';
            viewButton.addEventListener('click', () => showCookieDetailsModal(cookie));
            actionsCell.appendChild(viewButton);

            const editButton = document.createElement('button');
            editButton.classList.add('btn', 'btn-sm', 'btn-outline-primary', 'me-1');
            editButton.innerHTML = '<i class="fa fa-edit"></i>';
            editButton.title = 'Edit';
            editButton.addEventListener('click', () => showEditCookieModal(cookie, data, domainId));
            actionsCell.appendChild(editButton);

            const deleteButton = document.createElement('button');
            deleteButton.classList.add('btn', 'btn-sm', 'btn-outline-danger');
            deleteButton.innerHTML = '<i class="fa fa-trash"></i>';
            deleteButton.title = 'Delete';
            deleteButton.addEventListener('click', () => deleteCookieConfirm(cookie, data, domainId));
            actionsCell.appendChild(deleteButton);

            row.appendChild(actionsCell);
            return row;
        }


        function getTypeColor(type) {
            switch (type?.toLowerCase()) {
                case 'essential': return 'bg-danger';
                case 'personalization': return 'bg-primary';
                case 'analytics': return 'bg-info';
                case 'marketing': return 'bg-warning';
                case 'security': return 'bg-dark';
                case 'other': return 'bg-secondary';
                default: return 'bg-light text-dark';
            }
        }

        function showCookieDetailsModal(cookie) {
            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;

            // Get selected language shortCode for description display
            const languageDropdown = document.getElementById('select_language');
            let selectedLanguageCode = 'en_uk'; // default fallback to English

            if (languageDropdown && languageDropdown.selectedOptions.length > 0) {
                const selectedOption = languageDropdown.selectedOptions[0];
                const selectedId = selectedOption.value;

                // Try to get shortCode from data attribute first, then lookup by ID
                selectedLanguageCode = selectedOption.dataset.shortcode ||
                    selectedOption.getAttribute('data-shortcode') ||
                    getLanguageShortCodeById(selectedId) ||
                    'en_uk';
            }

            console.log('Details modal showing description for language:', selectedLanguageCode);

            // Get description for selected language with fallbacks
            let displayDescription = 'No description provided';
            if (cookie.description) {
                if (typeof cookie.description === 'object') {
                    displayDescription = cookie.description[selectedLanguageCode] ||
                        cookie.description['en_uk'] ||
                        cookie.description['en'] ||
                        Object.values(cookie.description)[0] ||
                        'No description provided';
                } else {
                    // Handle legacy string descriptions
                    displayDescription = cookie.description;
                }
            }

            modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        ${flexyconsentData['cookieDetails']} ${cookie.name}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary">${flexyconsentData['basicInformation']}</h6>
                            <dl class="row">
                                <dt class="col-sm-5">${flexyconsentData['displayName']} :</dt>
                                <dd class="col-sm-7">${cookie.displayName || 'N/A'}</dd>
                                <dt class="col-sm-5">${flexyconsentData['name']} :</dt>
                                <dd class="col-sm-7">${cookie.name || 'N/A'}</dd>
                                <dt class="col-sm-5">${flexyconsentData['type']} :</dt>
                                <dd class="col-sm-7">${cookie.type || 'N/A'}</dd>
                                <dt class="col-sm-5">${flexyconsentData['retentionPeriod']} :</dt>
                                <dd class="col-sm-7">${cookie.retentionPeriod || 'Session'}</dd>
                            </dl>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-primary">${flexyconsentData['properties']}</h6>
                            <dl class="row">
                                <dt class="col-sm-3">${flexyconsentData['custom']} :</dt>
                                <dd class="col-sm-9">${cookie.custom ? '✓ Yes' : '✗ No'}</dd>
                                <dt class="col-sm-3">ID:</dt>
                                <dd class="col-sm-9"><small class="font-monospace">${cookie.id || 'N/A'}</small></dd>
                            </dl>
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-12">
                            <h6 class="text-primary">${flexyconsentData['description']} <span class="badge bg-success">${getLanguageNameByShortCode(selectedLanguageCode)}</span></h6>
                            <p class="bg-light p-3 rounded">${displayDescription}</p>
                            ${typeof cookie.description === 'object' ?
                    `<small class="text-muted mb-3 d-block">${flexyconsentData['availableLanguages']} : ${Object.keys(cookie.description).map(code => getLanguageNameByShortCode(code)).join(', ')}</small>` : ''}
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary">${flexyconsentData['vendorInformation']}</h6>
                            <dl class="row">
                                <dt class="col-sm-5">${flexyconsentData['vendor']} :</dt>
                                <dd class="col-sm-7">${cookie.vendor || 'N/A'}</dd>
                                <dt class="col-sm-5">${flexyconsentData['privacyUrl']}:</dt>
                                <dd class="col-sm-7">
                                    ${cookie.privacyUrl ?
                    `<a href="${cookie.privacyUrl}" target="_blank" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-external-link-alt me-1"></i>${flexyconsentData['viewPolicy']}
                                        </a>` : 'N/A'}
                                </dd>
                            </dl>
                        </div>
                    </div>

                    ${cookie.script ? `
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6 class="text-primary">${flexyconsentData['associatedScript']}</h6>
                                <pre class="bg-dark text-light p-3 rounded"><code>${cookie.script}</code></pre>
                            </div>
                        </div>
                    ` : ''}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">${flexyconsentData['close']}</button>
                    <button id="btnEditCookie" type="button" class="btn btn-primary" onclick="showEditCookieModal(${JSON.stringify(cookie).replace(/"/g, '&quot;')}, arguments[1], arguments[2])" data-bs-dismiss="modal">
                        <i class="fas fa-edit me-2"></i>${flexyconsentData['editCookie']}
                    </button>
                </div>
            </div>
        </div>
    `;

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });

            // modal.querySelector('#btnEditCookie').addEventListener('click', () => {
            //     showEditCookieModal(cookie, window.currentData, window.currentDomainId);
            // });
        }

        window.showEditCookieModal = function (cookie, data, domainId) {
            console.log('showEditCookieModal called with domainId:', domainId);

            const modal = createEnhancedCookieModal('Edit Cookie', cookie, (cookieData, modalDomainId) => {
                console.log('Edit cookie callback called with domainId:', modalDomainId || domainId);
                updateCookie(cookieData, data, modalDomainId || domainId, cookie);
            }, domainId);

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }



        window.handleScanUrlKeypress = function (event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                const scanBtn = document.getElementById('modalScanBtn');
                if (scanBtn && !scanBtn.disabled) {
                    executeScan();
                }
            }
        }

        function showScanUrlModal(domainId) {
            // Get default URL from selected domain
            const domainDropdown = document.getElementById('select_domain');
            let defaultUrl = 'https://example.com';
            if (domainDropdown && domainDropdown.selectedOptions.length > 0) {
                const selectedDomain = domainDropdown.options[domainDropdown.selectedIndex].text;
                defaultUrl = 'https://' + selectedDomain + '/';
            }

            // Store domainId globally for the inline handlers
            window.currentScanDomainId = domainId;

            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;
            modal.id = 'scanUrlModal';

            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-cog me-2"></i>${flexyconsentData['configureScan']}
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <p class="text-muted">
                                    ${flexyconsentData['scanModalDescription']}
                                </p>
                            </div>
                            <div class="mb-3">
                                <label for="modalScanUrl" class="form-label">
                                    <i class="fas fa-link me-1"></i>${flexyconsentData['downloadPageUrl']} <span class="text-danger">*</span>
                                </label>
                                <input type="url" class="form-control" id="modalScanUrl"
                                    value="${defaultUrl}"
                                    placeholder="https://example.com"
                                    onkeypress="handleScanUrlKeypress(event)"
                                    oninput="validateScanUrl()"
                                    required>
                                <div class="form-text">
                                    ${flexyconsentData['scanUrlHelper']}
                                </div>
                                <div class="invalid-feedback">
                                    Please enter a valid URL
                                </div>
                            </div>

                            <div class="alert alert-info" role="alert">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>${flexyconsentData['scanTip']}</strong> ${flexyconsentData['scanTipText']}
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i>${flexyconsentData['cancel']}
                            </button>
                            <button type="button" class="btn btn-success" id="modalScanBtn" onclick="executeScan()">
                                <i class="fas fa-play me-2"></i>${flexyconsentData['startScan']}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);

            // Store modal reference globally for cleanup
            window.currentScanModal = bsModal;
            window.currentScanModalElement = modal;

            bsModal.show();

            // Auto-focus and select after modal is shown
            modal.addEventListener('shown.bs.modal', () => {
                const urlInput = document.getElementById('modalScanUrl');
                if (urlInput) {
                    setTimeout(() => {
                        urlInput.focus();
                        urlInput.select();
                        validateScanUrl(); // Initial validation
                    }, 100);
                }
            });

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
                // Clean up global variables
                delete window.currentScanDomainId;
                delete window.currentScanModal;
                delete window.currentScanModalElement;
            });
        }

        window.executeScan = async function () {
            const urlInput = document.getElementById('modalScanUrl');
            const scanBtn = document.getElementById('modalScanBtn');

            if (!urlInput) {
                console.error('URL input not found');
                flexyconsentResponseTop('alert-danger', 'Error: Form not found. Please try again.');
                return;
            }

            if (!scanBtn) {
                console.error('Scan button not found');
                return;
            }

            const url = urlInput.value.trim();
            const domainId = window.currentScanDomainId;

            if (!url) {
                urlInput.classList.add('is-invalid');
                urlInput.focus();
                return;
            }

            // Validate URL format
            try {
                new URL(url);
            } catch (e) {
                urlInput.classList.add('is-invalid');
                urlInput.focus();
                flexyconsentResponseTop('alert-danger', 'Please enter a valid URL');
                return;
            }

            if (!domainId) {
                console.error('Domain ID not found');
                flexyconsentResponseTop('alert-danger', 'Error: Domain not selected');
                return;
            }

            try {
                // Show loading state
                scanBtn.disabled = true;
                scanBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Starting Scan...';

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies-scanner',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId),
                        url: url
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        if (response.statusCode === 0) {
                            // Close modal
                            if (window.currentScanModal) {
                                window.currentScanModal.hide();
                            }

                            // Show success message
                            flexyconsentResponseTop('alert-success', 'Scan started successfully! Use "View Status" to check progress.');
                        } else {
                            flexyconsentResponseTop('alert-danger', 'Failed to start scan: ' + (response.statusMessage || 'Unknown error'));
                        }
                    },
                    error: function (error) {
                        console.error('Error starting scan:', error);
                        flexyconsentResponseTop('alert-danger', 'Error starting scan: ' + error.statusText);
                    }
                });
            } catch (error) {
                console.error('Error starting scan:', error);
                flexyconsentResponseTop('alert-danger', 'Error starting scan: ' + error.message);
            } finally {
                // Reset button state
                if (scanBtn) {
                    scanBtn.disabled = false;
                    scanBtn.innerHTML = '<i class="fas fa-play me-2"></i>' + (flexyconsentData['startScan']);
                }
            }
        }

        window.validateScanUrl = function () {
            const urlInput = document.getElementById('modalScanUrl');
            const scanBtn = document.getElementById('modalScanBtn');

            if (urlInput && scanBtn) {
                const isValid = urlInput.value.trim() !== '' && urlInput.checkValidity();
                scanBtn.disabled = !isValid;

                if (isValid) {
                    urlInput.classList.remove('is-invalid');
                    urlInput.classList.add('is-valid');
                } else {
                    urlInput.classList.remove('is-valid');
                    if (urlInput.value.trim() !== '') {
                        urlInput.classList.add('is-invalid');
                    }
                }
            }
        }

        async function viewScanStatus(domainId) {
            const viewStatusBtn = document.getElementById('viewStatusBtn');

            try {
                // Show loading state
                viewStatusBtn.disabled = true;
                viewStatusBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies-scanner',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        if (response.statusCode === 0) {
                            const results = response.results || [];
                            showScanStatusModal(results);
                        } else {
                            flexyconsentResponseTop('alert-danger', 'Failed to get scan status: ' + (response.statusMessage || 'Unknown error'));
                        }
                    },
                    error: function (error) {
                        console.error('Error getting scan status:', error);
                        flexyconsentResponseTop('alert-danger', 'Error getting scan status: ' + error.statusText);
                    }
                });
            } catch (error) {
                console.error('Error getting scan status:', error);
                flexyconsentResponseTop('alert-danger', 'Error getting scan status: ' + error.message);
            } finally {
                // Reset button state
                viewStatusBtn.disabled = false;
                viewStatusBtn.innerHTML = '<i class="fas fa-list me-2"></i>' + (flexyconsentData['viewStatus'] || 'View Status');
            }
        }

        function getStatusBadge(status) {
            switch (status) {
                case 1:
                    return `
                        <span class="badge bg-warning d-flex align-items-center gap-1">
                            <i class="fas fa-hourglass-half"></i>
                            Waiting
                        </span>
                    `;
                case 2:
                    return `
                        <span class="badge bg-info d-flex align-items-center gap-1">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            Processing
                        </span>
                    `;
                case 3:
                    return `
                        <span class="badge bg-success d-flex align-items-center gap-1">
                            <i class="fas fa-check-circle"></i>
                            Finished
                        </span>
                    `;
                default:
                    return `<span class="badge bg-secondary">Unknown</span>`;
            }
        }

        function getPreviewImageHtml(previewImageUri, url) {
            if (previewImageUri) {
                return `
                    <div class="position-relative" style="width: 80px; height: 60px; cursor: pointer;"
                        onclick="showPreviewImageModal('${previewImageUri}', '${url}')">
                        <img src="${previewImageUri}"
                            alt="Page Preview"
                            class="w-100 h-100 rounded border"
                            style="object-fit: cover;"
                            onerror="this.parentElement.innerHTML='<div class=\\'d-flex align-items-center justify-content-center w-100 h-100 bg-light rounded border\\' style=\\'color: #6c757d; font-size: 24px;\\'>🖼️</div>';">
                        <div class="position-absolute top-0 end-0 m-1 rounded-circle d-flex align-items-center justify-content-center"
                            style="background: rgba(0,0,0,0.7); width: 16px; height: 16px;">
                            <span style="color: white; font-size: 10px;">🔍</span>
                        </div>
                    </div>
                `;
            } else {
                return `
                    <div class="d-flex align-items-center justify-content-center bg-light rounded border"
                        style="width: 80px; height: 60px; color: #6c757d; font-size: 24px;">
                        🖼️
                    </div>
                `;
            }
        }

        window.toggleCookieList = function (index) {
            const isExpanded = expandedCookiesList[index] || false;
            expandedCookiesList[index] = !isExpanded;

            // Update the UI
            const cookieToggle = document.getElementById(`cookieToggle_${index}`);
            const cookieList = document.getElementById(`cookieList_${index}`);

            if (cookieToggle && cookieList) {
                cookieToggle.innerHTML = `
                    <span class="badge bg-success me-2" style="cursor: pointer;">
                        ${flexyconsentData['cookiesFound']} ${!isExpanded ? '▼' : '▶'}
                    </span>
                `;
                cookieList.style.display = !isExpanded ? 'block' : 'none';
            }
        }

        function renderCookieInfo(result, index) {
            let cookieInfoHtml = '';

            // Only show cookie info if scan is completed (status 3)
            if (result.status === 3 && (result.cookiesFound || result.numCookies !== undefined)) {
                cookieInfoHtml = `
                    <div class="mb-2">
                        <div class="d-flex gap-2 align-items-center flex-wrap">
                `;

                // Show expandable cookie names if available
                if (result.cookiesFound) {
                    const isExpanded = expandedCookiesList[index] || false;
                    cookieInfoHtml += `
                        <div>
                            <div id="cookieToggle_${index}" onclick="toggleCookieList('${index}')" style="cursor: pointer;">
                                <span class="badge bg-success" style="cursor: pointer;">
                                    ${flexyconsentData['cookiesFound']} ${isExpanded ? '▼' : '▶'}
                                </span>
                            </div>
                            <div id="cookieList_${index}" class="mt-2" style="display: ${isExpanded ? 'block' : 'none'};">
                                <div class="p-2 bg-light rounded border">
                                    <small class="text-muted fw-bold">${flexyconsentData['cookieNames']}:</small>
                                    <div class="mt-1 d-flex flex-wrap gap-1">
                                        ${renderCookieNames(result.cookiesFound)}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                }

                // Show cookie count if available
                if (result.numCookies !== undefined) {
                    cookieInfoHtml += `
                        <span class="badge bg-info">
                            ${result.numCookies} ${flexyconsentData['cookie']}${result.numCookies !== 1 ? 's' : ''}
                        </span>
                    `;
                }

                cookieInfoHtml += `
                        </div>
                    </div>
                `;
            }

            return cookieInfoHtml;
        }

        function renderCookieNames(cookiesFound) {
            let cookieNamesHtml = '';

            if (Array.isArray(cookiesFound)) {
                // Handle array format
                cookiesFound.forEach((cookieName, cookieIndex) => {
                    cookieNamesHtml += `
                        <span class="badge bg-info bg-opacity-75 text-dark">
                            ${String(cookieName)}
                        </span>
                    `;
                });
            } else if (typeof cookiesFound === 'string') {
                // Handle string format (comma-separated)
                const cookieNames = cookiesFound.split(',');
                cookieNames.forEach((cookieName, cookieIndex) => {
                    const trimmedName = cookieName.trim();
                    if (trimmedName) {
                        cookieNamesHtml += `
                            <span class="badge bg-info bg-opacity-75 text-dark">
                                ${trimmedName}
                            </span>
                        `;
                    }
                });
            } else {
                cookieNamesHtml = '<small class="text-muted">No cookie names available</small>';
            }

            return cookieNamesHtml;
        }

        window.showPreviewImageModal = function (imageUri, url) {
            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;

            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-image me-2"></i>
                                ${flexyconsentData['pagePreview']}
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body text-center">
                            ${url ? `
                                <div class="alert alert-info">
                                    <strong>${flexyconsentData['scannedUrl']}:</strong>
                                    <a href="${url}" target="_blank" class="ms-2">${url}</a>
                                </div>
                            ` : ''}
                            <img src="${imageUri}"
                                alt="Page Preview"
                                class="img-fluid rounded shadow"
                                style="height:60vh;width:100vw;object-fit:contain;"
                                onerror="this.parentElement.innerHTML='<div class=\\'alert alert-warning\\'>Preview image could not be loaded</div>';">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" onclick="window.open('${imageUri}', '_blank')">
                                <i class="fas fa-external-link-alt me-2"></i>
                                ${flexyconsentData['openInNewTab']}
                            </button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                ${flexyconsentData['close']}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }

        window.refreshScanStatus = async function () {
            const statusContent = document.getElementById('scanStatusContent');
            const refreshBtn = document.getElementById('refreshStatusBtn');

            if (statusContent && refreshBtn) {
                // Show loading state
                statusContent.innerHTML = `
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3 text-muted">${flexyconsentData['loadingStatus']}</p>
                    </div>
                `;

                refreshBtn.disabled = true;

                try {
                    const domainDropdown = document.getElementById('select_domain');
                    const domainId = domainDropdown ? domainDropdown.value : null;

                    if (!domainId) {
                        throw new Error('No domain selected');
                    }

                    $.ajax({
                        url: flexyconsentData.endpoint + 'cmp/page-cookies-scanner',
                        type: 'POST',
                        data: JSON.stringify({
                            email: flexyconsentData.email,
                            apiKey: flexyconsentData.apiKey,
                            domainId: parseInt(domainId)
                        }),
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            if (response.statusCode === 0) {
                                const results = response.results || [];
                                statusContent.innerHTML = renderScanStatusResults(results);
                            } else {
                                throw new Error(response.statusMessage || 'Unknown error');
                            }
                        },
                        error: function (error) {
                            const errorText = error.message || 'Unknown error';
                            console.error('HTTP Error Response:', errorText);
                            throw new Error('Failed to refresh scan status: ' + errorText);
                        }
                    });
                } catch (error) {
                    console.error('Error refreshing scan status:', error);
                    statusContent.innerHTML = `
                        <div class="text-center py-5">
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Error refreshing scan status: ${error.message}
                            </div>
                            <button class="btn btn-outline-primary mt-2" onclick="refreshScanStatus()">
                                <i class="fas fa-retry me-2"></i>Try Again
                            </button>
                        </div>
                    `;
                } finally {
                    refreshBtn.disabled = false;
                }
            }
        }

        let expandedCookiesList = {};

        async function showScanStatusModal() {
            // Create and show modal
            const modal = createScanStatusModal();
            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            // Clean up when modal is hidden
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
                expandedCookiesList = {}; // Reset expanded state when modal closes
            });

            try {
                // Fetch scan status results
                const domainDropdown = document.getElementById('select_domain');
                const domainId = domainDropdown ? domainDropdown.value : null;

                if (!domainId) {
                    throw new Error('No domain selected');
                }

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies-scanner',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        if (response.statusCode === 0) {
                            const results = response.results || [];
                            const statusContent = document.getElementById('scanStatusContent');
                            const refreshBtn = document.getElementById('refreshStatusBtn');

                            if (statusContent && refreshBtn) {
                                statusContent.innerHTML = renderScanStatusResults(results);
                                refreshBtn.disabled = false;
                            }
                        } else {
                            throw new Error(response.statusMessage || 'Unknown error');
                        }
                    },
                    error: function (error) {
                        const errorText = error.message || 'Unknown error';
                        console.error('HTTP Error Response:', errorText);
                        throw new Error('Failed to load scan status: ' + errorText);
                    }
                });
            } catch (error) {
                console.error('Error loading scan status:', error);

                const statusContent = document.getElementById('scanStatusContent');
                const refreshBtn = document.getElementById('refreshStatusBtn');

                if (statusContent && refreshBtn) {
                    statusContent.innerHTML = `
                <div class="text-center py-5">
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading scan status: ${error.message}
                    </div>
                    <button class="btn btn-outline-primary mt-2" onclick="refreshScanStatus()">
                        <i class="fas fa-retry me-2"></i>Try Again
                    </button>
                </div>
            `;
                    refreshBtn.disabled = false;
                }
            }
        }

        function createScanStatusModal() {
            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;

            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-list-ul me-2"></i>
                                ${flexyconsentData['scanStatus']}
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div id="scanStatusContent">
                                <div class="text-center py-5">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-3 text-muted">${flexyconsentData['loadingStatus']}</p>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" onclick="refreshScanStatus()" id="refreshStatusBtn">
                                <i class="fas fa-refresh me-2"></i>${flexyconsentData['refresh']}
                            </button>
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                ${flexyconsentData['close']}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            return modal;
        }

        function renderScanStatusResults(results) {
            if (!results || results.length === 0) {
                return `
                    <div class="text-center py-5">
                        <div class="mb-3">
                            <i class="fas fa-search fa-3x text-muted"></i>
                        </div>
                        <h5 class="mb-3">${flexyconsentData['noScansFound']}</h5>
                        <p class="text-muted">${flexyconsentData['startFirstScan']}</p>
                    </div>
                `;
            }

            let resultsHtml = `
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">${flexyconsentData['scanHistory']}</h6>
                        <span class="badge bg-info">${results.length} scan${results.length !== 1 ? 's' : ''}</span>
                    </div>
                </div>
                <div class="border rounded overflow-hidden" style="background-color: #f6f6f7;">
            `;

            results.forEach((result, index) => {
                const statusBadge = getStatusBadge(result.status);
                const previewImageHtml = getPreviewImageHtml(result.previewImageUri, result.url);
                const cookieInfoHtml = renderCookieInfo(result, index);

                // Better URL handling
                const urlDisplay = getUrlDisplay(result.url);

                resultsHtml += `
                    <div class="p-3 bg-white ${index < results.length - 1 ? 'border-bottom' : ''}" style="border-color: #e1e5e9;">
                        <div class="d-flex gap-3 align-items-start">
                            <!-- Preview Image -->
                            <div class="flex-shrink-0">
                                ${previewImageHtml}
                            </div>

                            <!-- Scan Details -->
                            <div class="flex-fill min-width-0">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div class="flex-fill min-width-0 me-3">
                                        ${urlDisplay.titleHtml}
                                        ${urlDisplay.linkHtml}
                                    </div>
                                    <div class="flex-shrink-0">
                                        ${statusBadge}
                                    </div>
                                </div>

                                <!-- Cookie Information -->
                                ${cookieInfoHtml}

                                <!-- Timestamps -->
                                <div class="d-flex gap-3 small text-muted">
                                    <span>
                                        <i class="fas fa-clock me-1"></i>
                                        Created: ${result.createdDate || 'N/A'}
                                    </span>
                                    ${result.completedDate ? `
                                        <span>
                                            <i class="fas fa-check-circle me-1"></i>
                                            Completed: ${result.completedDate}
                                        </span>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            resultsHtml += '</div>';
            return resultsHtml;
        }

        function getUrlDisplay(url) {
            if (!url || url.trim() === '') {
                return {
                    titleHtml: '<div class="fw-bold">Auto Scan</div>',
                    linkHtml: ''
                };
            }

            // Clean and validate the URL
            const cleanUrl = url.trim();
            let isValidUrl = false;
            let displayUrl = cleanUrl;

            try {
                // Validate URL
                new URL(cleanUrl);
                isValidUrl = true;
            } catch (e) {
                console.warn('Invalid URL detected:', cleanUrl);
                isValidUrl = false;
            }

            // Create truncated version for display
            const maxLength = 60;
            let truncatedUrl = displayUrl;
            if (displayUrl.length > maxLength) {
                truncatedUrl = displayUrl.substring(0, maxLength) + '...';
            }

            // Generate unique ID for tooltip
            const tooltipId = `url-tooltip-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

            const titleHtml = `
                <div class="fw-bold position-relative">
                    <span
                        id="${tooltipId}"
                        class="text-truncate d-inline-block"
                        style="max-width: 100%; cursor: help;"
                        title="${displayUrl}"
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                    >
                        ${truncatedUrl}
                    </span>
                </div>
            `;

            const linkHtml = isValidUrl ? `
                <div class="mt-1">
                    <a href="${cleanUrl}"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="text-decoration-none small text-muted"
                    onclick="handleUrlClick(event, '${cleanUrl.replace(/'/g, "\\'")}')"
                    >
                        <i class="fas fa-external-link-alt me-1"></i>View page
                    </a>
                    <button
                        class="btn btn-link btn-sm p-0 ms-2 text-muted"
                        style="font-size: 0.75rem; text-decoration: none;"
                        onclick="copyUrlToClipboard('${cleanUrl.replace(/'/g, "\\'")}')"
                        title="Copy URL to clipboard"
                    >
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            ` : `
                <div class="mt-1">
                    <span class="small text-warning">
                        <i class="fas fa-exclamation-triangle me-1"></i>Invalid URL format
                    </span>
                </div>
            `;

            // Initialize tooltip after a short delay to ensure element exists
            setTimeout(() => {
                const tooltipElement = document.getElementById(tooltipId);
                if (tooltipElement && window.bootstrap) {
                    new bootstrap.Tooltip(tooltipElement);
                }
            }, 100);

            return { titleHtml, linkHtml };
        }

        window.handleUrlClick = function (event, url) {
            try {
                // Validate URL before opening
                new URL(url);
                // Let the default behavior proceed (opening in new tab)
                return true;
            } catch (e) {
                event.preventDefault();
                console.error('Invalid URL:', url);
                flexyconsentResponseTop('alert-danger', 'Invalid URL format. Cannot open page.');
                return false;
            }
        }

        window.copyUrlToClipboard = async function (url) {
            try {
                await navigator.clipboard.writeText(url);
                flexyconsentResponseTop('alert-success', 'URL copied to clipboard!');
            } catch (err) {
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = url;
                textArea.style.position = 'fixed';
                textArea.style.opacity = '0';
                document.body.appendChild(textArea);
                textArea.select();

                try {
                    document.execCommand('copy');
                    flexyconsentResponseTop('alert-success', 'URL copied to clipboard!');
                } catch (e) {
                    flexyconsentResponseTop('alert-danger', 'Failed to copy URL. Please copy manually.');
                }

                document.body.removeChild(textArea);
            }
        }

        window.showAddCookieModal = function (data, domainId) {
            console.log('showAddCookieModal called with domainId:', domainId);

            const modal = createEnhancedCookieModal(flexyconsentData['addCookie'], {
                name: '',
                displayName: '',
                type: '',
                retentionPeriod: 'Session',
                custom: true,
                description: '',
                vendor: '',
                privacyUrl: '',
                script: ''
            }, (cookieData, modalDomainId) => {
                console.log('Add cookie callback called with domainId:', modalDomainId || domainId);
                addCookie(cookieData, data, modalDomainId || domainId);
            }, domainId);

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }

        function createEnhancedCookieModal(title, cookieData, onSave, domainId) {
            const modal = document.createElement('div');
            modal.classList.add('modal', 'fade');
            modal.tabIndex = -1;

            // Store domainId on the modal element for debugging
            modal.setAttribute('data-domain-id', domainId);
            console.log('Creating modal with domainId:', domainId);

            // Get selected language shortCode for description
            const languageDropdown = document.getElementById('select_language');
            let selectedLanguageCode = 'en_uk'; // default fallback to English

            if (languageDropdown && languageDropdown.selectedOptions.length > 0) {
                const selectedOption = languageDropdown.selectedOptions[0];
                const selectedId = selectedOption.value;

                // Try to get shortCode from data attribute first, then lookup by ID
                selectedLanguageCode = selectedOption.dataset.shortcode ||
                    selectedOption.getAttribute('data-shortcode') ||
                    getLanguageShortCodeById(selectedId) ||
                    'en_uk';
            }

            console.log('Modal created with language code:', selectedLanguageCode);

            // Get description for selected language
            let currentDescription = '';
            if (cookieData.description) {
                if (typeof cookieData.description === 'object') {
                    currentDescription = cookieData.description[selectedLanguageCode] || cookieData.description['en'] || '';
                } else {
                    // Handle legacy string descriptions
                    currentDescription = cookieData.description;
                }
            }

            modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">${title}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="validationErrors" class="alert alert-danger d-none"></div>
                    <form id="cookieForm" novalidate>
                        <!-- Basic Information -->
                        <div class="row">
                            <div class="col-12">
                                <h6 class="text-primary mb-3"><i class="fas fa-info-circle me-2"></i>${flexyconsentData['basicInformation']}</h6>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookieName" class="form-label">
                                        ${flexyconsentData['name']} <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="cookieName"
                                           value="${cookieData.name || ''}" required>
                                    <div class="invalid-feedback">${flexyconsentData['cookieNameRequired']}</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookieDisplayName" class="form-label">
                                        ${flexyconsentData['displayName']}
                                    </label>
                                    <input type="text" class="form-control" id="cookieDisplayName"
                                           value="${cookieData.displayName || ''}" placeholder="${flexyconsentData['displayNamePlaceHolder']}">
                                    <small class="form-text text-muted" ${flexyconsentData['displayNameNote']}></small>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookieType" class="form-label">
                                        ${flexyconsentData['type']} <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" id="cookieType" required>
                                        <option value="">${flexyconsentData['selectType']}</option>
                                        <option value="Essential" ${cookieData.type?.toLowerCase() === 'essential' ? 'selected' : ''}>${flexyconsentData['essential']}</option>
                                        <option value="Personalization" ${cookieData.type?.toLowerCase() === 'personalization' ? 'selected' : ''}>${flexyconsentData['personalization']}</option>
                                        <option value="Analytics" ${cookieData.type?.toLowerCase() === 'analytics' ? 'selected' : ''}>${flexyconsentData['analytics']}</option>
                                        <option value="Marketing" ${cookieData.type?.toLowerCase() === 'marketing' ? 'selected' : ''}>${flexyconsentData['marketing']}</option>
                                        <option value="Security" ${cookieData.type?.toLowerCase() === 'security' ? 'selected' : ''}>${flexyconsentData['security']}</option>
                                        <option value="Other" ${cookieData.type?.toLowerCase() === 'other' ? 'selected' : ''}>${flexyconsentData['other'] || 'Other'}</option>
                                    </select>
                                    <div class="invalid-feedback">${flexyconsentData['typeRequired']}</div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookieRetention" class="form-label">${flexyconsentData['retentionPeriod']}
                                    </label>
                                    <input type="text" class="form-control" id="cookieRetention"
                                           value="${cookieData.retentionPeriod || 'Session'}"
                                           placeholder="e.g., Session, 30 days, 1 year, etc.">
                                    <div class="form-text">${flexyconsentData['retentionPeriodNote']}</div>
                                </div>
                            </div>
                        </div>

                        <!-- Description and Purpose -->
                        <div class="row">
                            <div class="col-12">
                                <h6 class="text-primary mb-3 mt-4"><i class="fas fa-file-text me-2"></i>${flexyconsentData['descriptionPurpose']}</h6>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="cookieDescription" class="form-label">
                                ${flexyconsentData['description']} <span class="badge bg-success">${getLanguageNameByShortCode(selectedLanguageCode)}</span>
                            </label>
                            <textarea class="form-control" id="cookieDescription" rows="3"
                                      placeholder="Describe the purpose of this cookie, what data it stores, and why it is necessary...">${currentDescription}</textarea>
                            <small class="form-text text-muted">${flexyconsentData['descriptionLanguageNote']} (${getLanguageNameByShortCode(selectedLanguageCode)})</small>


                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookieVendor" class="form-label">
                                        ${flexyconsentData['vendor']}
                                    </label>
                                    <input type="text" class="form-control" id="cookieVendor"
                                           value="${cookieData.vendor || ''}" placeholder="Google, Facebook, etc.">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cookiePrivacyUrl" class="form-label">
                                        ${flexyconsentData['privacyUrl']}
                                    </label>
                                    <input type="url" class="form-control" id="cookiePrivacyUrl"
                                           value="${cookieData.privacyUrl || ''}" placeholder="https://example.com/privacy">
                                    <div class="invalid-feedback">Valid privacy URL is required</div>
                                </div>
                            </div>
                        </div>

                        <!-- Technical Details -->
                        <div class="row">
                            <div class="col-12">
                                <h6 class="text-primary mb-3 mt-4"><i class="fas fa-cogs me-2"></i>${flexyconsentData['technicalDetails']}</h6>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="cookieScript" class="form-label">${flexyconsentData['scriptUrl']}</label>
                            <input type="url" class="form-control" id="cookieScript"
                                      placeholder="${flexyconsentData['cookieScriptPlaceholder']}" value="${cookieData.script || ''}">
                            <small class="form-text text-muted">${flexyconsentData['cookieScriptNote']}</small>
                        </div>

                        <div class="alert alert-warning py-2 mb-3" role="alert">
                            <strong>${flexyconsentData['importantTitle']}</strong>
                            <p class="mb-2 mt-1">
                                ${flexyconsentData['importantNote']}
                            </p>
                            <p class="mb-1">
                                ${flexyconsentData['importantExample']}
                            </p>
                            <code class="d-block bg-light p-2 mb-2 rounded">
                                &lt;script async src="https://www.google-analytics.com/analytics.js"&gt;&lt;/script&gt;
                            </code>
                            <p class="mb-0">
                                ${flexyconsentData['importantConclusion']} <strong>https://www.google-analytics.com/analytics.js</strong>
                            </p>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        ${flexyconsentData['cancel']}
                    </button>
                    <button type="button" class="btn btn-primary" id="saveCookieBtn">
                        <i class="fas fa-save me-2"></i>${flexyconsentData['save']}
                    </button>
                </div>
            </div>
        </div>
    `;

            // Add save functionality with enhanced validation
            const saveBtn = modal.querySelector('#saveCookieBtn');
            const form = modal.querySelector('#cookieForm');
            const errorContainer = modal.querySelector('#validationErrors');

            saveBtn.addEventListener('click', () => {
                // Clear previous validation states
                form.classList.remove('was-validated');
                errorContainer.classList.add('d-none');

                // Get form data - Updated with multilingual description support using shortCode
                const nameValue = modal.querySelector('#cookieName').value.trim();
                const displayNameValue = modal.querySelector('#cookieDisplayName').value.trim();
                const descriptionValue = modal.querySelector('#cookieDescription').value.trim();
                const scriptValue = modal.querySelector('#cookieScript').value.trim();
                let typeValue = modal.querySelector('#cookieType').value;

                // If no script is provided and type is essential, change to other
                if (!scriptValue && typeValue === 'essential') {
                    typeValue = 'other';
                    console.log('Script is blank and type was essential - changed to other');
                }

                // Get selected language shortCode from dropdown based on the actual language structure
                const languageDropdown = document.getElementById('select_language');
                let selectedLanguageCode = 'en_uk'; // default fallback to English

                if (languageDropdown && languageDropdown.selectedOptions.length > 0) {
                    const selectedOption = languageDropdown.selectedOptions[0];
                    const selectedId = selectedOption.value;

                    // Try to find the language shortCode by matching the ID
                    selectedLanguageCode = selectedOption.dataset.shortcode ||
                        selectedOption.getAttribute('data-shortcode') ||
                        getLanguageShortCodeById(selectedId) ||
                        'en_uk';
                }

                console.log('Selected language code for description:', selectedLanguageCode);

                // Handle multilingual description
                let descriptionObject = {};
                if (cookieData.description && typeof cookieData.description === 'object') {
                    // Keep existing translations
                    descriptionObject = { ...cookieData.description };
                }
                // Update the description for the selected language
                descriptionObject[selectedLanguageCode] = descriptionValue;

                const formData = {
                    name: nameValue,
                    displayName: displayNameValue || nameValue, // Use name if displayName is empty
                    type: typeValue, // Use the potentially modified type
                    retentionPeriod: modal.querySelector('#cookieRetention').value.trim() || 'Session',
                    custom: true, // Always true for user-added/edited cookies
                    description: descriptionObject,
                    vendor: modal.querySelector('#cookieVendor').value.trim(),
                    privacyUrl: modal.querySelector('#cookiePrivacyUrl').value.trim(),
                    script: scriptValue,
                    id: cookieData.id || generateCookieId()
                };

                // Validate form data
                const validationErrors = validateCookieData(formData);

                if (validationErrors.length > 0) {
                    errorContainer.innerHTML = flexyconsentData['fixErrorMessage'] +
                        validationErrors.map(error => `<li>${error}</li>`).join('') + '</ul>';
                    errorContainer.classList.remove('d-none');
                    form.classList.add('was-validated');
                    return;
                }

                // Check HTML5 validation
                if (form.checkValidity()) {
                    onSave(formData);
                    bootstrap.Modal.getInstance(modal).hide();
                } else {
                    form.classList.add('was-validated');
                }
            });

            return modal;
        }

        function getLanguageShortCodeById(languageId) {
            // Language mapping based on the provided data structure
            const languageMap = {
                '1': 'tr_TR',     // Türkçe (Turkish)
                '2': 'en_uk',     // English
                '3': 'fr_fr',     // Français (French)
                '4': 'es_es',     // Español (Spanish)
                '5': 'de',        // Deutsch (German)
                '6': 'zh',        // 中文 (Chinese)
                '7': 'ar',        // اللغة العربية (Arabic)
                '8': 'ro',        // Română (Romanian)
                '9': 'ru',        // Русский (Russian)
                '10': 'ja',       // 日本語 (Japanese)
                '11': 'ko',       // 한국어 (Korean)
                '12': 'it_it',    // Italiano (Italian)
                '13': 'bg',       // Български (Bulgarian)
                '14': 'bs',       // Bosanski (Bosnian)
                '15': 'ca',       // Català (Catalan)
                '16': 'cs',       // Česky (Czech)
                '17': 'cy',       // Cymraeg (Welsh)
                '18': 'da',       // Dansk (Danish)
                '19': 'el',       // Ελληνική (Greek)
                '20': 'et',       // Eesti (Estonian)
                '21': 'eu',       // Euskara (Basque)
                '22': 'fi',       // Suomalainen (Finnish)
                '23': 'gl',       // Galego (Galician)
                '24': 'he',       // עִברִית (Hebrew)
                '25': 'hr',       // Hrvatski (Croatian)
                '26': 'hu',       // Magyar (Hungarian)
                '27': 'id',       // Bahasa Indonesia (Indonesian)
                '28': 'lt',       // Lietuvių kalba (Lithuanian)
                '29': 'lv',       // latviski (Latvian)
                '30': 'mk',       // македонски (Macedonian)
                '31': 'ms',       // Melayu (Malay)
                '32': 'mt',       // Malti (Malteze)
                '33': 'nl',       // Nederlands (Dutch)
                '34': 'nb',       // Norsk (Norwegian)
                '35': 'pl',       // Polski (Polish)
                '36': 'pt-br',    // Português - Brasil (Portuguese)
                '37': 'pt-pt',    // Português - Portugal (Portuguese)
                '38': 'sk',       // Slovenská (Slovak)
                '39': 'sl',       // Slovenski (Slovenian)
                '40': 'sr',       // Српски (Serbian)
                '41': 'sv',       // Svenska (Swedish)
                '42': 'uk',       // Українська (Ukrainian)
                '43': 'fl'        // Filipino (Tagalog)
            };

            return languageMap[languageId] || null;
        }

        function getLanguageNameByShortCode(shortCode) {
            const languageNames = {
                'tr_TR': 'TR',
                'en_uk': 'EN',
                'fr_fr': 'FR',
                'es_es': 'ES',
                'de': 'DE',
                'zh': 'ZH',
                'ar': 'AR',
                'ro': 'RO',
                'ru': 'RU',
                'ja': 'JA',
                'ko': 'KO',
                'it_it': 'IT',
                'bg': 'BG',
                'bs': 'BS',
                'ca': 'CA',
                'cs': 'CS',
                'cy': 'CY',
                'da': 'DA',
                'el': 'EL',
                'et': 'ET',
                'eu': 'EU',
                'fi': 'FI',
                'gl': 'GL',
                'he': 'HE',
                'hr': 'HR',
                'hu': 'HU',
                'id': 'ID',
                'lt': 'LT',
                'lv': 'LV',
                'mk': 'MK',
                'ms': 'MS',
                'mt': 'MT',
                'nl': 'NL',
                'nb': 'NB',
                'pl': 'PL',
                'pt-br': 'PT-BR',
                'pt-pt': 'PT-PT',
                'sk': 'SK',
                'sl': 'SL',
                'sr': 'SR',
                'sv': 'SV',
                'uk': 'UK',
                'fl': 'FL'
            };

            return languageNames[shortCode] || shortCode.toUpperCase();
        }

        function generateCookieId() {
            return Date.now() + Math.floor(Math.random() * 1000);
        }

        function validateCookieData(cookieData) {
            const errors = [];

            // Debug: Log the data being validated
            console.log('Validating cookie data:', cookieData);

            // Check required fields with more detailed logging
            if (!cookieData.name || cookieData.name.trim() === '') {
                console.log('Name validation failed:', cookieData.name);
                errors.push(flexyconsentData['cookieNameRequired']);
            }

            if (!cookieData.type || cookieData.type.trim() === '') {
                console.log('Type validation failed:', cookieData.type);
                errors.push(flexyconsentData['typeRequired']);
            }

            // Validate URL format for privacyUrl if provided
            if (cookieData.privacyUrl && cookieData.privacyUrl.trim() !== '') {
                try {
                    new URL(cookieData.privacyUrl);
                } catch (e) {
                    console.log('Privacy URL format validation failed:', cookieData.privacyUrl);
                    errors.push('Privacy URL must be a valid URL');
                }
            }

            console.log('Validation errors:', errors);
            return errors;
        }

        async function addCookie(cookieData, data, domainId) {
            try {
                console.log('addCookie called with:');
                console.log('- cookieData:', cookieData);
                console.log('- domainId:', domainId);
                console.log('- data:', data);

                // Validate domainId
                if (!domainId || domainId === 'null' || domainId === null) {
                    console.error('Invalid domainId:', domainId);

                    // Try to get domainId from dropdown
                    const domainDropdown = document.getElementById('select_domain');
                    if (domainDropdown && domainDropdown.value) {
                        domainId = domainDropdown.value;
                        console.log('Retrieved domainId from dropdown:', domainId);
                    } else {
                        flexyconsentResponseTop('alert-danger', 'Error: No domain selected. Please select a domain first.');
                        return;
                    }
                }

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    dataType: 'json',
                    success: async function (loadResponseBody) {
                        console.log('Current cookies loaded successfully:', loadResponseBody);
                        if (loadResponseBody.statusCode !== 0) {
                            throw new Error('Error loading current cookies: ' + (loadResponseBody.statusMessage || 'Unknown error'));
                        }

                        // Get current resources
                        let resources = loadResponseBody.resources || [];

                        // Add new cookie
                        resources.push(cookieData);

                        // Save updated resources
                        await saveCookieResources(resources, { value: { resources } }, domainId);
                        flexyconsentResponseTop('alert-success', flexyconsentData['cookieAddedSuccessfully']);

                        // Reload the cookie manager
                        loadCookiesForDomain(domainId);
                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to load current cookies:', status, error);
                        flexyconsentResponseTop('alert-danger', 'Failed to load current cookies: ' + error);
                        return;
                    }
                });
            } catch (error) {
                console.error('Error adding cookie:', error);
                flexyconsentResponseTop('alert-danger', 'Error adding cookie: ' + error.message);
            }
        }

        async function updateCookie(cookieData, data, domainId, originalCookie) {
            try {
                console.log('updateCookie called with:');
                console.log('- cookieData:', cookieData);
                console.log('- domainId:', domainId);
                console.log('- originalCookie:', originalCookie);

                // Validate domainId
                if (!domainId || domainId === 'null' || domainId === null) {
                    console.error('Invalid domainId:', domainId);

                    // Try to get domainId from dropdown
                    const domainDropdown = document.getElementById('select_domain');
                    if (domainDropdown && domainDropdown.value) {
                        domainId = domainDropdown.value;
                        console.log('Retrieved domainId from dropdown:', domainId);
                    } else {
                        flexyconsentResponseTop('alert-danger', 'Error: No domain selected. Please select a domain first.');
                        return;
                    }
                }

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    dataType: 'json',
                    success: async function (loadResponseBody) {
                        console.log('Current cookies loaded successfully:', loadResponseBody);
                        if (loadResponseBody.statusCode !== 0) {
                            throw new Error('Error loading current cookies: ' + (loadResponseBody.statusMessage || 'Unknown error'));
                        }

                        // Get current resources
                        let resources = loadResponseBody.resources || [];

                        // Find and update the cookie
                        const index = resources.findIndex(r =>
                            r.id === originalCookie.id ||
                            (r.name === originalCookie.name && r.displayName === originalCookie.displayName)
                        );

                        if (index !== -1) {
                            resources[index] = { ...resources[index], ...cookieData };
                        } else {
                            resources.push(cookieData);
                        }

                        // Save updated resources
                        await saveCookieResources(resources, { value: { resources } }, domainId);
                        flexyconsentResponseTop('alert-success', flexyconsentData['cookieUpdatedSuccessfully']);

                        // Reload the cookie manager
                        loadCookiesForDomain(domainId);
                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to load current cookies:', status, error);
                        flexyconsentResponseTop('alert-danger', 'Failed to load current cookies: ' + error);
                        return;
                    }
                });
            } catch (error) {
                console.error('Error updating cookie:', error);
                flexyconsentResponseTop('alert-danger', 'Error updating cookie: ' + error.message);
            }
        }

        async function cookieManagerDeleteCookie(cookie, data, domainId) {
            try {
                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId)
                    }),
                    dataType: 'json',
                    success: async function (loadResponseBody) {
                        console.log('Current cookies loaded successfully:', loadResponseBody);
                        if (loadResponseBody.statusCode !== 0) {
                            throw new Error('Error loading current cookies: ' + (loadResponseBody.statusMessage || 'Unknown error'));
                        }

                        // Get current resources
                        let resources = loadResponseBody.resources || [];

                        // Remove the cookie
                        const index = resources.findIndex(r => r.id === cookie.id ||
                            (r.name === cookie.name && r.displayName === cookie.displayName));

                        if (index !== -1) {
                            resources.splice(index, 1);
                        }

                        // Save updated resources
                        await saveCookieResources(resources, { value: { resources } }, domainId);
                        flexyconsentResponseTop('alert-success', flexyconsentData['cookieDeletedSuccessfully']);

                        // Reload the cookie manager
                        loadCookiesForDomain(domainId);
                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to load current cookies:', status, error);
                        flexyconsentResponseTop('alert-danger', 'Failed to load current cookies: ' + error);
                        return;
                    }
                });
            } catch (error) {
                console.error('Error deleting cookie:', error);
                flexyconsentResponseTop('alert-danger', 'Error deleting cookie: ' + error.message);
            }
        }

        function deleteCookieConfirm(cookie, data, domainId) {
            if (confirm((flexyconsentData['confirmDeleteCookie']) + '\n\n' +
                (flexyconsentData['cookieName']) + ': ' + cookie.name)) {
                cookieManagerDeleteCookie(cookie, data, domainId);
            }
        }

        async function saveCookieResources(resources, originalData, domainId) {
            console.log('saveCookieResources called with domainId:', domainId);

            return new Promise((resolve, reject) => {
                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/page-cookies',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        domainId: parseInt(domainId),
                        value: {
                            resources: resources,
                            lastUpdated: new Date().getTime()
                        }
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (responseBody) {
                        console.log('Cookie resources saved successfully:', responseBody);
                        if (responseBody.statusCode === 0) {
                            resolve(responseBody);
                        } else {
                            reject(new Error('Error saving cookie data: ' + (responseBody.statusMessage || 'Unknown error')));
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to save cookie resources:', status, error);
                        reject(new Error('Failed to save cookie resources: ' + error));
                    }
                });
            });
        }



        document.addEventListener('DOMContentLoaded', function () {
            // Add event delegation for copy button
            document.addEventListener('click', async function (e) {
                if (e.target && e.target.id === 'copyScriptBtn') {
                    const textarea = document.getElementById('scriptCodeArea');
                    const copyBtn = e.target;

                    try {
                        await navigator.clipboard.writeText(textarea.value);

                        // Show success feedback
                        const originalText = copyBtn.innerHTML;
                        copyBtn.innerHTML = `<i class="fas fa-check me-2"></i>${flexyconsentData['copied'] || 'Copied!'}`;
                        copyBtn.classList.remove('btn-primary');
                        copyBtn.classList.add('btn-success');

                        setTimeout(() => {
                            copyBtn.innerHTML = originalText;
                            copyBtn.classList.remove('btn-success');
                            copyBtn.classList.add('btn-primary');
                        }, 2000);

                    } catch (err) {
                        // Fallback
                        textarea.select();
                        document.execCommand('copy');

                        const originalText = copyBtn.innerHTML;
                        copyBtn.innerHTML = `<i class="fas fa-check me-2"></i>${flexyconsentData['copied'] || 'Copied!'}`;
                        copyBtn.classList.remove('btn-primary');
                        copyBtn.classList.add('btn-success');

                        setTimeout(() => {
                            copyBtn.innerHTML = originalText;
                            copyBtn.classList.remove('btn-success');
                            copyBtn.classList.add('btn-primary');
                        }, 2000);
                    }
                }
            });

            // Handle tab switching to preview
            document.addEventListener('shown.bs.tab', function (e) {
                if (e.target.id === 'preview-tab') {
                    loadPreview();
                }
            });
        });

        function findProjectIdByDomainId(domainId, projects) {
            if (!domainId || !projects || !Array.isArray(projects)) {
                return null;
            }

            // Convert domainId to number for comparison
            const targetDomainId = parseInt(domainId);

            // Search through all projects
            for (const project of projects) {
                if (project.domains && Array.isArray(project.domains)) {
                    // Check if this project contains the domain
                    const foundDomain = project.domains.find(domain =>
                        parseInt(domain.id) === targetDomainId
                    );

                    if (foundDomain) {
                        return project.id;
                    }
                }
            }

            return null; // Domain not found in any project
        }

        async function loadPreviewFromScript(scriptCode, projectId) {
            const previewContainer = document.getElementById('previewContainer');
            if (!previewContainer) return;

            try {
                // Extract script URL from the script tag (e.g., <script src="..."></script>)
                const scriptUrlMatch = scriptCode.match(/src=["']([^"']+)["']/);
                if (!scriptUrlMatch) {
                    throw new Error(flexyconsentData['couldNotExtractURL']);
                }

                const scriptUrl = scriptUrlMatch[1];

                // Clear the preview container and prepare it for script execution
                previewContainer.innerHTML = '<div id="cookie-declaration"></div>';

                // Create and load the script dynamically
                const script = document.createElement('script');
                script.src = scriptUrl;
                script.async = true;

                // Handle script load success
                script.onload = function () {
                    console.log('Cookie declaration script loaded successfully');
                    // The script should automatically render in the cookie-declaration div
                };

                // Handle script load error
                script.onerror = function () {
                    console.error('Failed to load cookie declaration script');
                    previewContainer.innerHTML = `
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>${flexyconsentData['previewUnavailable']}:</strong> ${flexyconsentData['previewUnavailableDesc']}
                    <br><br>
                    <div class="bg-light p-3 rounded mt-2">
                        <strong>${flexyconsentData['yourScript']}:</strong><br>
                        <code>${scriptCode}</code>
                    </div>
                    <br>
                    <small class="text-muted">
                        ${flexyconsentData['scriptWorksOnWebsite']}
                    </small>
                </div>
            `;
                };

                // Append script to document body to execute it
                document.body.appendChild(script);

                // Clean up script after some time
                setTimeout(() => {
                    if (document.body.contains(script)) {
                        document.body.removeChild(script);
                    }
                }, 10000);

            } catch (error) {
                console.error('Error loading preview:', error);
                previewContainer.innerHTML = `
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>${flexyconsentData['preview']}:</strong> ${flexyconsentData['scriptReadyToUse']}
                <br><br>
                <div class="bg-light p-3 rounded mt-2">
                    <strong>${flexyconsentData['yourScript']}:</strong><br>
                    <code>${scriptCode}</code>
                </div>
                <br>
                <small class="text-muted">
                    ${flexyconsentData['scriptDisplaysTablesDesc']}
                </small>
            </div>
        `;
            }
        }

        document.addEventListener('shown.bs.tab', function (e) {
            if (e.target.id === 'preview-tab') {
                const previewContainer = document.getElementById('previewContainer');
                if (previewContainer && previewContainer.innerHTML.includes(flexyconsentData['loadingPreviewDesc'])) {
                    const scriptCodeArea = document.getElementById('scriptCodeArea');
                    const domainDropdown = document.getElementById('select_domain');

                    if (scriptCodeArea && domainDropdown) {
                        // const projects = getProjects();
                        // const projectId = findProjectIdByDomainId(domainDropdown.value, projects);
                        const projectId = flexyconsentData.projectId;
                        loadPreviewFromScript(scriptCodeArea.value, projectId);
                    }
                }
            }
        });

        // Cookie Declaration Script
        function createCookieDeclarationCard(domainId) {
            const declarationCard = document.createElement('div');
            declarationCard.classList.add('card', 'mb-4');
            declarationCard.id = 'cookie_declaration_section';

            declarationCard.innerHTML = `
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-code me-2"></i>${flexyconsentData['cookieDeclarationScript']}
                </h5>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="collapse" data-bs-target="#declarationCardBody" aria-expanded="false" aria-controls="declarationCardBody">
                    <i class="fas fa-chevron-down" id="declarationToggleIcon"></i>
                </button>
            </div>
        </div>
        <div class="collapse" id="declarationCardBody">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h6 class="text-primary mb-3">
                            <i class="fas fa-file-code me-2"></i>${flexyconsentData['generateScriptForWebsite']}
                        </h6>
                        <p class="text-muted mb-3">
                            ${flexyconsentData['declarationScriptDescription']}
                        </p>
                        <div class="mb-2">
                            <h6 class="text-success mb-2">
                               ${flexyconsentData['scriptFeatures']}
                            </h6>
                            <ul class="list-unstyled mb-0">
                                <li class="mb-1">
                                    <i class="fas fa-table text-primary me-2"></i>
                                    ${flexyconsentData['scriptFeature1']}
                                </li>
                                <li class="mb-1">
                                    <i class="fas fa-mobile-alt text-info me-2"></i>
                                    ${flexyconsentData['scriptFeature2']}
                                </li>
                                <li class="mb-1">
                                    <i class="fas fa-sync text-warning me-2"></i>
                                    ${flexyconsentData['scriptFeature3']}
                                </li>
                                <li class="mb-1">
                                    <i class="fas fa-shield-alt text-secondary me-2"></i>
                                    ${flexyconsentData['scriptFeature4']}
                                </li>
                                <li class="mb-0">
                                    <i class="fas fa-link text-success me-2"></i>
                                    ${flexyconsentData['scriptFeature5']}
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="mb-4">
                                <i class="fas fa-code fa-3x text-primary mb-3"></i>
                                <h6><strong>${flexyconsentData['scriptActions'] || 'Script Actions'}</strong></h6>
                            </div>
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-primary btn-lg" id="generateScriptBtn">
                                    <i class="fas fa-code me-2"></i>${flexyconsentData['cookieDeclarationScript']}
                                </button>
                                <button type="button" class="btn btn-success" id="previewDeclarationBtn">
                                    <i class="fas fa-eye me-2"></i>${flexyconsentData['previewDeclaration']}
                                </button>
                                <button type="button" class="btn btn-info" id="viewInstructionsBtn">
                                    <i class="fas fa-info-circle me-2"></i>${flexyconsentData['viewInformation']}
                                </button>
                            </div>
                            <div class="mt-3 pt-3 border-top">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    ${flexyconsentData['oneTimeSetup']}
                                </small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Script Content Area (Initially Hidden) -->
                <div id="scriptContentArea" class="mt-4" style="display: none;">
                    <div class="border-top pt-4">
                        <div id="scriptLoadingContent">
                            <div class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">${flexyconsentData['loading']}</span>
                                </div>
                                <p class="mt-3 text-muted">${flexyconsentData['loadingScript']}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

            return declarationCard;
        }


        function displayEnhancedCookieManager(data, domainId) {
            console.log('displayEnhancedCookieManager called');

            const container = document.getElementById('cookie_manager_container');

            // Check if scanner section already exists
            const existingScanner = document.getElementById('cookie_scanner_section');
            const existingDeclaration = document.getElementById('cookie_declaration_section');

            if (existingScanner && existingDeclaration) {
                console.log('Scanner and Declaration sections already exist, not recreating');
                // Don't clear the container if both exist, just update the cookie list part
                const existingCookieCard = container.querySelector('.card:not(#cookie_scanner_section):not(#cookie_declaration_section)');
                if (existingCookieCard) {
                    existingCookieCard.remove();
                }
            } else {
                console.log('Creating new sections');
                container.innerHTML = '';

                // Add cookie scanner section first (Collapsed by default)
                const scannerSection = createCookieScannerSection(domainId);
                container.appendChild(scannerSection);

                // Add event listeners for scanner buttons
                const newScanBtn = document.getElementById('newScanBtn');
                const viewStatusBtn = document.getElementById('viewStatusBtn');

                if (newScanBtn) {
                    newScanBtn.addEventListener('click', () => showScanUrlModal(domainId));
                }

                if (viewStatusBtn) {
                    viewStatusBtn.addEventListener('click', () => viewScanStatus(domainId));
                }

                // Add cookie declaration card (Collapsed by default)
                const declarationCard = createCookieDeclarationCard(domainId);
                container.appendChild(declarationCard);

                // Add event listeners for declaration card
                const generateScriptBtn = document.getElementById('generateScriptBtn');
                const previewDeclarationBtn = document.getElementById('previewDeclarationBtn');
                const viewInstructionsBtn = document.getElementById('viewInstructionsBtn');

                if (generateScriptBtn) {
                    generateScriptBtn.addEventListener('click', () => loadCookieDeclarationScript(domainId));
                }

                if (previewDeclarationBtn) {
                    previewDeclarationBtn.addEventListener('click', () => showCookieDeclarationPreview(domainId));
                }

                if (viewInstructionsBtn) {
                    viewInstructionsBtn.addEventListener('click', () => showInstructionsInCard());
                }

                // Add toggle icon rotation for collapse/expand
                setupCollapseToggle('declarationCardBody', 'declarationToggleIcon');
                setupCollapseToggle('scannerCardBody', 'scannerToggleIcon');
                setupCollapseToggle('cookieListCardBody', 'cookieListToggleIcon');
            }

            // Create main cookie list card
            createCookieListCard(container, data, domainId);
        }

        function setupCollapseToggle(bodyId, iconId) {
            const cardBody = document.getElementById(bodyId);
            const toggleIcon = document.getElementById(iconId);

            if (cardBody && toggleIcon) {
                cardBody.addEventListener('show.bs.collapse', function () {
                    toggleIcon.classList.remove('fa-chevron-down');
                    toggleIcon.classList.add('fa-chevron-up');
                });

                cardBody.addEventListener('hide.bs.collapse', function () {
                    toggleIcon.classList.remove('fa-chevron-up');
                    toggleIcon.classList.add('fa-chevron-down');
                });
            }
        }

        function createCookieListCard(container, data, domainId) {
            const card = document.createElement('div');
            card.classList.add('card', 'shadow-sm');
            container.appendChild(card);

            // Cookie List Card Header
            const cardHeader = document.createElement('div');
            cardHeader.classList.add('card-header');
            card.appendChild(cardHeader);

            const headerContainer = document.createElement('div');
            headerContainer.classList.add('d-flex', 'justify-content-between', 'align-items-center');
            cardHeader.appendChild(headerContainer);

            const headerTitle = document.createElement('h5');
            headerTitle.classList.add('card-title', 'mb-0');
            headerTitle.innerHTML = '<i class="fas fa-list me-2"></i>' + (flexyconsentData['cookieList'] || 'Cookie List');
            headerContainer.appendChild(headerTitle);

            const headerToggleBtn = document.createElement('button');
            headerToggleBtn.type = 'button';
            headerToggleBtn.classList.add('btn', 'btn-outline-secondary', 'btn-sm');
            headerToggleBtn.setAttribute('data-bs-toggle', 'collapse');
            headerToggleBtn.setAttribute('data-bs-target', '#cookieListCardBody');
            headerToggleBtn.setAttribute('aria-expanded', 'false');
            headerToggleBtn.setAttribute('aria-controls', 'cookieListCardBody');
            headerToggleBtn.innerHTML = '<i class="fas fa-chevron-down" id="cookieListToggleIcon"></i>';
            headerContainer.appendChild(headerToggleBtn);

            // Cookie List Collapsible Body
            const cardBodyCollapse = document.createElement('div');
            cardBodyCollapse.classList.add('collapse');
            cardBodyCollapse.id = 'cookieListCardBody';
            card.appendChild(cardBodyCollapse);

            const cardBody = document.createElement('div');
            cardBody.classList.add('card-body');
            cardBodyCollapse.appendChild(cardBody);

            // Get cookies with proper filtering
            let cookies = [];
            if (data && data.value && Array.isArray(data.value.resources)) {
                cookies = data.value.resources.filter(resource => {
                    if (!resource) return false;
                    const cookieTypes = ['Essential', 'Personalization', 'Analytics', 'Marketing', 'Security', 'Other'];
                    return !resource.type ||
                        resource.type === 'cookie' ||
                        cookieTypes.includes(resource.type) ||
                        (resource.name && resource.displayName);
                });
            }

            // Add stats badges
            const statsContainer = document.createElement('div');
            statsContainer.classList.add('d-flex', 'gap-2', 'mb-4');

            const totalBadge = document.createElement('span');
            totalBadge.classList.add('badge', 'bg-primary', 'fs-6');
            totalBadge.textContent = cookies.length + ' Total';
            statsContainer.appendChild(totalBadge);

            const systemCount = cookies.filter(c => !c.custom).length;
            if (systemCount > 0) {
                const systemBadge = document.createElement('span');
                systemBadge.classList.add('badge', 'bg-outline-secondary', 'text-secondary', 'border', 'border-secondary', 'fs-6');
                systemBadge.textContent = systemCount + ' System';
                systemBadge.style.backgroundColor = 'transparent';
                statsContainer.appendChild(systemBadge);
            }

            const customCount = cookies.filter(c => c.custom).length;
            if (customCount > 0) {
                const customBadge = document.createElement('span');
                customBadge.classList.add('badge', 'bg-success', 'fs-6');
                customBadge.textContent = customCount + ' Custom';
                statsContainer.appendChild(customBadge);
            }

            cardBody.appendChild(statsContainer);

            // Action buttons and search container
            const actionsContainer = document.createElement('div');
            actionsContainer.classList.add('d-flex', 'justify-content-between', 'align-items-center', 'mb-4');

            const buttonsContainer = document.createElement('div');
            buttonsContainer.classList.add('d-flex', 'gap-2');

            const addButton = document.createElement('button');
            addButton.classList.add('btn', 'btn-primary');
            addButton.innerHTML = '<i class="fa fa-plus me-2"></i>' + (flexyconsentData['addCookie'] || 'Add Cookie');
            addButton.addEventListener('click', () => showAddCookieModal(data, domainId));
            buttonsContainer.appendChild(addButton);

            const refreshButton = document.createElement('button');
            refreshButton.classList.add('btn', 'btn-outline-secondary');
            refreshButton.innerHTML = '<i class="fa fa-refresh me-2"></i>' + (flexyconsentData['refresh'] || 'Refresh');
            refreshButton.addEventListener('click', () => loadCookiesForDomain(domainId));
            buttonsContainer.appendChild(refreshButton);

            actionsContainer.appendChild(buttonsContainer);

            // Search container
            const searchContainer = document.createElement('div');
            searchContainer.classList.add('d-flex', 'gap-2');

            const searchInput = document.createElement('input');
            searchInput.type = 'text';
            searchInput.classList.add('form-control');
            searchInput.placeholder = 'Search cookies...';
            searchInput.style.width = '250px';
            searchContainer.appendChild(searchInput);

            const filterSelect = document.createElement('select');
            filterSelect.classList.add('form-select');
            filterSelect.style.width = '150px';
            filterSelect.innerHTML = `
                <option value="all">${flexyconsentData['allTypes'] || 'All Types'}</option>
                <option value="Essential">${flexyconsentData['essential'] || 'Essential'}</option>
                <option value="Personalization">${flexyconsentData['personalization'] || 'Personalization'}</option>
                <option value="Analytics">${flexyconsentData['analytics'] || 'Analytics'}</option>
                <option value="Marketing">${flexyconsentData['marketing'] || 'Marketing'}</option>
                <option value="Security">${flexyconsentData['security'] || 'Security'}</option>
                <option value="Other">${flexyconsentData['other'] || 'Other'}</option>
            `;
            searchContainer.appendChild(filterSelect);

            actionsContainer.appendChild(searchContainer);
            cardBody.appendChild(actionsContainer);

            // Create table
            const tableContainer = document.createElement('div');
            tableContainer.classList.add('table-responsive');
            cardBody.appendChild(tableContainer);

            const table = document.createElement('table');
            table.classList.add('table', 'table-hover', 'cookie-manager-table', 'mb-0');
            table.id = 'cookiesTable';
            tableContainer.appendChild(table);

            const thead = document.createElement('thead');
            thead.classList.add('table-dark');
            table.appendChild(thead);
            const headerRow = document.createElement('tr');
            thead.appendChild(headerRow);

            const headers = [
                { key: 'displayName', text: 'Display Name', icon: 'fa-file-code', sortable: true },
                { key: 'name', text: 'Name', icon: 'fa-tag', sortable: true },
                { key: 'type', text: 'Type', icon: 'fa-layer-group', sortable: true },
                { key: 'retentionPeriod', text: 'Retention', icon: 'fa-clock', sortable: true },
                { key: 'actions', text: 'Actions', icon: 'fa-cogs', sortable: false }
            ];

            headers.forEach(header => {
                const th = document.createElement('th');
                th.classList.add('user-select-none');
                if (header.sortable) {
                    th.classList.add('cursor-pointer');
                    th.style.cursor = 'pointer';
                }

                const content = `<i class="fa ${header.icon} me-2"></i>` + (flexyconsentData[header.key] || header.text);
                if (header.sortable) {
                    th.innerHTML = content + ' <i class="fas fa-sort text-muted ms-1"></i>';
                    th.addEventListener('click', () => sortTable(header.key));
                } else {
                    th.innerHTML = content;
                }

                headerRow.appendChild(th);
            });

            const tbody = document.createElement('tbody');
            tbody.id = 'cookiesTableBody';
            table.appendChild(tbody);

            // Store cookies globally for search/filter
            window.currentCookies = cookies;

            // Render initial table
            renderCookieTable(cookies, data, domainId);

            // Add search and filter functionality
            let searchTimeout;
            searchInput.addEventListener('input', () => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    filterAndSearch(cookies, data, domainId);
                }, 300);
            });

            filterSelect.addEventListener('change', () => {
                filterAndSearch(cookies, data, domainId);
            });
        }

        async function loadCookieDeclarationScript(domainId) {
            const scriptContentArea = document.getElementById('scriptContentArea');
            const scriptLoadingContent = document.getElementById('scriptLoadingContent');

            if (!scriptContentArea || !scriptLoadingContent) {
                console.error('Script content area not found');
                return;
            }

            scriptContentArea.style.display = 'block';

            try {
                const domainDropdown = document.getElementById('select_domain');
                if (!domainDropdown || !domainDropdown.value) {
                    throw new Error(flexyconsentData['noDomainSelected']);
                }

                const currentDomainId = domainDropdown.value;
                // const projects = await getProjects();

                // if (!projects || !projects.length) {
                //     throw new Error(flexyconsentData['noProjectsAvailable']);
                // }

                // const projectId = findProjectIdByDomainId(currentDomainId, projects);
                // if (!projectId) {
                //     throw new Error(flexyconsentData['projectNotFound']);
                // }
                const projectId = flexyconsentData.projectId;

                // const data = {
                //     sid: getSid(),
                //     projectId: projectId
                // };

                // const response = await postRequest(endpoint + '/scriptcode', data);

                // if (response && response.ok) {
                //     const responseBody = await response.json();
                //     if (responseBody.statusCode === 0) {
                //         scriptLoadingContent.innerHTML = generateScriptCardContent(responseBody.cookiesScriptCode);
                //         window.currentCookieScript = responseBody.cookiesScriptCode;
                //     } else {
                //         throw new Error(responseBody.statusMessage || 'Server error');
                //     }
                // } else {
                //     throw new Error(flexyconsentData['failedToLoadScript']);
                // }
                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/scriptcode',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectId: parseInt(projectId)
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (responseBody) {
                        console.log('Script code fetched successfully:', responseBody);
                        if (responseBody.statusCode === 0) {
                            scriptLoadingContent.innerHTML = generateScriptCardContent(responseBody.cookiesScriptCode);
                            window.currentCookieScript = responseBody.cookiesScriptCode;
                        } else {
                            throw new Error(responseBody.statusMessage || 'Server error');
                        }
                    },
                    error: function (xhr, status, error) {
                       throw new Error(flexyconsentData['failedToLoadScript']);
                    }
                });
            } catch (error) {
                console.error('Error loading cookie declaration script:', error);
                scriptLoadingContent.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>${flexyconsentData['error']}:</strong> ${error.message}
                    </div>
                `;
            }
        }

        function generateScriptCardContent(scriptCode) {
            return `
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0 text-primary">
                    <i class="fas fa-code me-2"></i>${flexyconsentData['scriptTagForWebsite']}
                </h6>
                <button type="button" class="btn btn-primary btn-sm" onclick="copyScriptToClipboard()">
                    <i class="fas fa-copy me-2"></i>${flexyconsentData['copyScriptTag']}
                </button>
            </div>

            <div class="alert alert-info mb-3">
                <i class="fas fa-info-circle me-2"></i>
                <strong>${flexyconsentData['simpleIntegration']}:</strong>
                ${flexyconsentData['simpleIntegrationDesc']}
            </div>

            <div class="bg-light p-3 rounded border">
                <label class="form-label small text-muted">${flexyconsentData['htmlScriptTag']}:</label>
                <textarea
                    class="form-control font-monospace"
                    id="scriptCodeArea"
                    rows="3"
                    readonly
                    style="font-size: 0.9em; line-height: 1.4; background: white;"
                >${scriptCode}</textarea>
            </div>

            <div class="mt-4">
                <h6 class="fw-bold mb-2">${flexyconsentData['howToAddToWebsite']}:</h6>
                <div class="bg-light p-3 rounded">
                    <p class="mb-2 small"><strong>${flexyconsentData['option1AddToHead']}:</strong></p>
                    <pre class="mb-3" style="font-size: 0.85em;"><code>&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Your Website&lt;/title&gt;
    ${scriptCode.replace(/</g, '&lt;').replace(/>/g, '&gt;')}
&lt;/head&gt;
&lt;body&gt;
    &lt;div id="cookie-declaration"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>

                    <p class="mb-2 small"><strong>${flexyconsentData['option2AddToPage']}:</strong></p>
                    <pre style="font-size: 0.85em;"><code>&lt;div id="cookie-declaration"&gt;
    ${scriptCode.replace(/</g, '&lt;').replace(/>/g, '&gt;')}
&lt;/div&gt;</code></pre>
                </div>
            </div>

            <div class="mt-3">
                <small class="text-muted">
                    <i class="fas fa-shield-alt me-1"></i>
                    ${flexyconsentData['scriptSecurityDesc']}
                </small>
            </div>
        </div>
    `;
        }

        window.copyScriptToClipboard = async function() {
            const textarea = document.getElementById('scriptCodeArea');
            if (!textarea) {
                console.error('Script code area not found');
                return;
            }

            try {
                await navigator.clipboard.writeText(textarea.value);
                flexyconsentResponseTop('alert-success', flexyconsentData['scriptCopied']);
            } catch (err) {
                // Fallback for older browsers
                textarea.select();
                document.execCommand('copy');
                flexyconsentResponseTop('alert-success', flexyconsentData['scriptCopied']);
            }
        }


        function showInstructionsInCard() {
            const scriptContentArea = document.getElementById('scriptContentArea');
            const scriptLoadingContent = document.getElementById('scriptLoadingContent');

            if (!scriptContentArea || !scriptLoadingContent) {
                console.error('Script content area not found');
                return;
            }

            scriptContentArea.style.display = 'block';

            scriptLoadingContent.innerHTML = `
        <div class="row">
            <div class="col-md-8">
                <div class="alert alert-info mb-4">
                    <h6 class="alert-heading">
                        <i class="fas fa-info-circle me-2"></i>${flexyconsentData['whyNeedThis']}
                    </h6>
                    <p class="mb-2">${flexyconsentData['legalComplianceDesc']}
                    </p>
                    <ul class="mb-0 small">
                        <li>${flexyconsentData['listAllCookies']}</li>
                        <li>${flexyconsentData['showCookiePurposes']}</li>
                        <li>${flexyconsentData['helpComplyTransparency']}</li>
                        <li>${flexyconsentData['linkFromPrivacyPolicy']}</li>
                        <li>${flexyconsentData['updatesAutomatically']}</li>
                    </ul>
                </div>

                <h6 class="text-primary mb-3">
                    <i class="fas fa-rocket me-2"></i>${flexyconsentData['howToAddDeclaration']}
                </h6>

                <div class="mb-4">
                    <h6 class="fw-bold mb-2">${flexyconsentData['step1CopyScript']}</h6>
                    <p class="text-muted">${flexyconsentData['step1Desc']}</p>
                </div>

                <div class="mb-4">
                    <h6 class="fw-bold mb-2">${flexyconsentData['step2AddToHTML']}</h6>
                    <p class="text-muted">${flexyconsentData['step2Desc']}</p>
                    <pre class="bg-light p-3 rounded"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Cookie Declaration&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Our Cookie Declaration&lt;/h1&gt;
    &lt;div id="cookie-declaration"&gt;
        &lt;!-- Script will be inserted here --&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
                </div>

                <div class="mb-4">
                    <h6 class="fw-bold mb-2">${flexyconsentData['step3LinkFromPolicy']}</h6>
                    <p class="text-muted">${flexyconsentData['step3Desc']}</p>
                    <pre class="bg-light p-3 rounded"><code>&lt;a href="/cookies.html"&gt;View Our Cookie Declaration&lt;/a&gt;</code></pre>
                </div>

                <div class="mb-4">
                    <h6 class="fw-bold mb-2">${flexyconsentData['step4AutoUpdates']}</h6>
                    <p class="text-muted">${flexyconsentData['step4Desc'] || ''}</p>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card bg-light">
                    <div class="card-body">
                        <h6 class="card-title text-success">
                            <i class="fas fa-shield-check me-2"></i>${flexyconsentData['legalComplianceBenefits']}
                        </h6>
                        <ul class="list-unstyled mb-3 small">
                            <li class="mb-2"><i class="fas fa-check text-success me-2"></i>${flexyconsentData['gdprCompliance']}</li>
                            <li class="mb-2"><i class="fas fa-check text-success me-2"></i>${flexyconsentData['ccpaCompliance']}</li>
                            <li class="mb-2"><i class="fas fa-check text-success me-2"></i>${flexyconsentData['cookieLawCompliance']}</li>
                            <li class="mb-0"><i class="fas fa-check text-success me-2"></i>${flexyconsentData['isoCompliance']}</li>
                        </ul>

                        <h6 class="card-title text-info mt-4">
                            <i class="fas fa-star me-2"></i>${flexyconsentData['features']}
                        </h6>
                        <ul class="list-unstyled mb-0 small">
                            <li class="mb-2"><i class="fas fa-mobile-alt text-primary me-2"></i>${flexyconsentData['mobileResponsive']}</li>
                            <li class="mb-2"><i class="fas fa-palette text-info me-2"></i>${flexyconsentData['professionalStyling']}</li>
                            <li class="mb-2"><i class="fas fa-layer-group text-warning me-2"></i>${flexyconsentData['organizedByCategories']}</li>
                            <li class="mb-2"><i class="fas fa-link text-success me-2"></i>${flexyconsentData['privacyPolicyLinks']}</li>
                            <li class="mb-0"><i class="fas fa-sync text-secondary me-2"></i>${flexyconsentData['autoUpdatesWithChanges']}</li>
                        </ul>
                    </div>
                </div>

                <div class="alert alert-warning mt-3">
                    <i class="fas fa-lightbulb me-2"></i>
                    <strong>${flexyconsentData['important']}:</strong> ${flexyconsentData['scriptGeneratesTablesDesc']}
                </div>

                <div class="alert alert-info mt-3">
                    <i class="fas fa-users me-2"></i>
                    <strong>${flexyconsentData['userFriendly']}:</strong> ${flexyconsentData['userFriendlyDesc']}
                </div>
            </div>
        </div>
    `;
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        window.hideCookiePreview = function() {
            const scriptContentArea = document.getElementById('scriptContentArea');
            if (scriptContentArea) {
                scriptContentArea.style.display = 'none';
            }
        }

        function copyScriptFromPreview() {
            const scriptCode = window.currentCookieScript;

            if (!scriptCode) {
                flexyconsentResponseTop('alert-danger', flexyconsentData['noScriptToCopy']);
                return;
            }

            navigator.clipboard.writeText(scriptCode).then(() => {
                flexyconsentResponseTop('alert-success', flexyconsentData['scriptCopied']);
            }).catch(() => {
                // Fallback copy method
                const textarea = document.createElement('textarea');
                textarea.value = scriptCode;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                flexyconsentResponseTop('alert-success', flexyconsentData['scriptCopied']);
            });
        }

        async function showCookieDeclarationPreview(domainId) {
            const scriptContentArea = document.getElementById('scriptContentArea');
            const scriptLoadingContent = document.getElementById('scriptLoadingContent');

            if (!scriptContentArea || !scriptLoadingContent) {
                console.error('Script content area not found');
                return;
            }

            scriptContentArea.style.display = 'block';

            // Show loading state
            scriptLoadingContent.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">${flexyconsentData['loading']}</span>
            </div>
            <p class="mt-3 text-muted">${flexyconsentData['loadingPreview']}</p>
        </div>
    `;

            try {
                const domainDropdown = document.getElementById('select_domain');
                if (!domainDropdown || !domainDropdown.value) {
                    throw new Error(flexyconsentData['noDomainSelected']);
                }

                const currentDomainId = domainDropdown.value;
                // const projects = await getProjects();

                // if (!projects || !projects.length) {
                //     throw new Error(flexyconsentData['noProjectsAvailable']);
                // }

                // const projectId = findProjectIdByDomainId(currentDomainId, projects);
                // if (!projectId) {
                //     throw new Error(flexyconsentData['projectNotFound']);
                // }
                const projectId = flexyconsentData.projectId;

                // const data = {
                //     sid: getSid(),
                //     projectId: projectId
                // };

                // const response = await postRequest(endpoint + '/scriptcode', data);

                // if (response && response.ok) {
                //     const responseBody = await response.json();
                //     if (responseBody.statusCode === 0) {
                //         // Store both scripts globally
                //         window.currentCookieScript = responseBody.cookiesScriptCode;
                //         window.currentPageCode = responseBody.pageCode;

                //         // Display the preview with both scripts
                //         scriptLoadingContent.innerHTML = generatePreviewContent(
                //             responseBody.cookiesScriptCode,
                //             responseBody.pageCode
                //         );

                //     } else {
                //         throw new Error(responseBody.statusMessage || 'Server error');
                //     }
                // } else {
                //     throw new Error(flexyconsentData['failedToLoadScript']);
                // }

                $.ajax({
                    url: flexyconsentData.endpoint + 'cmp/scriptcode',
                    type: 'POST',
                    data: JSON.stringify({
                        email: flexyconsentData.email,
                        apiKey: flexyconsentData.apiKey,
                        projectId: parseInt(projectId)
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (responseBody) {
                        console.log('Script code fetched successfully for preview:', responseBody);
                        if (responseBody.statusCode === 0) {
                            // Store both scripts globally
                            window.currentCookieScript = responseBody.cookiesScriptCode;
                            window.currentPageCode = responseBody.pageCode;

                            // Display the preview with both scripts
                            scriptLoadingContent.innerHTML = generatePreviewContent(
                                responseBody.cookiesScriptCode,
                                responseBody.pageCode
                            );

                        } else {
                            throw new Error(responseBody.statusMessage || 'Server error');
                        }
                    },
                    error: function (xhr, status, error) {
                       throw new Error(flexyconsentData['failedToLoadScript']);
                    }
                });
            } catch (error) {
                console.error('Error loading preview:', error);
                scriptLoadingContent.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>${flexyconsentData['error']}:</strong> ${error.message}
            </div>
        `;
            }
        }

        function generatePreviewContent(scriptCode, pageCode) {
            const uniquePreviewId = 'cookie-declaration-preview-' + Date.now();

            const previewHtml = `
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0 text-primary">
                    <i class="fas fa-eye me-2"></i>${flexyconsentData['livePreviewTitle']}
                </h6>
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="hideCookiePreview()">
                    <i class="fas fa-times me-2"></i>${flexyconsentData['closePreview']}
                </button>
            </div>

            <div class="alert alert-info mb-3">
                <i class="fas fa-info-circle me-2"></i>
                <strong>${flexyconsentData['previewNote']}:</strong>
                ${flexyconsentData['livePreviewDesc'] || ''}
            </div>

            <!-- Script Code Display -->
            <div class="mb-3">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="text-muted mb-0">
                        <i class="fas fa-code me-1"></i>${flexyconsentData['yourScriptCodeTitle']}
                    </h6>
                    <button class="btn btn-sm btn-primary" onclick="copyScriptFromPreview()">
                        <i class="fas fa-copy me-1"></i>${flexyconsentData['copyScript'] || 'Copy Script'}
                    </button>
                </div>
                <div class="bg-light p-3 rounded border">
                    <code class="d-block" style="background-color: transparent; word-break: break-all; font-size: 0.85em;">
                        ${escapeHtml(scriptCode)}
                    </code>
                </div>
            </div>

            <!-- Preview Container -->
            <div class="border rounded p-4 bg-white" style="max-height: 600px; overflow-y: auto;">
                <div id="${uniquePreviewId}">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">${flexyconsentData['loadingPreview']}</span>
                        </div>
                        <p class="mt-2 text-muted">${flexyconsentData['loadingPreviewDesc']}</p>
                    </div>
                </div>
            </div>

            <div class="mt-3">
                <div class="alert alert-success">
                    <i class="fas fa-check-circle me-2"></i>
                    <strong>${flexyconsentData['readyToUse']}:</strong> ${flexyconsentData['readyToUseDesc']}
                </div>
            </div>
        </div>
    `;

            // Load the complex script after a short delay
            setTimeout(() => {
                loadComplexScriptPreview(scriptCode, pageCode, uniquePreviewId);
            }, 100);

            return previewHtml;
        }

        function loadComplexScriptPreview(cookiesScriptCode, pageCode, containerId) {
            const container = document.getElementById(containerId);
            if (!container) {
                console.error('Preview container not found');
                return;
            }

            try {
                // Always treat as complex script
                const iframe = document.createElement('iframe');
                iframe.style.width = '100%';
                iframe.style.minHeight = '500px';
                iframe.style.border = 'none';
                iframe.style.backgroundColor = 'white';

                // Use minimal sandboxing to allow the scripts to work
                iframe.sandbox = 'allow-scripts allow-same-origin allow-popups allow-forms';

                // Build the complete HTML with both pageCode and cookiesScriptCode
                const iframeContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    body {
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                        padding: 20px;
                        background: white;
                        color: #333;
                        line-height: 1.6;
                    }
                    .cookie-declaration-wrapper {
                        max-width: 1200px;
                        margin: 0 auto;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin: 20px 0;
                        background: white;
                        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                    }
                    th, td {
                        padding: 12px 15px;
                        text-align: left;
                        border: 1px solid #e0e0e0;
                    }
                    th {
                        background-color: #f8f9fa;
                        font-weight: 600;
                        color: #2c3e50;
                        text-transform: uppercase;
                        font-size: 0.85em;
                        letter-spacing: 0.5px;
                    }
                    tr:nth-child(even) {
                        background-color: #fafafa;
                    }
                    tr:hover {
                        background-color: #f0f0f0;
                    }
                    .cookie-category {
                        margin: 30px 0;
                    }
                    .category-title {
                        font-size: 1.4em;
                        font-weight: 600;
                        margin-bottom: 15px;
                        color: #2c3e50;
                        border-bottom: 2px solid #3498db;
                        padding-bottom: 10px;
                    }
                    .cookie-description {
                        margin: 10px 0;
                        color: #666;
                        font-size: 0.95em;
                    }
                    /* Specific styles for cookie declaration elements */
                    #cookie-declaration {
                        min-height: 100px;
                    }
                    .cookie-table-container {
                        margin: 20px 0;
                    }
                    .cookie-policy-link {
                        color: #3498db;
                        text-decoration: none;
                    }
                    .cookie-policy-link:hover {
                        text-decoration: underline;
                    }
                    /* Loading state */
                    .loading {
                        text-align: center;
                        padding: 40px;
                        color: #999;
                    }
                    /* Error state */
                    .error-message {
                        background: #fee;
                        border: 1px solid #fcc;
                        color: #c33;
                        padding: 15px;
                        border-radius: 4px;
                        margin: 20px 0;
                    }
                </style>
                ${pageCode ? `
                <!-- Page Code (Additional Scripts/Styles) -->
                ${pageCode}
                ` : ''}
            </head>
            <body>
                <div class="cookie-declaration-wrapper">
                    <div id="cookie-declaration">
                        <!-- Cookie tables will be injected here -->
                    </div>
                </div>

                <!-- Cookie Declaration Script -->
                ${cookiesScriptCode}

                <!-- Fallback detection script -->
                <script>
                    // Check if content was loaded after 3 seconds
                    setTimeout(function() {
                        var container = document.getElementById('cookie-declaration');
                        if (container && container.innerHTML.trim() === '') {
                            container.innerHTML = '<div class="error-message">Cookie declaration is loading... If this message persists, please check your browser console for errors.</div>';
                        }
                    }, 3000);

                    // Auto-adjust iframe height
                    function adjustHeight() {
                        if (window.parent && window.parent.postMessage) {
                            var height = document.body.scrollHeight;
                            window.parent.postMessage({
                                type: 'adjustHeight',
                                height: height
                            }, '*');
                        }
                    }

                    // Adjust height on load and after content changes
                    window.addEventListener('load', adjustHeight);
                    setTimeout(adjustHeight, 1000);
                    setTimeout(adjustHeight, 2000);
                    setTimeout(adjustHeight, 5000);

                    // Watch for DOM changes
                    var observer = new MutationObserver(adjustHeight);
                    observer.observe(document.body, {
                        childList: true,
                        subtree: true
                    });
                </script>
            </body>
            </html>
        `;

                iframe.srcdoc = iframeContent;

                // Listen for height adjustment messages
                window.addEventListener('message', function (e) {
                    if (e.data && e.data.type === 'adjustHeight') {
                        iframe.style.height = (e.data.height + 50) + 'px';
                    }
                });

                iframe.onload = function () {
                    console.log('Preview iframe loaded successfully');
                };

                iframe.onerror = function () {
                    console.error('Preview iframe failed to load');
                    showFallbackPreview(container, cookiesScriptCode);
                };

                container.innerHTML = '';
                container.appendChild(iframe);

            } catch (error) {
                console.error('Error loading preview:', error);
                showFallbackPreview(container, cookiesScriptCode);
            }
        }

        function showFallbackPreview(container, scriptCode) {
            container.innerHTML = `
        <div class="alert alert-warning">
            <h6 class="alert-heading">
                <i class="fas fa-exclamation-triangle me-2"></i>${flexyconsentData['previewLimitations']}
            </h6>
            <p>${flexyconsentData['previewCannotBeDisplayed']}</p>
            <div class="bg-light p-3 rounded mt-3">
                <strong>${flexyconsentData['yourGeneratedScript']}:</strong>
                <pre class="mb-0 mt-2" style="white-space: pre-wrap; word-break: break-all;">
                    <code>${escapeHtml(scriptCode)}</code>
                </pre>
            </div>
            <hr>
            <div class="d-flex justify-content-between align-items-center">
                <small class="text-muted">
                    <i class="fas fa-shield-alt me-1"></i>
                    ${flexyconsentData['browserSecurityFeature']}
                </small>
                <button class="btn btn-sm btn-primary" onclick="copyScriptFromPreview()">
                    <i class="fas fa-copy me-1"></i>${flexyconsentData['copyScript']}
                </button>
            </div>
        </div>
    `;
        }

        function getProject() {
            $.ajax({
            url: flexyconsentData.endpoint + 'project/get',
            type: 'POST',
            data: JSON.stringify(
                {
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                    project: flexyconsentData.projectId
                }
            ),
            contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.statusCode === 0) {
                        return response.projects || [];
                    } else {
                        throw new Error(response.statusMessage || 'Failed to fetch projects');
                    }
                },
                error: function (error) {
                    console.error('Error fetching projects:', error);
                    return [];
                }
            });
        }
        function getProjects() {
            $.ajax({
                url: flexyconsentData.endpoint + 'project/list',
                type: 'POST',
                data: JSON.stringify({
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                }),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    if (response.statusCode === 0) {
                        return response.projects || [];
                    } else {
                        throw new Error(response.statusMessage || 'Failed to fetch projects');
                    }
                },
                error: function (error) {
                    console.error('Error fetching projects:', error);
                    return [];
                }
            });
        }
    }

    /**
     * Call Functions
     */
    $(function () {
        flexyconsent_init();
        flexyconsent_startPage();
        flexyconsent_userSettingsPage();
        flexyconsent_updateUserSettingsPage();
        flexyconsent_updateEmailPage();
        flexyconsent_updateEmailValidateKeyPage();
        flexyconsent_deleteAccountPage();
        flexyconsent_dashboardPage();
        flexyconsent_projectSettingsPage();
        flexyconsent_subscriptionPage();
        flexyconsent_paymentPage();
        flexyconsent_cookieManagerPage();

        flexyconsentSetTooltips();
    });

    // Helpers
    function flexyconsentResponse($class, message, url, urlText) {
        if (url && urlText) {
            htmlUrl = '<a href ="' + url + '">' + urlText + '</a>';
            message = message.replace('[URL]', htmlUrl);
            message = message.replace('&lt;', '<').replace('&gt;', '>');
        }
        $('#flexyconsent-result').removeClass().addClass('alert ' + $class + '').html(message);
    }
    function flexyconsentResponseTop($class, $message) {
        $('#flexyconsent-result-top').removeClass('d-none').addClass('alert ' + $class + '').html($message);
    }
    function flexyconsentGoPage(page) {
        location.href = flexyconsentData.redirectRoot + page
    }
    function flexyconsentReturnPage(page) {
        return flexyconsentData.redirectRoot + page
    }

    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function saveOption(key, value) {
        const options = [
            { key: key, value: value },
        ];

        $.ajax({
            url: flexyconsentData.resturl + 'flexyconsent/v1/option',
            type: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
            },
            data: jQuery.param({ updates: options }),
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (response) {
                // flexyconsentResponse('alert-success', 'Options saved');
            },
            error: function (error) {
                console.log(error);
                if (error.responseText) {
                    error = error.responseText;
                }
                flexyconsentResponse('alert-danger', error);
            }
        });
    }

    function saveOptions(options) {
        $.ajax({
            url: flexyconsentData.resturl + 'flexyconsent/v1/option',
            type: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
            },
            data: jQuery.param({ updates: options }),
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (response) {
                // flexyconsentResponse('alert-success', 'Options saved');
            },
            error: function (error) {
                console.log(error);
                if (error.responseText) {
                    error = error.responseText;
                }
                flexyconsentResponse('alert-danger', error);
            }
        });
    }

    function saveOptionsAndGoPage(options, page) {
        $.ajax({
            url: flexyconsentData.resturl + 'flexyconsent/v1/option',
            type: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
            },
            data: jQuery.param({ updates: options }),
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (response) {
                if (page) {
                    flexyconsentGoPage(page);
                }
            },
            error: function (error) {
                console.log(error);
                if (error.responseText) {
                    error = error.responseText;
                }
                flexyconsentResponse('alert-danger', error);
            }
        });
    }


    // function flexyconsent_convert_message(message,element) {
    //     let brackets = message.match(/\[(.*?)\]/);
    //     if(brackets) {
    //         message = message.replace(brackets[0], element.infoForRequest[brackets[1]]);
    //         return flexyconsent_convert_message(message,element);
    //     } 
    //     return message;        
    // }
    function flexyconsent_convert_message(message, response) {
        let brackets = message.match(/\[(.*?)\]/);
        if (brackets && response[brackets[1]]) {
            message = message.replace(brackets[0], response[brackets[1]]);
            return flexyconsent_convert_message(message, response);
        }
        return message;
    }

    function isRealEmail() {
        return flexyconsentData.email.includes("@");
    }

    function flexyconsentSetTooltips() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
}(jQuery));

