<template>
    <fragment>
        <div class="wcc-gcm-container">
            <div class="wcc-loader-view" style="min-height: 400px" v-if="saving">
                <p class="wcc-loading-text">
                    <loader />
                    {{ $i18n.__("Saving...", "webtoffee-cookie-consent") }}
                </p>
            </div>
            <div v-else>
                <div class="wcc-gcm-header">
                    <div class="wcc-row">
                        <div class="wcc-col-8">
                            <div class="wcc-row wcc-align-center">
                                <label class="wcc-col-label wcc-checkbox-gcm-title" for="wcc-checkbox-gcm-title"
                                    style="font-weight: bold">
                                    {{
                                        $i18n.__(
                                            "Google Consent Mode (GCM)",
                                            "webtoffee-cookie-consent"
                                        )
                                    }}
                                </label>
                                <base-switch v-model="googleConsentModeStatus" name="gcm-toggle" />
                            </div>
                        </div>
                        <div class="wcc-col-4 wcc-gcm-support-link-wrap">
                            <div class="wcc-gcm-support-link">
                                <div class="wcc-support-logo"></div>
                                <div class="wcc-support-text">
                                    {{
                                        $i18n.__(
                                            "For troubleshooting/assistance, ",
                                            "webtoffee-cookie-consent"
                                        )
                                    }}
                                    <a href="https://www.webtoffee.com/gcm-support-center/" target="_blank">
                                        {{ $i18n.__("reach out", "webtoffee-cookie-consent") }}
                                    </a>
                                    {{
                                        $i18n.__(
                                            " to our dedicated support team at GCM Support Center",
                                            "webtoffee-cookie-consent"
                                        )
                                    }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="wcc-gcm-body">
                    <div :class="{'wcc_gcm_overlay': !googleConsentModeStatus}" class="wcc-gtm-settings">
                        <div class="wcc-row">
                            <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-checkbox-gtm-template">
                                            {{
                                                $i18n.__(
                                                    "Manage Consent mode via GTM template",
                                                    "webtoffee-cookie-consent"
                                                )
                                            }}
                                        </label>
                                        <div class="wcc-col-9">
                                            <base-popper :content="$i18n.__('When enabled, Consent Mode will be managed using the WebToffee CMP GTM template instead of the plugin\'s built-in logic. Recommended if you\'re integrating Consent Mode through GTM using the WebToffee CMP template.',
                                                        'webtoffee-cookie-consent') " />
                                            <input type="checkbox" id="wcc-checkbox-gtm-template"
                                                v-model="gtmTemplateStatus" :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-gtm-template-checkbox`" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="wcc-row">
                            <div class="wcc-section-separator wcc-col-12"></div>
                        </div>
                        <div class="wcc-row">
                            <div class="wcc-col-12">
                                <div class="wcc-app-box">
                                    <label class="wcc-gtm-help-label">
                                    {{
                                        $i18n.__(
                                            "Learn how to configure the, ",
                                            "webtoffee-cookie-consent"
                                        )
                                    }}
                                    <a href="https://www.webtoffee.com/setup-gcm-using-webtoffee-gtm-template" target="_blank">
                                        {{ $i18n.__("GTM Template", "webtoffee-cookie-consent") }}
                                    </a>   
                                </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-if="gtmTemplateStatus" class="wcc-gtm-settings" :class="{'wcc_gcm_overlay': !googleConsentModeStatus}">
                        <GTMTemplate />
                    </div>
                    <div :class="{'wcc_gcm_overlay': !googleConsentModeStatus}" class="wcc-gcm-general-settings" v-if="!gtmTemplateStatus">
                        <div class="wcc-row">
                            <div class="wcc-gcm-general-settings-title">
                                {{ $i18n.__("1. General", "webtoffee-cookie-consent") }}
                            </div>
                        </div>
                        <div class="wcc-row">
                            <div class="wcc-col-12">
                                <div class="wcc-app-box">
                                    <div class="wcc-row">
                                        <label class="wcc-col-3 wcc-col-label" for="wcc-radio-gtag-behavior">
                                            {{
                                                $i18n.__(
                                                    "Google tags behavior",
                                                    "webtoffee-cookie-consent"
                                                )
                                            }}
                                        </label>
                                        <div class="wcc-col-9" style="display: flex; flex-direction: column; align-items: flex-start;">
                                            <div class="wcc-gtag-behavior-inner">
                                                <base-popper :content="$i18n.__(
                                                            'Google Consent Mode allows websites to adjust the behavior of Google tags (e.g., Google Analytics, Ads) based on user\'s consent status',
                                                            'webtoffee-cookie-consent'
                                                        )
                                                        " />
                                                <!-- Advanced Radio -->
                                                <div class="wcc-form-check wcc-align-center" style=" align-items: flex-start; ">
                                                    <input class="wcc-form-check-input wcc-gtag-advanced" type="radio"
                                                        id="wcc-radio-gtag-advanced" value="advanced"
                                                        v-model="gtagBehaviorStatus"
                                                        :checked="gtagBehaviorStatus === 'advanced'"
                                                        :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-gtag-advanced-radio`" />
                                                    <div style="display: inline-flex; flex-direction: column; align-items: flex-start;">
                                                        <div style="display: flex; align-items: baseline;">
                                                            <label class="wcc-form-check-label" for="wcc-radio-gtag-advanced" style="margin: 0px 6px 10px 0px;">
                                                                {{
                                                                    $i18n.__("Advanced", "webtoffee-cookie-consent")
                                                                }}
                                                            </label>
                                                            <badge
                                                                :title="$i18n.__('Recommended', 'webtoffee-cookie-consent')"
                                                                :type="'success'"
                                                                >
                                                            </badge>
                                                        </div>
                                                        
                                                        <p class="wcc-radio-gtag-description">
                                                            {{
                                                                $i18n.__(
                                                                    "Google tags are fired before consent",
                                                                    "webtoffee-cookie-consent"
                                                                )
                                                            }}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- Basic Radio -->
                                            <div class="wcc-form-check wcc-align-center"
                                                style="margin-bottom: 10px; margin-left: 27px;align-items: flex-start;">
                                                <input class="wcc-form-check-input" type="radio" id="wcc-radio-gtag-basic"
                                                    value="basic" v-model="gtagBehaviorStatus"
                                                    :checked="gtagBehaviorStatus === 'basic'"
                                                    :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-gtag-basic-radio`" />
                                                <div style="display: flex; flex-direction: column; align-items: flex-start;">
                                                    <label class="wcc-form-check-label" for="wcc-radio-gtag-basic">
                                                        {{ $i18n.__("Basic", "webtoffee-cookie-consent") }}
                                                    </label>
                                                    <p class="wcc-radio-gtag-description">
                                                        {{
                                                            $i18n.__(
                                                                "Google tags are blocked until user consents",
                                                                "webtoffee-cookie-consent"
                                                            )
                                                        }}
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="wcc-row" v-if="'advanced' === gtagBehaviorStatus">
                            <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-checkbox-url-passthrough">
                                            {{
                                                $i18n.__(
                                                    "Allow URL data to passthrough",
                                                    "webtoffee-cookie-consent"
                                                )
                                            }}
                                        </label>
                                        <div class="wcc-col-9">
                                            <base-popper :content="$i18n.__('URL passthrough can be used to send event and session-based analytics (including key events) without cookies across pages. When using URL passthrough, a few query parameters may be appended to links as users navigate through pages on your website: gclid, dclid, gclsrc, _gl, wbraid',
                                                        'webtoffee-cookie-consent'
                                                    )
                                                    " />
                                            <input type="checkbox" id="wcc-checkbox-url-passthrough"
                                                v-model="urlPassthroughStatus"
                                                :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-url-passthrough-checkbox`" />
                                            <label class="wcc-form-check-label" for="wcc-checkbox-url-passthrough">
                                                {{
                                                    $i18n.__("Enable to pass data between pages for tracking", "webtoffee-cookie-consent")
                                                }}
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="wcc-row">
                            <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-checkbox-gcm-debug-mode">
                                            {{
                                                $i18n.__("Enable debug mode", "webtoffee-cookie-consent")
                                            }}
                                        </label>
                                        <div class="wcc-col-9">
                                            <input type="checkbox" id="wcc-checkbox-gcm-debug-mode" v-model="debugModeStatus" style="margin-left: 27px;"
                                                :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-debug-mode-checkbox`" />
                                            <label class="wcc-form-check-label" for="wcc-checkbox-gcm-debug">
                                                {{
                                                    $i18n.__("Enable to log user consent states in the browser console for troubleshooting", "webtoffee-cookie-consent")
                                                }}
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="wcc-row" v-if="'advanced' === gtagBehaviorStatus">
                            <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-checkbox-redact-ads-data">
                                            {{
                                                $i18n.__("Redact ads data", "webtoffee-cookie-consent")
                                            }}
                                        </label>
                                        <div class="wcc-col-9">
                                            <base-popper :content="$i18n.__(
                                                        'Enable  to redact previously collected ads data when the user\'s consent for advertisements is withdrawn',
                                                        'webtoffee-cookie-consent'
                                                    )
                                                    " />
                                            <input type="checkbox" id="wcc-checkbox-redact-ads-data"
                                                v-model="redactDataStatus"
                                                :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-redact-data-checkbox`" />
                                            <label class="wcc-form-check-label" for="wcc-checkbox-redact-data">
                                                {{
                                                    $i18n.__("Enable to remove ad data if consent is withdrawn", "webtoffee-cookie-consent")
                                                }}
                                            </label>
                                        </div>
                                        <div class="wcc-col-3">
                                        </div>
                                        <div class="wcc-col-4" style="padding-left: 42px; padding-top: 4px; color: #555E6B;">
                                            <label class="wcc-form-check-label wcc-ads-redact-help" for="wcc-checkbox-ads-redact">
                                                {{
                                                    $i18n.__("When enabled, disabling the Advertisement category denies ad_storage and sets ads_data_redaction to true", "webtoffee-cookie-consent")
                                                }}
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div :class="{'wcc_gcm_overlay': !googleConsentModeStatus}" class="wcc-gcm-default-consent-state" v-if="!gtmTemplateStatus">
                        <div class="wcc-row">
                            <div class="wcc-gcm-default-consent-title">
                                {{
                                    $i18n.__(
                                        "2. Default consent states",
                                        "webtoffee-cookie-consent"
                                    )
                                }}
                            </div>
                        </div>
                        <div class="wcc-row">
                            <div class="wcc-gcm-default-consent-description">
                                {{
                                    $i18n.__(
                                        "Modify default consent settings by region here. By default, security_storage (necessary) is always allowed, and all other categories are denied for all regions.","webtoffee-cookie-consent")
                                }}
                            </div>
                        </div>
                        <div class="wcc-row">
                            <div class="wcc-col-12">
                                <div class="wcc-app-box">
                                    <div class="">
                                       <GCMTable @updateConsentValues="handleConsentValuesUpdate" :emptyRegions="emptyRegions" ref="consentTable" :key="tableKey" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="wcc-gcm-footer">
                    <base-button class="wcc-button wcc-button-blue" @click.native="saveGcmSettings" ref="wccButtonSaveGcm" :disabled="!googleConsentModeStatus" v-if="!gtmTemplateStatus" :data-test-id="`wcc-gcm-save-settings-button`">{{
                        $i18n.__("Update settings", "webtoffee-cookie-consent")
                    }}</base-button>
                </div>
            </div>
        </div>
    </fragment>
</template>
    
<script>
import { Fragment } from "vue-frag";
import { saveOptions } from "@/helpers/common";
import Badge from "@/components/elements/Badge.vue";
import api from "@/modules/gcm/helpers/api";
import GCMTable from "@/modules/gcm/components/gcm-consent-table.vue";
import GTMTemplate from "@/modules/gcm/components/gtm-template.vue";
import Loader from "@/components/elements/Loader.vue";

export default {
    name: "Gcm",
    components: {
        Fragment,
        Badge,
        GCMTable,
        GTMTemplate,
        Loader
    },
    props: {
        law: {
            type: String,
            default: "gdpr",
        },
    },
    data() {
        return {
            emptyRegions: [],
            tableKey: 0, // This is the key used to force reload
            saving: false,
        };
    },

    methods: {
        saveGcmSettings: async function () {
            this.$refs.wccButtonSaveGcm.startLoading();
            try {
                // Check if any region is empty and include the index
                const emptyRegions = this.consentValues
                .map((consent, index) => ({ ...consent, index }))
                .filter(consent => consent.region.length === 0);
                
                if (emptyRegions.length > 0) {
                    // Emit an event back to the GCM table to handle the empty region case
                    this.emptyRegions = emptyRegions;
                    this.$emit("regionEmptyError", emptyRegions);
                    this.$root.$emit("triggerNotification", {
                        type: "error",
                        message: this.$i18n.__("Some regions are missing. Please complete all fields.", "webtoffee-cookie-consent"),
                    });
                    return; // Prevent saving if any region is empty
                }
                
                // Retrieve the consent settings from the table
                await api.saveConsents(this.consentValues);
                await saveOptions();
                // Force a reload of the GCMTable component
                this.tableKey += 1;
                this.$root.$emit("triggerNotification", {
                    type: "success",
                    message: this.$i18n.__("Settings updated successfully!", "webtoffee-cookie-consent"),
                });
            } catch (error) {
                console.error(error);
                this.$root.$emit("triggerNotification", {
                    type: "error",
                    message: this.$i18n.__("Problem occurred while saving your settings. Please try again later!", "webtoffee-cookie-consent"),
                });
            } finally {
                this.$refs.wccButtonSaveGcm.stopLoading();
            }
        },
        handleConsentValuesUpdate(newValues) {
            this.consentValues = newValues; // Update consent values with new data
        },
        handleClickOutside(event) {
            // Check if the table component is referenced and has the closeDropdown method
            if (this.$refs.consentTable && typeof this.$refs.consentTable.closeDropdown === 'function') {
                this.$refs.consentTable.closeDropdown(event); // Call the method from child
            }
        }
    },
    computed: {
        googleConsentModeStatus: {
            get() {
                return this.$store.state.settings.options.google_consent_mode.status;
            },
            set(value) {
                this.$store.state.settings.options.google_consent_mode.status = value;
                let data = {};
				data.status = value;
				this.setOption("google_consent_mode", data);
				this.saveOptions();
            },
        },
        gtagBehaviorStatus: {
            get() {
                return this.$store.state.settings.options.gtag_behavior.selected;
            },
            set(value) {
                this.$store.state.settings.options.gtag_behavior.selected = value;
            },
        },
        urlPassthroughStatus: {
            get() {
                return this.$store.state.settings.options.url_passthrough.status;
            },
            set(value) {
                this.$store.state.settings.options.url_passthrough.status = value;
            },
        },
        debugModeStatus: {
            get() {
                return this.$store.state.settings.options.gcm_debug_mode.status;
            },
            set(value) {
                this.$store.state.settings.options.gcm_debug_mode.status = value;
            },
        },
        redactDataStatus: {
            get() {
                return this.$store.state.settings.options.redact_ads_data.status;
            },
            set(value) {
                this.$store.state.settings.options.redact_ads_data.status = value;
            },
        },
        gtmTemplateStatus: {
            get() {
                return this.$store.state.settings.options.gtm_template.status;
            },
            set(value) {
                this.saving = true;
                this.$store.state.settings.options.gtm_template.status = value;
                let data = {};
				data.status = value;
				this.setOption("gtm_template", data);
				this.saveOptions();
                this.saving = false;
            },
        },
    },
};
</script>

<style lang="scss">
@include wrap-class() {
    .wcc-gcm-container {
        margin: -12px -20px;
        padding: 12px 20px;
        background-color: #f1f8fe;
    }

    .wcc-gcm-header {
        padding: 10px 0px;
    }

    .wcc-gcm-header .wcc-row {
        align-items: center;
    }

    .wcc-gcm-body {
        .wcc-gtm-settings,
        .wcc-gcm-general-settings,
        .wcc-gcm-default-consent-state {
            border-radius: 12px;
            background-color: #fff;
            margin-bottom: 20px;

            .wcc-app-box {
                border-radius: 12px;
                .wcc-row .wcc-col-9 .wcc-popper-container {
                    margin-right: 10px;
                }
            }
        }

        .wcc-gcm-general-settings-title,
        .wcc-gcm-default-consent-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            padding: 28px 0px 10px 32px;
            color: #2a3646;
        }

        .wcc-gcm-default-consent-description {
            padding: 0px 0px 10px 32px;
            color: #2a3646;
        }
        .wcc-gcm-general-settings label.wcc-col-3 {
            font-weight: 500;
        }
        .wcc-section-separator {
            margin: 0px 30px 0px 30px;
            border-top: 1px solid #EAEBED;
        }
        .wcc-gtm-settings .wcc-row:first-child, .wcc-gtm-settings .wcc-row:last-child {
           margin-top:10px;
        }
        .wcc-gtm-help-label {
            font-size: 12px;
            color: #555E6B;
            font-weight: 400;
            line-height: 14.52px;
            text-align: left;
        }
    }

    .wcc-checkbox-gcm-title {
        color: #3157a6;
        font-size: 16px;
        font-weight: 700;
    }

    .wcc-gcm-support-link {
        width: 337px;
        height: 40px;
        display: inline-flex;
    }

    .wcc-gcm-support-link .wcc-support-logo {
        width: 50px;
        height: 40px;
        background: url("~@/assets/support-icon.svg");
        background-repeat: no-repeat;
        background-position: center;
        background-color: #0576fe;
        padding: 6px 10px 6px 30px;
        border-bottom-left-radius: 10px;
        border-top-left-radius: 10px;
    }

    .wcc-gcm-support-link-wrap {
        display: flex;
        justify-content: flex-end;
    }

    .wcc-gcm-support-link .wcc-support-text {
        font-size: 12px;
        background: #fff;
        padding: 6px 0px 6px 10px;
        border-bottom-right-radius: 10px;
        border-top-right-radius: 10px;
        line-height: 15px;

        a {
            color: #3157a6;
            text-decoration: underline;
        }
    }
    .wcc_gcm_overlay {
        position: relative;
        cursor: not-allowed;
    }
    .wcc_gcm_overlay::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.7);
        z-index: 1;
        pointer-events: none;
    }
    .wcc-gtag-behavior-inner {
        display: flex;
        margin-bottom: 10px;
        .wcc-gtag-advanced,.wcc-popper-container {
            margin-top: 5px;
        }
    }
    .wcc-ads-redact-help {
        font-family: Inter;
        font-size: 12px;
        font-style: italic;
        font-weight: 400;
        line-height: 14.52px;
        text-align: left;
    }
}
</style>
    