<template>
    <fragment>
        <div class="wcc-row" v-if="appliedLaw === 'gdpr'">
            <modal ref="confirmationModal" :class="['wcc-app-modal-' + modalType, 'wcc-general-tab-iab-modal']">
                <template v-slot:header>
                    <h4>{{ modalHeader }}</h4>
                </template>
                <template v-slot:body>
                    <div v-if="loading" class="wcc-app-modal-body-loader-class">
                        <p class="wcc-loading-text">
                        <loader />
                        {{ $i18n.__("Loading", "webtoffee-cookie-consent") }}
                        </p>
                    </div>
                    <div v-else>
                        <div v-if="modalType === 'purpose_feature'">
                            <div class="wcc-row">
                                <div class="wcc-col-12">
                                    <!-- Custom HTML for Purpose Feature Modal -->
                                    <div class="wcc-banner-layout-wrap">
                                        <div class="wcc-button-group">
                                            <button v-for="category in purposeFeatures" :key="category.type" :class="[
                                                'wcc-layout-type-button',
                                                { selected: category.type === selectedLayoutType },
                                            ]" @click="selectLayoutType(category.type)" :data-test-id="`wcc-layout-type-${category.type}`">
                                                {{ category.type }}
                                            </button>
                                        </div>
                                        <div :class="['wcc-layout-items-container']">
                                            <div class="wcc-layout-item-title">{{ getLayoutTitle() }}</div>
                                            <div v-for="item in selectedLayoutItems" :key="item.id"
                                                :class="`wcc-layout-item wcc-${selectedLayoutTypeClass}`">
                                                <input type="checkbox"
                                                    :id="`wcc-checkbox-${selectedLayoutTypeClass}-${item.id}`" :value="item.id"
                                                    :checked="isItemChecked(item.id, selectedLayoutTypeClass)"
                                                    @change="handleItemCheckboxChange(item.id, selectedLayoutTypeClass)" 
                                                    :data-test-id="`wcc-checkbox-${selectedLayoutTypeClass}-${item.id}`" />
                                                <label :for="`wcc-checkbox-${selectedLayoutTypeClass}-${item.id}`">{{ item.name
                                                }}</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else-if="modalType === 'vendors'">
                            <div class="wcc-row">
                                <div class="wcc-col-12">
                                    <div class="wcc-banner-layout-wrap">
                                        <div class="wcc-button-group">
                                            <button v-for="category in vendorList" :key="category.type" :class="[
                                                'wcc-layout-type-button',
                                                { selected: category.type === selectedVendorType },
                                            ]" @click="selectVendorType(category.type)" :data-test-id="`wcc-layout-type-${category.type}`">
                                                {{ getVendorLayoutTitle(category.type) }}
                                            </button>
                                            {{  }}
                                        </div>
                                        <div :class="['wcc-layout-items-container']">
                                            
                                            <div class="wcc-layout-item-title">{{ getVendorLayoutDescription() }}</div>
                                            <div class="wcc-search-wrap">
                                                <div class="wcc-vendor-search-input">
                                                    <input type="text" class="wcc-form-control" v-model="searchText"
                                                        :placeholder="$i18n.__('Search...', 'webtoffee-cookie-consent')"
                                                        ref="wccSearchInput" />
                                                </div>
                                                <div class="wcc-selected-list">
                                                    <div class="checkbox-container"
                                                        v-if="selectedCount > 0 && selectedCount < totalCount">
                                                        <input type="checkbox" id="wcc-custom-checkbox"
                                                            class="wcc-hidden-checkbox"
                                                            @click="unselectAll(selectedVendorType)" :data-test-id="`wcc-custom-checkbox`" />
                                                        <label for="wcc-custom-checkbox" class="wcc-custom-checkbox-label" :data-test-id="`wcc-custom-checkbox-label`">
                                                            <span class="wcc-checkbox-icon" style="cursor:pointer;">-</span>
                                                            <span>{{ selectedCount }} of {{ totalCount }} selected</span>
                                                        </label>
                                                    </div>
                                                    <div v-else>
                                                        <input type="checkbox" v-model="selectAllChecked"
                                                            @change="handleSelectAll(selectedVendorType)" :data-test-id="`wcc-select-all-checkbox`">
                                                        <span>{{ selectedCount }} of {{ totalCount }} selected</span>
                                                        <span v-if="selectedCount > 0" @click="unselectAll(selectedVendorType)"
                                                            style="cursor:pointer;"></span>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="wcc-vendor-list-section">
                                                <div v-for="item in filteredVendorItems" :key="item.id"
                                                    :class="`wcc-layout-item wcc-${selectedVendorTypeClass}`">
                                                    <input type="checkbox"
                                                        :id="`wcc-checkbox-${selectedVendorTypeClass}-${item.id}`"
                                                        :value="item.id"
                                                        :checked="isItemChecked(item.id, selectedVendorTypeClass, true)"
                                                        @change="handleItemCheckboxChange(item.id, selectedVendorTypeClass, true)" 
                                                        :data-test-id="`wcc-checkbox-${selectedVendorTypeClass}-${item.id}`" />
                                                    <label :for="`wcc-checkbox-${selectedVendorTypeClass}-${item.id}`">{{
                                                        item.name }}</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else>
                            <div class="wcc-row">
                                <div class="wcc-col-12">
                                    {{ modalBody }}
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
                <template v-slot:footer>
                    <div class="wcc-app-modal-actions wcc-app-reset-settings wcc-justify-end">
                        <button class="wcc-button wcc-button-no-style" @click="closeModal" :data-test-id="`wcc-cancel-button`">
                            {{ $i18n.__("Cancel", "webtoffee-cookie-consent") }}
                        </button>
                        <base-button class="wcc-button-primary" ref="wccIABSavebutton" @click.native="confirmAction" :disabled="updating" :data-test-id="`wcc-iab-settings-save-button`">
                            <template slot="loader">{{ modalConfirmButton }} </template>
                            {{ modalConfirmButton }}
                        </base-button>
                    </div>
                </template>
            </modal>
            <div class="wcc-col-12">
                <div class="wcc-app-box">
                    <div class="wcc-row wcc-align-center">
                        <label class="wcc-col-label wcc-checkbox-iab-title" for="wcc-checkbox-iab-title" style="font-weight: bold">
                            {{
                                $i18n.__(
                                    "IAB TCF 2.3",
                                    "webtoffee-cookie-consent"
                                )
                            }}
                        </label>
                        <base-switch v-model="iabEnabled" name="iab-toggle" :data-test-id="`wcc-iab-toggle`" />
                    </div>
                </div>
            </div>
        </div>
        <div class="wcc-row" v-if="iabEnabled && appliedLaw === 'gdpr'">
            <div class="wcc-col-12">
                <div class="wcc-app-box">
                    <div class="wcc-row wcc-align-center">
                        <label class="wcc-col-3 wcc-col-label" for="wcc-gacm-checkbox">
                            {{
                                $i18n.__(
                                    "Support Google’s Additional Consent",
                                    "webtoffee-cookie-consent"
                                )
                            }}
                        </label>
                        <div class="wcc-col-9">
                            <input type="checkbox" id="wcc-gacm-checkbox"
                                v-model="banner.properties.settings.gacm_enabled" :data-test-id="`wcc-gacm-checkbox`" />
                            <span id="wcc-gacm-checkbox" aria-hidden="true"> </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="wcc-row" v-if="iabEnabled && appliedLaw === 'gdpr'">
            <div class="wcc-col-12">
                <div class="wcc-app-box">
                    <div class="wcc-row wcc-align-center">
                        <label class="wcc-col-3 wcc-col-label" for="wcc-purpose-features">
                            {{
                                $i18n.__(
                                    "Manage Purposes and Features",
                                    "webtoffee-cookie-consent"
                                )
                            }}
                        </label>
                        <div class="wcc-col-9">
                            <button class="wcc-button wcc-button-outline wcc-reset-settings-btn"
                                @click="showModal('purpose_feature')" :data-test-id="`wcc-purpose-features-button`">
                                {{ $i18n.__("Select", "webtoffee-cookie-consent") }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="wcc-row" v-if="iabEnabled && appliedLaw === 'gdpr'">
            <div class="wcc-col-12">
                <div class="wcc-app-box">
                    <div class="wcc-row wcc-align-center">
                        <label class="wcc-col-3 wcc-col-label" for="wcc-vendors-button">
                            {{ $i18n.__("Manage vendor list", "webtoffee-cookie-consent") }}
                        </label>
                        <div class="wcc-col-9">
                            <button class="wcc-button wcc-button-outline wcc-reset-settings-btn"
                                @click="showModal('vendors')" :data-test-id="`wcc-vendors-button`">
                                {{
                                    $i18n.__("Select vendors", "webtoffee-cookie-consent")
                                }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </fragment>
</template>
    
<script>
import { Fragment } from "vue-frag";
import Modal from "@/components/Modal.vue";
import wccRest from "@/helpers/api";
import { saveOptions } from "@/helpers/common";
import banners from "@/modules/banners/helpers/utils";
import Loader from "@/components/elements/Loader.vue";

export default {
    name: "IABSettings",
    components: {
        Fragment,
        Modal,
        Loader,
    },
    props: {
        law: {
            type: String,
            default: "gdpr",
        },
    },
    data() {
        return {
            updating: false,
            loading: false,
            modalType: "",
            modalHeader: "",
            modalBody: "",
            modalConfirmButton: "",
            searchText: "",
            vendorData: null, // Store the fetched data
            currentVendorData: null,
            selectedLayoutType: "Purposes",
            selectedVendorType: "Third party vendors",
            selectedCategoryName: "Purposes",
            selectedLayoutTypeClass: "purpose",
            selectedVendorTypeClass: "thirdpartyvendors",
            selectedVendorName: "",
            selectedCategoryLength: "",
            selectedPurposeFeatureArray: {
                purpose: [],
                specialpurpose: [],
                feature: [],
                specialfeature: [],
            },
            selectedVendorArray: {
                thirdpartyvendors: [],
                googlevendors: [],
            },
            selectAllChecked: false, // Checkbox state for "Select All"
            selectedCategory: { items: [] }, // Your vendor items here
        };
    },
    methods: {
        async showModal(type) {
            try {
                this.modalType = type;
                if (type === "purpose_feature") {
                    this.modalHeader = this.$i18n.__(
                        "Manage purposes and features",
                        "webtoffee-cookie-consent"
                    );
                    this.modalBody = this.$i18n.__(
                        "The cookie banner will reappear for all previously consenting users, prompting them to provide their consent once more",
                        "webtoffee-cookie-consent"
                    );
                    this.modalConfirmButton = this.$i18n.__(
                        "Save settings",
                        "webtoffee-cookie-consent"
                    );
                    this.confirmAction = this.updatePurposeFeatures;
                } else if (type === "vendors") {
                    this.modalHeader = this.$i18n.__(
                        "Manage vendors",
                        "webtoffee-cookie-consent"
                    );
                    this.modalBody = this.$i18n.__(
                        "You will lose all the customizations you have done so far",
                        "webtoffee-cookie-consent"
                    );
                    this.modalConfirmButton = this.$i18n.__(
                        "Update vendors",
                        "webtoffee-cookie-consent"
                    );
                    this.confirmAction = this.updateVendors;
                }
                this.loading = true; // Set loading to true
                this.$refs.confirmationModal.show();
                // Fetch vendor file
                await this.fetchJson();
                // For vendors modal, always fetch fresh data from database
                if (type === "vendors") {
                    this.currentVendorData = null; // Clear cached data to force fresh fetch
                }
                // Fetch vendor data
                await this.fetchVendorData();
            } catch (error) {
                console.error("API Error:", error);
            }
            finally {
                this.loading = false; // Set loading to false
            }
        },
        async updatePurposeFeatures() {
            this.$refs.wccIABSavebutton.startLoading();
            try {
                this.updating = true;
                const response = await wccRest.post({
                    path: `/banners/purposefeatures`,
                    data: { content: this.selectedPurposeFeatureArray },
                });
                await saveOptions();
                await banners.bulkUpdate();
                this.$root.$emit("triggerNotification", {
                    type: "success",
                    message: this.$i18n.__(
                        "Purposes and features updated successfully!",
                        "webtoffee-cookie-consent"
                    ),
                });
                return response;
            } catch (error) {
                console.error(error);
                this.showErrors(
                    this.$i18n.__(
                        "Problem occurred while saving your settings. Please try again later!",
                        "webtoffee-cookie-consent"
                    )
                );
            }
            finally {
                this.updating = false;
                this.closeModal();
            }
            this.$refs.wccIABSavebutton.stopLoading();
        },
        async updateVendors() {
            // Check if vendor count is zero BEFORE starting the save process
            const thirdPartyCount = Array.isArray(this.selectedVendorArray.thirdpartyvendors) 
                ? this.selectedVendorArray.thirdpartyvendors.length 
                : 0;
            
            // Only count Google vendors if "Support Google's Additional Consent" is enabled
            const gacmEnabled = this.banner?.properties?.settings?.gacm_enabled;
            const googleVendorsCount = gacmEnabled && Array.isArray(this.selectedVendorArray.googlevendors) 
                ? this.selectedVendorArray.googlevendors.length 
                : 0;
            
            const totalVendorCount = thirdPartyCount + googleVendorsCount;
            
            if (totalVendorCount === 0) {
                this.$root.$emit("triggerNotification", {
                    type: "warning",
                    message: this.$i18n.__(
                        "Vendor list is empty. Unable to generate disclosed vendors segment. Please validate TCF settings",
                        "webtoffee-cookie-consent"
                    ),
                });
                this.closeModal(); // Close modal even when validation fails
                return; // Exit early - do not save
            }
            
            this.$refs.wccIABSavebutton.startLoading();
            try {
                this.updating = true;
                const response = await wccRest.post({
                    path: `/banners/updatevendordata`,
                    data: { content: this.selectedVendorArray },
                });
                await saveOptions();
                await banners.bulkUpdate();
                this.$root.$emit("triggerNotification", {
                    type: "success",
                    message: this.$i18n.__(
                        "Vendor list updated successfully!",
                        "webtoffee-cookie-consent"
                    ),
                });
                return response;
            } catch (error) {
                console.error(error);
                this.showErrors(
                    this.$i18n.__(
                        "Problem occurred while saving your settings. Please try again later!",
                        "webtoffee-cookie-consent"
                    )
                );
            }
            finally {
                this.updating = false;
                this.closeModal();
            }
            this.$refs.wccIABSavebutton.stopLoading();
        },
        async fetchJson() {
            if (this.vendorData) {
                // Vendor data is already loaded, no need to fetch again
                return;
            }
            this.loading = true;
            try {
                // Fetch the vendor file from the API
                const response = await wccRest.post({
                    path: `/banners/fetchJson`,
                    data: { content: this.language },
                });

                this.vendorData = response; // Store the fetched data
                this.vendorData.vendors = this.mapVendors(response); // Map ans store the vendors data
                
                if (!this.vendorData.vendors || Object.keys(this.vendorData.vendors).length === 0) {
                    const vendorlistArray = await wccRest.post({
                        path: `/banners/fetchJson`,
                        data: { content: 'en' },
                    });
                    // Set vendors and googleVendors from the fetched data
                    if (vendorlistArray) {
                        this.vendorData.vendors = vendorlistArray.vendors || {};
                        this.vendorData.googleVendors = vendorlistArray.googleVendors || {};
                        
                        // Re-map vendors after updating the data
                        this.vendorData.vendors = this.mapVendors(this.vendorData);
                    }
                }
            } catch (error) {
                // Handle errors
                console.error('API Error:', error);
            } finally {
                this.loading = false;
            }
        },
        async fetchVendorData() {
            if (this.currentVendorData) {
                // Vendor data is already loaded, no need to fetch again
                return;
            }
            this.loading = true;
            try {
                // Fetch the vendor dta from the API
                const response = await wccRest.get({
                    path: "banners/fetchvendordata",
                });
                this.currentVendorData = response; // Store the fetched data
            } catch (error) {
                // Handle errors
                console.error('API Error:', error);
            } finally {
                this.loading = false;
                await this.initializeVendorData();
            }
        },
        async initializeVendorData() {
            // Ensure that vendors is an object
            if (Object.keys(this.currentVendorData.vendors).length === 0) {
                this.currentVendorData.vendors = {
                    googleVendors: Array.isArray(this.vendorData.googleVendors) ? this.vendorData.googleVendors : Object.values(this.vendorData.googleVendors || {}),
                    thirdpartyvendors: Array.isArray(this.vendorData.vendors) ? this.vendorData.vendors : Object.values(this.vendorData.vendors || {})
                };
            }

            // Ensure that purpose_feature is also an object
            if (Object.keys(this.currentVendorData.purpose_feature).length === 0) {
                this.currentVendorData.purpose_feature = {
                    purposes: Array.isArray(this.vendorData.purposes) ? this.vendorData.purposes : Object.values(this.vendorData.purposes || {}),
                    specialPurposes: Array.isArray(this.vendorData.specialPurposes) ? this.vendorData.specialPurposes : Object.values(this.vendorData.specialPurposes || {}),
                    features: Array.isArray(this.vendorData.features) ? this.vendorData.features : Object.values(this.vendorData.features || {}),
                    specialFeatures: Array.isArray(this.vendorData.specialFeatures) ? this.vendorData.specialFeatures : Object.values(this.vendorData.specialFeatures || {})
                };
            }
        },

        selectLayoutType(type) {
            this.selectedLayoutType = type;
            // Convert categoryType to lowercase and remove spaces for consistency
            const normalizedCategoryType = type.toLowerCase().replace(" ", "").replace(/s$/, "");
            this.selectedLayoutTypeClass = normalizedCategoryType;
            // Update the selectedCategoryName based on the selectedLayoutType
            const selectedCategory = this.purposeFeatures.find(
                (category) => category.type === type
            );
            this.selectedCategoryName = selectedCategory ? selectedCategory.type : "";
        },
        selectVendorType(type) {
            this.selectedVendorType = type;
            // Convert categoryType to lowercase and remove spaces for consistency
            const normalizedCategoryType = type.toLowerCase().replace(/\s+/g, "");
            this.selectedVendorTypeClass = normalizedCategoryType;
            // Update the selectedVendorName based on the selectedVendorType
            const selectedVendorCategory = this.vendorList.find(
                (category) => category.type === type
            );
            this.selectedVendorName = selectedVendorCategory ? selectedVendorCategory.type : "";
            if (this.selectedCount !== this.totalCount) {
                this.selectAllChecked = false;
            } else {
                this.selectAllChecked = true;
            }
        },
        closeModal() {
            this.$refs.confirmationModal.close();
            this.selectedVendorType= "Third party vendors";
            this.selectedVendorTypeClass= "thirdpartyvendors";
        },
        getLayoutTitle() {
            // Use the stored category name
            if (this.selectedCategoryName) {
                return `Select '${this.selectedCategoryName}' to be displayed on the second layer of the cookie banner for user consent.`;
            } else {
                return 'Select items to be displayed on the second layer of the cookie banner for user consent.';
            }
        },
        getVendorLayoutTitle(type) {
            // Convert categoryType to lowercase and remove spaces for consistency
            const normalizedCategoryType = type.toLowerCase().replace(/\s+/g, "");
            // Use the stored category name
            if ('thirdpartyvendors' === normalizedCategoryType) {
                return 'Third-party vendors';
            } else if( 'googlevendors' === normalizedCategoryType ){
                return 'Google Ad Tech providers';
            }
        },
        getVendorLayoutDescription() {
            // Use the stored category name
            if ('thirdpartyvendors' === this.selectedVendorTypeClass) {
                return `Select TCF-listed vendors to display in the cookie banner. All vendors selected will get the consent to purpose, features and special features if applicable.`;
            } else if( 'googlevendors' === this.selectedVendorTypeClass ){
                return 'Select Google Ads certified vendors to display in the cookie banner for user consent.';
            }
        },
        isItemChecked(itemId, categoryType, isVendor = false) {
            // Convert categoryType to lowercase and remove spaces for consistency
            const normalizedCategoryType = isVendor 
                ? categoryType.toLowerCase().replace(" ", "") 
                : categoryType.toLowerCase().replace(" ", "").replace(/s$/, "");
            
            // Determine which array to update
            let categoryArray = isVendor 
                ? this.selectedVendorArray[normalizedCategoryType] 
                : this.selectedPurposeFeatureArray[normalizedCategoryType];
            // If categoryArray is not an array, check if it's an object
            if (!Array.isArray(categoryArray)) {
                if (typeof categoryArray === 'object' && categoryArray !== null) {
                    // Handle the object case (e.g., extract keys, convert to array, etc.)
                    categoryArray = Object.keys(categoryArray);
                } else {
                    // Convert to an empty array if it's not an object
                    categoryArray = [];
                }
            }
            // Handle the selectAllChecked logic for vendors
            if (isVendor) {
                this.selectAllChecked = this.selectedCount === this.totalCount;
            }
            return categoryArray.some(item => item.id === itemId);
        },
        handleItemCheckboxChange(itemId, categoryType, isVendor = false) {
            const normalizedCategoryType = isVendor
                ? categoryType.toLowerCase().replace(/\s+/g, "")
                : categoryType.toLowerCase().replace(/\s+/g, "").replace(/s$/, "");

            // Determine which array to update
            const targetArray = isVendor
                ? this.selectedVendorArray
                : this.selectedPurposeFeatureArray;

            // Ensure the categoryArray is initialized and is an array
            let categoryArray = targetArray[normalizedCategoryType];

            if (!Array.isArray(categoryArray)) {
                categoryArray = [];
                this.$set(targetArray, normalizedCategoryType, categoryArray);
            }

            // Find the index of the object with the matching itemId
            const itemIndex = categoryArray.findIndex(item => item.id === itemId);
            
            if (itemIndex === -1) {
                // If the object with the given itemId is not found, add it
                const newItem = isVendor ? { id: itemId } : { id: itemId }; // Adjust based on your data structure
                categoryArray.push(newItem);
            } else {
                // If the object is found, remove it
                categoryArray.splice(itemIndex, 1);
            }

            // Handle the selectAllChecked logic for vendors
            if (isVendor) {
                // Get all item IDs for the current vendor type
                const allItemIds = Object.keys(this.selectedVendorItems[this.selectedVendorType] || {}).map(key => Number(key));
                this.selectAllChecked = allItemIds.length === categoryArray.length;
            }
        },
        handleSelectAll(categoryType) {
            const normalizedCategoryType = categoryType.toLowerCase().replace(/\s+/g, "");

            // Ensure the vendor array is initialized as an array
            if (!Array.isArray(this.selectedVendorArray[normalizedCategoryType])) {
                this.$set(this.selectedVendorArray, normalizedCategoryType, []);
            }
            const vendorArray = this.selectedVendorArray[normalizedCategoryType];
            
            // Get the list of all item IDs from selectedVendorItems
            const itemIds = Object.keys(this.selectedVendorItems).map(key => Number(key));

            // Determine whether to add or remove items based on selectAllChecked
            if (this.selectAllChecked) {
                // Add all item IDs if they are not already present in vendorArray
                itemIds.forEach(itemId => {
                    if (!vendorArray.some(item => item.id === itemId)) {
                        vendorArray.push({ id: itemId }); // Ensure adding a new object
                    }
                });
            } else {
                // Remove all item IDs from vendorArray
                itemIds.forEach(itemId => {
                    const index = vendorArray.findIndex(item => item.id === itemId);
                    if (index !== -1) {
                        vendorArray.splice(index, 1);
                    }
                });
            }

            // Optionally, reset the select all checkbox state
            this.selectAllChecked = false;
        },

        unselectAll(categoryType) {
            const normalizedCategoryType = categoryType.toLowerCase().replace(/\s+/g, "");

            // Ensure the vendor array is initialized as an array
            if (!Array.isArray(this.selectedVendorArray[normalizedCategoryType])) {
                this.$set(this.selectedVendorArray, normalizedCategoryType, []);
            }

            const vendorArray = this.selectedVendorArray[normalizedCategoryType];

            // Uncheck items and log for debugging
            vendorArray.forEach(item => {
                const itemId = item.id; // Assuming each item has an 'id' property
                if (this.selectedVendorItems[itemId]) {
                    // Uncheck the item
                    this.$set(this.selectedVendorItems[itemId], 'checked', false);
                } else {
                    console.warn(`ItemId ${itemId} not found in selectedVendorItems`); // Debug log
                }
            });

            // Clear the vendorArray by replacing it with an empty array
            this.$set(this.selectedVendorArray, normalizedCategoryType, []);

            // Optionally, reset the select all checkbox state
            this.selectAllChecked = false;

            // Trigger any necessary updates
            this.$nextTick(() => {
                this.$forceUpdate(); // Force the Vue component to re-render if needed
            });
        },
        mapVendors(vendorData) {
            const vendorList = vendorData.vendors || {};  // vendorList is likely an object
            let purposes = this.vendorData.purposes;
            let specialPurposes = this.vendorData.specialPurposes;
            let features = this.vendorData.features;
            let specialFeatures = this.vendorData.specialFeatures;
            let vendorIds = [];

            // Loop through each vendor and push the vendor.id into vendorIds array
            for (const vendor of Object.values(vendorList)) {
                vendorIds.push(vendor.id);
            }

            // Create new instances of the maps
            this.byPurposeVendorMap = {};
            this.bySpecialPurposeVendorMap = {};
            this.byFeatureVendorMap = {};
            this.bySpecialFeatureVendorMap = {};

            // Initializes data structure for purpose map
            Object.keys(purposes).forEach((purposeId) => {
                this.byPurposeVendorMap[purposeId] = {
                    legInt: new Set(),
                    consent: new Set(),
                    flexible: new Set(),
                };
            });

            // Initializes data structure for special purpose map
            Object.keys(specialPurposes).forEach((purposeId) => {
                this.bySpecialPurposeVendorMap[purposeId] = new Set();
            });

            // Initializes data structure for feature map
            Object.keys(features).forEach((featureId) => {
                this.byFeatureVendorMap[featureId] = new Set();
            });

            // Initializes data structure for special feature map
            Object.keys(specialFeatures).forEach((featureId) => {
                this.bySpecialFeatureVendorMap[featureId] = new Set();
            });

            // Ensure `vendorIds` is an array
            if (!Array.isArray(vendorIds)) {
                vendorIds = Object.keys(this.fullVendorList).map((vId) => +vId);
            }

            // Convert Set back to an array for reduce operation
            vendorIds = Array.from(new Set(vendorIds));

            // Assign vendor ids to their respective maps
            let vendors_ = vendorIds.reduce((vendors, vendorId) => {
                // Convert vendorList object to an array using Object.values() and find the vendor by ID
                const vendor = Object.values(vendorList).find(v => v.id === vendorId);
                if (vendor && vendor.deletedDate === undefined) {
                    vendor.purposes.forEach((purposeId) => {
                        const purpGroup = this.byPurposeVendorMap[String(purposeId)];
                        purpGroup.consent.add(vendorId);
                    });
                    vendor.specialPurposes.forEach((purposeId) => {
                        this.bySpecialPurposeVendorMap[String(purposeId)].add(vendorId);
                    });
                    vendor.legIntPurposes.forEach((purposeId) => {
                        this.byPurposeVendorMap[String(purposeId)].legInt.add(vendorId);
                    });
                    // Flexible purposes could not be there
                    if (vendor.flexiblePurposes) {
                        vendor.flexiblePurposes.forEach((purposeId) => {
                            this.byPurposeVendorMap[String(purposeId)].flexible.add(vendorId);
                        });
                    }
                    vendor.features.forEach((featureId) => {
                        this.byFeatureVendorMap[String(featureId)].add(vendorId);
                    });
                    vendor.specialFeatures.forEach((featureId) => {
                        this.bySpecialFeatureVendorMap[String(featureId)].add(vendorId);
                    });
                    vendors[vendorId] = vendor; // Collect the vendor data
                }
                return vendors;
            }, {});

            return vendors_;
        },
    },
    computed: {
        banner() {
            return this.$store.state.banners.current;
        },
        appliedLaw() {
            return this.banner.properties.settings.applicableLaw;
        },
        purposeFeatures() {
            // Ensure vendorData is available
            if (!this.vendorData) {
                return [];
            }

            // Extracting the purposes, special purposes, and special features from vendorData
            const purposes = this.vendorData.purposes || [];
            const specialPurposes = this.vendorData.specialPurposes || [];
            const features = this.vendorData.features || [];
            const specialFeatures = this.vendorData.specialFeatures || [];

            // Combine them into a single array with keys
            return [
                { type: 'Purposes', items: purposes },
                { type: 'Special purpose', items: specialPurposes },
                { type: 'Features', items: features },
                { type: 'Special features', items: specialFeatures },
            ];
        },
        vendorList() {
            // Ensure vendorData is available
            if (!this.vendorData) {
                return [];
            }

            // Extracting the purposes, special purposes, and special features from vendorData
            const vendors = this.vendorData.vendors || [];
            const googleVendors = this.vendorData.googleVendors || [];

            // Check if GACM is enabled
            if (this.banner.properties.settings.gacm_enabled) {
                // Return both third party vendors and Google vendors
                return [
                    { type: 'Third party vendors', items: vendors },
                    { type: 'Google vendors', items: googleVendors },
                ];
            } else {
                // Return only third party vendors
                return [
                    { type: 'Third party vendors', items: vendors },
                ];
            }
        },
        selectedLayoutItems() {
            // Find the selected category by matching the selectedLayoutType
            const selectedCategory = this.purposeFeatures.find(
                (category) => category.type === this.selectedLayoutType
            );
            return selectedCategory ? selectedCategory.items : [];
        },
        selectedVendorItems() {
            // Find the selected category by matching the selectedVendorType
            const selectedVendorCategory = this.vendorList.find(
                (category) => category.type === this.selectedVendorType
            );
            return selectedVendorCategory ? selectedVendorCategory.items : [];
        },
        filteredVendorItems() {
            if (!this.searchText) {
                return this.selectedVendorItems; // Return entire list if search text is empty
            }
            const searchLower = this.searchText.toLowerCase();
            // Filter items based on the search text
            return Object.values(this.selectedVendorItems).filter(item => {
                return item.name.toLowerCase().includes(searchLower);
            });
        },
        selectedCount() {
            const normalizedCategoryType = this.selectedVendorType.toLowerCase().replace(/\s+/g, "");
            const categoryData = this.selectedVendorArray[normalizedCategoryType];

            // Return the length if it's an array, or the number of object keys if it's an object, otherwise return 0
            return Array.isArray(categoryData) ? categoryData.length :
                typeof categoryData === 'object' && categoryData !== null ? Object.keys(categoryData).length :
                0;
        },
        totalCount() {
            // Convert object to array and get the length
            const itemsArray = Object.values(this.selectedVendorItems);
            return itemsArray.length;
        },
        iabEnabled: {
            get() {
                return this.banner.properties.settings.iab_enabled === "1";
            },
            set(newValue) {
                this.banner.properties.settings.iab_enabled = newValue ? "1" : "0";
                banners.bulkUpdate();
			
            }
        },
        language() {
            return this.$store.state.languages?.default || 'en';
        },
    },
    watch: {
        currentVendorData: {
            immediate: true,
            handler(newData) {
                // Initialize or update the checked items based on currentVendorData
                if (newData) {
                    // Clear existing selections
                    this.selectedPurposeFeatureArray = {
                        purpose: [],
                        specialpurpose: [],
                        feature: [],
                        specialfeature: [],
                    };
                    // Clear existing selections
                    this.selectedVendorArray = {
                        thirdpartyvendors: [],
                        googlevendors: [],
                    };

                    // Populate the selections from currentVendorData
                    for (const [category, items] of Object.entries(newData.purpose_feature || {})) {
                        const normalizedCategory = category.toLowerCase().replace(" ", "").replace(/s$/, "");
                        this.selectedPurposeFeatureArray[normalizedCategory] = items;
                    }

                    // Populate vendor selections similarly
                    for (const [category, items] of Object.entries(newData.vendors || {})) {
                        const normalizedCategory = category.toLowerCase().replace(" ", "");
                        this.selectedVendorArray[normalizedCategory] = items;
                    }
                }
            },
        },
    },
};
</script>

<style lang="scss">
@include wrap-class() {
    .wcc-general-tab-iab-modal .wcc-app-modal {
        max-width: 794px;
        height: 476px;
    }

    .wcc-general-tab-iab-modal .wcc-app-modal .wcc-app-modal-body {
        height: 366px;
        padding: 0px 30px;
    }
    .wcc-app-modal-body-loader-class {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
    }
    .wcc-general-tab-iab-modal .wcc-app-modal .wcc-app-modal-footer .wcc-button-no-style {
        color: #056be7;
        margin-right: 20px;
    }
    .wcc-banner-iab-settings .wcc-button.wcc-button-outline:hover {
        background-color:#F2F8FF ;
        color: #3157A6;
    }
    .wcc-banner-layout-wrap {
        display: block;

        /* Changed from flex to block */
        .wcc-button-group {
            display: flex;
            margin-bottom: 15px;

            .wcc-layout-type-button {
                width: auto;
                height: 32px;
                gap: 0px;
                color: #555e6b;
                font-size: 14px;
                line-height: 16px;
                text-align: left;
                border-radius: 19px;
                background: none;
                cursor: pointer;
                padding: 8px 18px 8px 18px;
                border: 1px solid #eaebed;
                box-shadow: 0px 4px 12px 0px #55657d14;
                margin-right: 10px;

                &.selected {
                    background: #f1f8fe;
                    color: #056be7;
                    border: 1px solid #cce3ff;
                }
                &:hover{
                    background: #f1f8fe;
                }
            }
        }
    }

    .wcc-layout-items-container:has(.wcc-purpose) {
        display: flex;
        flex-wrap: wrap;

        .wcc-layout-item {
            width: 50%;
        }
    }

    .wcc-layout-items-container {
        .wcc-layout-item-title {
            width: 100%;
            margin-bottom: 12px;
            font-size: 14px;
        }

        .wcc-layout-item {
            display: flex;
            align-items: center;
            /* Align items vertically in the center */
            gap: 8px;
            /* Optional: Adjust space between checkbox and label */
            font-weight: 500;
        }

        .wcc-layout-item input[type="checkbox"] {
            margin: 10px 0px;
            /* Remove default margin */
        }

        .wcc-layout-item label {
            margin: 10px 0px;
            /* Remove default margin */
        }
    }

    .wcc-vendor-list-section {
        height: 260px;
        overflow-y: scroll;
        margin-top: 10px;
    }

    .wcc-vendor-search-input {
        margin-bottom: 0;
        width: 75%;

        input[type="text"] {
            background-image: url("~@/assets/search.svg");
            background-position: 10px 12px;
            background-repeat: no-repeat;
            padding: 5px 0 5px 33px;
            z-index: 1;
            background-size: 18px;
            display: flex;
            align-items: center;
            gap: 6px;
            flex-shrink: 0;
            border-radius: 33px;
            border: 1.5px solid var(--light-color-border-focused, #388BFF);
            background-position: 15px 12px;
            /* Adjust the horizontal and vertical values for margin */
        }
    }

    .wcc-search-wrap {
        display: flex;
        align-items: center;
    }

    .wcc-selected-list {
        width: 25%;
        padding-left: 20px;
    }

    .wcc-hidden-checkbox {
        display: none;
        /* Hide the default checkbox */
    }

    .wcc-custom-checkbox-label {
        display: flex;
        align-items: center;
        cursor: pointer;
        font-size: 14px;
        /* Adjust size as needed */
        position: relative;
        margin-bottom: 0px;
    }

    .wcc-custom-checkbox-label .wcc-checkbox-icon {
        display: inline-block;
        width: 1rem;
        /* Adjust size as needed */
        height: 1rem;
        /* Adjust size as needed */
        text-align: center;
        line-height: 11px;
        /* Center the wcc-checkbox-icon vertically */
        border: 1px solid rgba(0, 0, 0, 0.25);
        border-radius: 4px;
        /* Rounded corners */
        background-color: #056BE7;
        /* Change background color when checked */
        border-color: #056BE7;
        /* Change border color when checked */
        color: white;
        /* Change wcc-checkbox-icon color when checked */
        font-size: 24px;
        /* Adjust size as needed */
        margin-right: 5px;
    }

    /* Style for the checkbox when checked */
    .wcc-hidden-checkbox:checked+.wcc-custom-checkbox-label .wcc-checkbox-icon {
        background-color: #056BE7;
        /* Change background color when checked */
        border-color: #056BE7;
        /* Change border color when checked */
        color: white;
        /* Change wcc-checkbox-icon color when checked */
    }

    /* Optional: Add a hover effect */
    .wcc-custom-checkbox-label:hover .wcc-checkbox-icon {
        background-color: #056BE7;
        /* Change background on hover */
    }
    .wcc-checkbox-iab-title {
        color: #3157A6;
        font-size: 16px;
    }
}
</style>
    