import store from '@/store/store';
import wccRest from "@/helpers/api";
import * as core from '@/modules/banners/helpers/core';
import * as iab from '@/modules/banners/helpers/iab';


const preview = {
    shortCodes: window.wccBannerConfig._shortCodes,
    /**
     * Generate preview based on banner values
     * 
     * @param {object} banner Banner object.
     * @param {boolean} render check if banner should be rendered or not.
     */
    generate: async function (force = false, preview = true) {
        const banner = store.state.banners.current;
        let template = await this.getTemplate(force);
        if (banner) {
            await this.renderBannerStyles(template.styles);
            const html = this.refreshBannerStyles(banner.properties);
            await this.renderBannerHtml(html, preview);
        }
    },
    startLoading() {
        const container = document.getElementById('wcc-banner-preview-container');
        container && container.classList.add('wcc-preview-partial-refreshing');
    },
    stopLoading() {
        const container = document.getElementById('wcc-banner-preview-container');
        container && container.classList.remove('wcc-preview-partial-refreshing');
    },
    getTemplate: async function (force = false) {
        const banner = store.state.banners.current;
        if (!banner || !banner.properties) return;
        const preferenceCenter =  banner.properties.settings.preferenceCenter;
        const type = ( preferenceCenter !== 'push-down' ) ? banner.properties.settings.type : 'classic';
        const law = banner.properties.settings.applicableLaw;
        const iab_status = banner.properties.settings.iab_enabled;
        const templates = store.state.banners.template || [];
        if (
            Object.prototype.hasOwnProperty.call(templates, law) &&
            Object.prototype.hasOwnProperty.call(templates[law], type) &&
            force === false &&
            banner.properties.settings.is_enabled === iab_status
        ) {
            return templates[law][type];
        }
        const template = await this.getPreviewHtml(banner);
        if (template.html) {
            const lawTemplates = templates[law] || [];
            lawTemplates[type] = template;
            templates[law] = lawTemplates;
            await store.dispatch('banners/setTemplate', templates);
            return templates[law][type];
        }
    },
    showPreview: async function (force = false) {
        if (store.state.banners.preview === true) {
            await this.generate(force);
        } else {
            this.hidePreview();
        }
    },
    forceShowPreview: async function () {
        await this.generate(true);
    },
    forceRerenderPreview: async function () {
        if (store.state.banners.preview === true) {
            await this.generate(true, false);
        }
    },
    hidePreview: function () {
        const container = document.getElementById('wcc-banner-preview-container');
        if (container !== null) {
            document.body.removeChild(container);
        }
        //Remove wcc-popup-overflow class from <body>
        if (document.body && document.body.classList.contains('wcc-popup-overflow')) {
            document.body.classList.remove('wcc-popup-overflow');
        }
        //Reset vendor list generated constants when preview closed.
        const banner = store.state.banners.current;
        if (!banner || !banner.properties) return;
        const iab_status = banner.properties.settings.iab_enabled;
        if (iab_status) {
            iab._wccResetVendorListGenerated();
        }
    },
    closePreview: function (clear = true) {
        store.state.banners.preview = false;
        if (clear === true) {
            this.clearTemplate();
        }
        this.hidePreview();
    },
    clearTemplate: function () {
        store.state.banners.template = [];
        store.state.banners.current = false // Reset current banner to false on Vuex state.
    },
    resetTemplate() {
        store.state.banners.template = [];
    },
    renderBannerHtml: async function (html, preview = true) {
        if (!html || !preview) return;
        const banner = store.state.banners.current;
        if (!banner || !banner.properties) return;
        const iab_status = banner.properties.settings.iab_enabled;
        if (iab_status) {
            html = iab._wccSetVendorCount(banner,html);
        }
        let container = document.getElementById('wcc-banner-preview-container');
        if (container === null) {
            container = document.createElement('div');
            container.id = 'wcc-banner-preview-container';
            container.className = 'wcc-banner-preview';
            document.body.insertBefore(container, document.body.firstChild);
        } else {
            const banner = document.querySelector('.wcc-consent-container');
            if (banner) {
                container.innerHTML = '';
            }
        }
        const doc = new DOMParser().parseFromString(html, 'text/html');
        this.updateCategoryPeview(doc);
        core._wccReplaceSrcAttribute(doc, 'detail-close');
        core._wccReplaceSrcAttribute(doc, 'close-button');
        core._wccReplaceSrcAttribute(doc, 'detail-powered-by');
        core._wccReplaceSrcAttribute(doc, 'revisit-consent');
        core._wccReplaceSrcAttribute(doc, 'optout-powered-by');
        core._wccSetFooterShadow(doc);
        container.insertAdjacentHTML(
            "afterbegin",
            doc.body.innerHTML
        );
        core._wccRegisterListeners();
        if (iab_status) {
            iab._wccRegisterListeners();
        }
        core._wccAddPositionClass();
        core._wccShowBanner();
        core._wccSetShowMoreLess();
        core._wccSetPreferenceCheckBoxStates();
        core._wccAttachReadMore(document);
        core._wccAddRtlClass();
        core._wccSetPoweredBy();
        core._wccSetCCPAOptions();
        this.attachPreviewCloseBtn();
    },
    renderBannerStyles: async function (styles) {
        const bannerStyle = document.getElementById('wcc-banner-style');
        if (bannerStyle !== null) {
            document.getElementsByTagName('head')[0].removeChild(bannerStyle);
        }
        const style = document.createElement('style');
        style.id = 'wcc-banner-style';
        style.innerHTML = styles;
        document.getElementsByTagName('head')[0].appendChild(style);

    },
    refreshBannerStyles: function (data) {
        const banner = store.state.banners.current;
        if (!banner) return;
        const preferenceCenter =  banner.properties.settings.preferenceCenter;
        const type = ( preferenceCenter !== 'push-down' ) ? banner.properties.settings.type : 'classic';
        const law = banner.properties.settings.applicableLaw;
        const template = store.state.banners.template[law][type];
        const html = template.html;
        if (!html) return;
        const doc = new DOMParser().parseFromString(html, 'text/html');
        core._wccAttachReadMore(doc);
        const obj = data.config;
        const keyExists = (obj) => {
            Object.keys(obj).forEach(key => {
                if (typeof obj[key] === 'object' && obj[key] !== null) {
                    if (Object.prototype.hasOwnProperty.call(obj[key], 'tag')) {
                        let config = obj[key];
                        let tag = config['tag'] ? config['tag'] : '';
                        if (tag != '') {
                            doc.querySelectorAll(`[data-tag^="${tag}"]`).forEach(function (item) {
                                let status = config['status'] && true === config['status'] ? true : false;
                                if (status === false) {
                                    item.parentNode.removeChild(item);
                                }
                                preview.addStylesToElement(item, config)
                            });
                        }
                    }
                    keyExists(obj[key]);
                }
            })
        }
        keyExists(obj);
        this.updateCategoryPeview(doc);
        return doc.body.innerHTML;
    },
    updateCategoryPeview(doc) {
        const categories = store.state.cookies.items;
        if (!categories) return;
        categories.forEach(function (item) {
            if (item.slug === 'necessary') return;
            let element = doc.getElementById(`wccDetailCategory${item.slug}`);
            if (item.visibility === false) {
                element && element.parentNode.removeChild(element);
            }
        });
    },
    addStylesToElement: function (element, config) {
        if (config !== null && element !== null && ( element.getAttribute('data-tag') !== 'detail-category-title' && element.getAttribute('data-tag') !== 'detail-category-description' && element.getAttribute('data-tag') !== 'detail-category-toggle')) {
            let styles = '';
            for (const key in config.styles) {
                styles += `${key}: ${config.styles[key]};`;
            }
            element.style.cssText += styles;
        }
    },
    getPreviewHtml: async function (data) {
        try {
            return await wccRest.post({
                path: `/banners/preview`,
                params: {
                    language: store.state.languages.current,
                },
                data: data,
            });
        } catch (error) {
            console.log(error)
        }
    },
    attachPreviewCloseBtn() {
        const banner = store.state.banners.current;
        if (!banner) return;
    
        const preferenceCenter = banner.properties.settings.preferenceCenter;
        const type = (preferenceCenter !== 'push-down') ? banner.properties.settings.type : 'classic';
        if (type === 'box' || type === 'banner' || type === 'classic' || type === 'popup') {
            // Ensure we get the correct container element
            const bannerContainer = document.querySelector('.wcc-consent-container');
            if (bannerContainer) {
                // Find the wcc-consent-bar element inside the bannerContainer
                let consentBar = bannerContainer.querySelector('.wcc-consent-bar');
                if (consentBar) {
                    // Hide the button with class wcc-banner-btn-close inside the consentBar
                    const closeButton = consentBar.querySelector('.wcc-banner-btn-close');
                    if (closeButton) {
                        closeButton.style.display = 'none';
                    }
                    // Get the class names of the wcc-consent-bar element
                    const classNames = bannerContainer.className.split(' ');
                    // Determine insertion position based on class names
                    let insertionPosition = 'afterend';
                    let isTopPosition = false;
                    
                    classNames.forEach(className => {
                        if (className.includes('bottom') || className.includes('center')) {
                            insertionPosition = 'beforebegin';
                        }
                        if (className.includes('top')) {
                            isTopPosition = true;
                        }
                    });
    
                    // Define the URL for the SVG image
                    const imgUrl = `${window.wccGlobals.app.url}img/close-icon.svg`;
    
                    // Insert close preview button based on insertionPosition
                    const closeButtonHtml = `
                        <div class="wcc-preview-btn-wrapper" style="display: flex; justify-content:end; width:100%;">
                            <button type="button" id="wcc-close-preview-btn" class="wcc-button wcc-button-blue">
                                <img src="${imgUrl}" alt="Close Icon" class="close-preview-icon"/>
                                <span>Close Preview</span>
                            </button>
                        </div>`;
    
                    if (type === 'classic' && isTopPosition) {
                        // Add preview button as the last div of bannerContainer
                        bannerContainer.insertAdjacentHTML('beforeend', closeButtonHtml);
                    } else {
                        consentBar.insertAdjacentHTML(insertionPosition, closeButtonHtml);
                    }
    
                    // Attach event listener to close preview button
                    const button = document.getElementById('wcc-close-preview-btn');
                    button.addEventListener('click', this.closePreview.bind(this));
    
                    // Style the button
                    button.style.cssText = `
                        display: flex;
                        align-items:center;
                        justify-content: space-evenly;
                        float: right;
                        background: #FFEBDF;
                        font-size: 14px;
                        font-weight: 600;
                        line-height: 16px;
                        text-align: center;
                        color: #CC4014;
                        width: 156px;
                        height: 36px;
                        border-color: transparent;
                        cursor: pointer;`;
    
                    if (insertionPosition === 'beforebegin') {
                        button.style.marginBottom = '10px';
                    } else {
                        button.style.marginTop = '10px';
                    }
                }
            }
        }
    },
    parseDom(str) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(str, 'text/html');
        return doc.body;
    },
};
export default preview;