import wccRest from "@/helpers/api";
import store from '@/store/store';

/**
 * Fetch vendor json file from database
 * 
 * @returns {object}
 */
const vendorData = await fetchJson();
export function _wccGetElementByTag(tag) {
    const item = document.querySelector('[data-tag=' + tag + ']')
    return item ? item : false;
}
// ********************Event Registers******************//
/**
 * Register event handler for all the action elements.
 */
export function _wccRegisterListeners() {
    _wccAttachListener("category-tab", () => _wccShowTab('wccIABSectionCookie'));
    _wccAttachListener("purpose-tab", () => _wccShowTab('wccIABSectionPurpose'));
    _wccAttachListener("vendor-tab", () => _wccShowTab('wccIABSectionVendor'));
    _wccInitiAccordionTabs();
}

/**
 * Bind click event to banner elements.
 * 
 * @param {string} tag data-tag of the element
 * @param {function} fn callback function
 */
export function _wccAttachListener(tag, fn) {
    document.querySelectorAll('[data-tag=' + tag + ']').forEach(item => {
        item && item.addEventListener("click", fn);
    })
}

// ********************Banner functions*****************//
/**
 * Get the banner container
 * 
 * @returns {object}
 */
export function _wccSetVendorCount(banner, html) {
    // Check if `window.wccConfig.settings.vendors` is defined and not empty, otherwise use `window.wccConfig.vendors`
    let vendors = (window.wccConfig.settings && Object.keys(window.wccConfig.settings.vendors || {}).length > 0) ? 
    window.wccConfig.settings.vendors : (window.wccConfig.vendors || {});

    let vendorCount = Array.isArray(vendors.thirdpartyvendors) ? vendors.thirdpartyvendors.length : 0;
    const gacm_status = banner.properties.settings.gacm_enabled;
    if (gacm_status) {
        vendorCount += Array.isArray(vendors.googlevendors) ? vendors.googlevendors.length : 0;
    }
    // Replace all instances of {{count}} in the HTML string with vendorCount
    const updatedHtml = html.replace(/\{\{count\}\}/g, vendorCount);

    return updatedHtml;
}
// Define section names array
const sectionNames = ['wccIABSectionCookie', 'wccIABSectionPurpose', 'wccIABSectionVendor'];
export function _wccShowTab(tagName = false) {
    sectionNames.forEach(validTagName => {
        _wccNavBar();
        const tab = _wccGetTab(validTagName);
        if (validTagName === tagName) {
            tab && tab.classList.remove('wcc-hide');
        } else {
            tab && tab.classList.add('wcc-hide');
        }
    });
}
export function _wccNavBar() {
    // Get all buttons
    const buttons = document.querySelectorAll('.wcc-iab-nav-item');

    // Add click event listeners to each button
    buttons.forEach(button => {
        button.addEventListener('click', function () {
            // Remove 'wcc-iab-nav-item-active' from all buttons
            buttons.forEach(btn => btn.classList.remove('wcc-iab-nav-item-active'));

            // Add 'wcc-iab-nav-item-active' only to the clicked button
            this.classList.add('wcc-iab-nav-item-active');
        });
    });
}
export function _wccGetTab(tagName = false) {
    const tab = _wccGetElementByTag(tagName);
    return tab && tab || false;
}
// ***************Accordion functions****************//
/**
 * Add support for accordion tabs on the privacy overview screen.
 */
export function _wccInitiAccordionTabs() {
    _wccIabInnerAccordionClickListener('wccIABSectionPurpose');
    _wccIabInnerAccordionClickListener('wccIABSectionVendor');
    document.querySelectorAll(".wcc-child-accordion .wcc-child-accordion-item").forEach((item) => (
        item.addEventListener('click', function (event) {
            if (event.target.type === 'checkbox') return;
            this.parentNode.classList.toggle('wcc-child-accordion-active');
        })
    ));
    // Enable / disable all purposes/features consent based on user action
    const checkboxes = document.querySelectorAll('.wcc-consents-checkbox');
    checkboxes.forEach(function (checkbox) {
        checkbox.addEventListener('change', wcc_enable_disable_consent);
    });
}
export function wcc_enable_disable_consent() {
    let el = this.getAttribute('data-tag');
    const nestedInputs = document.querySelectorAll('.wcc-' + el + '-checkbox, .wcc-' + el + '-legitimate-interests-checkbox');
    const isChecked = this.checked;
    nestedInputs.forEach(input => {
        input.checked = isChecked;
    });
}
export function _wccIabInnerAccordionClickListener(containerId) {
    const accordionItems = document.querySelectorAll(`#${containerId} .wcc-accordion .wcc-accordion-iab-item`);
    accordionItems.forEach((item) => {
        item.addEventListener('click', function (event) {
            if (event.target.type === 'checkbox') return;
            this.parentNode.classList.toggle('wcc-accordion-active');
        });
    });
    _cliAddVendorList();
    const banner = store.state.banners.current;
    if (!banner || !banner.properties) return;
    const gacm_status = banner.properties.settings.gacm_enabled;
    if (gacm_status) {
        _cliAddGoogleVendorList()
    }
}
export async function fetchJson() {
    try {
        // Fetch the vendor file from the API
        const response = await wccRest.post({
            path: "banners/fetchJson",
            data: { content: 'en' },
        });
        return response; // Store the fetched data
    } catch (error) {
        // Handle errors
        console.error('API Error:', error);
    }
}

export let vendorListGenerated = false;
let oldVendorsCount = 0; // Initialize oldGoogleVendorsCount to 0 for the first load

// Generate vendor details content
export function _cliAddVendorList() {
    // Check if `window.wccConfig.settings.vendors` is defined and not empty, otherwise use `window.wccConfig.vendors`
    let vendors = (window.wccConfig.settings && Object.keys(window.wccConfig.settings.vendors || {}).length > 0) ? 
    window.wccConfig.settings.vendors : (window.wccConfig.vendors || {});
    const thirdpartyvendors = vendorData.vendors;
    let allowedthirdpartyvendors = vendors.thirdpartyvendors;
    // Check if allowedthirdpartyvendors is an array of numbers, then convert to array of objects
    if (Array.isArray(allowedthirdpartyvendors) && typeof allowedthirdpartyvendors[0] === 'number') {
        allowedthirdpartyvendors = allowedthirdpartyvendors.map(vendorId => ({ id: String(vendorId) }));
    }
    const allowedthirdpartyvendorsCount = allowedthirdpartyvendors.length;
    const vendorListElement = document.querySelector(`#accordion-vendors .wcc-accordion-body`);
    const vendorListClickElement = document.querySelector(`#accordion-vendors .wcc-accordion-iab-item`);
    if (!vendorListElement || !vendorListClickElement) return;
    // Add click event listener to the vendor list
    vendorListClickElement.addEventListener('click', async function () {
        try {
            // Check if the vendor list has already been generated
            if (vendorListGenerated && oldVendorsCount === allowedthirdpartyvendorsCount) {
                return; // Exit if the vendor list has already been generated
            }
            // Show loader while content is being loaded
            vendorListElement.innerHTML = `<div class="wcc_loader" style="font-size:14px;">Loading...</div>`;
            // Load content asynchronously
            const content = await loadVendorList(thirdpartyvendors,'vendors',allowedthirdpartyvendors);
            // Display content
            vendorListElement.innerHTML = content;
            vendorListGenerated = true;
            oldVendorsCount = allowedthirdpartyvendorsCount;
        } catch (error) {
            console.error('Error loading vendor list:', error);
            // Display error message if content loading fails
            vendorListElement.innerHTML = '<div class="error">Failed to load vendor list. Please try again.</div>';
        }
    });
}
export let googleVendorListGenerated = false;
let oldGoogleVendorsCount = 0; // Initialize oldGoogleVendorsCount to 0 for the first load

export function _cliAddGoogleVendorList() {
    // Check if `window.wccConfig.settings.vendors` is defined and not empty, otherwise use `window.wccConfig.vendors`
    let vendors = (window.wccConfig.settings && Object.keys(window.wccConfig.settings.vendors || {}).length > 0) ? 
    window.wccConfig.settings.vendors : (window.wccConfig.vendors || {});
    
    const googleVendors = vendorData.googleVendors;
    let allowedGoogleVendors = vendors.googlevendors;
    // Check if allowedGoogleVendors is an array of strings and convert it to an array of objects
    if (Array.isArray(allowedGoogleVendors) && typeof allowedGoogleVendors[0] === 'string') {
        allowedGoogleVendors = allowedGoogleVendors.map(vendorId => ({ id: vendorId }));
    }
    const allowedGoogleVendorsCount = allowedGoogleVendors.length;
    
    const vendorListElement = document.querySelector(`#accordion-google-vendors .wcc-accordion-body`);
    const vendorListClickElement = document.querySelector(`#accordion-google-vendors .wcc-accordion-iab-item`);
    
    if (!vendorListElement || !vendorListClickElement) return;

    // Add click event listener to the vendor list
    vendorListClickElement.addEventListener('click', async function () {
        try {
            // Check if the vendor list has already been generated and if the count hasn't changed
            if (googleVendorListGenerated && oldGoogleVendorsCount === allowedGoogleVendorsCount) {
                return; // Exit if the vendor list has already been generated and the count is the same
            }

            // Show loader while content is being loaded
            vendorListElement.innerHTML = `<div class="cli_loader" style="font-size:14px;">Loading...</div>`;
            
            // Load content asynchronously
            const content = await loadVendorList(googleVendors, 'google-vendors', allowedGoogleVendors);
            
            // Display content
            vendorListElement.innerHTML = content;
            
            // Mark the vendor list as generated
            googleVendorListGenerated = true;
            
            // Save the current vendor count for future comparisons
            oldGoogleVendorsCount = allowedGoogleVendorsCount;
            
        } catch (error) {
            console.error('Error loading vendor list:', error);
            
            // Display error message if content loading fails
            vendorListElement.innerHTML = '<div class="error">Failed to load vendor list. Please try again.</div>';
        }
    });
}

export async function loadVendorList(vendors,key,allowedkeys) {
    // Simulate asynchronous loading with a setTimeout
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            try {
                // Generate HTML content for vendor details
                const content = generateVendorListHtml(vendors,key,allowedkeys);
                resolve(content);
            } catch (error) {
                reject(error);
            }
        }, 1000); // Simulating a delay of 1 second (you can adjust as needed)
    });
}
export function generateVendorListHtml(vendors, key, allowedkeys) {
    // Convert allowedkeys array to a set for efficient lookup
    const allowedKeySet = new Set(allowedkeys.map(item => item.id));

    let html = '';
    Object.values(vendors)
        .filter(vendor => allowedKeySet.has(String(vendor.id))) // Filter vendors based on allowed keys
        .forEach((vendor) => {
            html += `
                <div class="wcc-child-accordion" id="wcc-${key}-consents-content-${vendor.id}" aria-labelledby="wcc-${key}-consents-content-${vendor.id}">
                    <div class="wcc-child-accordion-item">
                        <div class="wcc-child-accordion-chevron"><i class="wcc-chevron-right"></i></div>
                        <div class="wcc-child-accordion-header-wrapper">
                            <button class="wcc-child-accordion-btn" aria-label="${vendor.name}" data-tag="detail-category-title" style="color:#212121">${vendor.name}</button>`;
                            // Check if vendor has legitimate interests
                            html += `<div class="wcc-switch-wrapper">`;
                            if (vendor.legIntPurposes && vendor.legIntPurposes.length > 0 && key === 'vendors') {
                                html += `
                                    <div class="wcc-switch wcc-legitimate-switch-wrapper wcc-switch-separator wcc-switch-sm" data-tag="detail-category-toggle">
                                        <label for="wcc-${key}-legitimate-interests-checkbox-item-${vendor.id}" class="wcc-legitimate-interest">Legitimate interest</label>
                                        <input type="checkbox" class="wcc-iab-checkbox wcc-${key}-checkbox" id="wcc-${key}-legitimate-interests-checkbox-item-${vendor.id}"/>
                                    </div>`;
                            }
                            html += `
                                <div class="wcc-switch wcc-consent-switch-wrapper wcc-switch-sm" data-tag="detail-category-toggle">
                                    <label for="wcc-${key}-consents-checkbox-item-${vendor.id}" class="wcc-switch wcc-checkbox-label">Consent</label>
                                    <input type="checkbox" id="wcc-${key}-consents-checkbox-item-${vendor.id}" class="wcc-iab-checkbox wcc-${key}-checkbox">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="wcc-child-accordion-body" aria-hidden="true"></div>
                </div>`;
        });
    return html;
}
// Reset vendorListGenerated to false
export function _wccResetVendorListGenerated() {
    // Reset vendorListGenerated to false
    vendorListGenerated = false;
    // Reset googleVendorListGenerated to false
    googleVendorListGenerated = false;
}