<template>
    <span v-if="!isLoaded"></span>
    <span class="wcc-review-banner-wrapper" v-else-if="showReviewBanner">
        <div class="wcc-review-banner-inner-wrapper">
            <notice type="default" isDismissable class="wcc-review-banner-notice" @onDismiss="handleRemindLater">
                <div class="wcc-align-center">
                    <div class="wcc-review-banner">
                        <h4>{{ $i18n.__("Enjoying WebToffee Cookie Consent? Please leave us a review!",
                            "webtoffee-cookie-consent") }}</h4>
                        <p class="wcc-notice-text">
                            {{ $i18n.__( "Hey, We at WebToffee would like to thank you for using our plugin. We would really appreciate, if you could take a moment to drop a quick review that will inspire us to keep going.",
                            "webtoffee-cookie-consent"
                            )
                            }}
                        </p>
                        <div class="wcc-review-action-buttons">
                            <button class="wcc-button wcc-button-primary" @click="rateUsNow" >{{ $i18n.__("Rate us now", "webtoffee-cookie-consent") }}</button>
                            <button class="wcc-button wcc-button-outline" @click="handleRemindLater">{{ $i18n.__("Remind me later", "webtoffee-cookie-consent") }}</button>
                            <button class="wcc-button wcc-button-link" @click="handleDismiss">{{ $i18n.__("Dismiss forever", "webtoffee-cookie-consent") }}</button>
                        </div>
                    </div>
                </div>
            </notice>
            <div class="wcc-image-background"></div>
        </div>
    </span>
</template>

<script>
import { mapState } from "vuex";
import Notice from "@/components/elements/Notice.vue";
import BaseIcon from "@/components/icons/BaseIcon.vue";

export default {
    name: "ReviewSeekingBanner",
    components: {
        Notice,
        BaseIcon,
    },
    data() {
        return {
            remindLaterCount: 0,
            firstScanCompletedAt: null,
            installedAt: null,
            bannerDismissed: false,
            loading: true, // Set loading to true by default
        };
    },
    methods: {
        async handleDismiss() {
            try {
                const remindLaterData = {
                    remindLaterCount: this.remindLaterCount,
                    remindLaterAt: Math.floor(new Date().getTime() / 1000),
                    dismissed: true, // Set dismissed to true when dismissed
                };
                this.updateReviewData(remindLaterData);
                await this.setOption("review_data", remindLaterData); // Ensure async updates complete
                await this.saveOptions(); // Ensure async updates complete
            } catch (error) {
                console.log(error);
            }
        },
        async handleRemindLater() {
            try {
                this.remindLaterCount++;
                if (this.remindLaterCount >= 3) {
                    this.handleDismiss();
                } else {
                    const remindLaterData = {
                        remindLaterCount: this.remindLaterCount,
                        remindLaterAt: Math.floor(new Date().getTime() / 1000),
                        dismissed: false, // Set dismissed to false for remind later
                    };
                    this.updateReviewData(remindLaterData);
                    await this.setOption("review_data", remindLaterData); // Ensure async updates complete
                    await this.saveOptions(); // Ensure async updates complete
                }
            } catch (error) {
                console.log(error);
            }
        },
        async rateUsNow() {
            try {
                const remindLaterData = {
                    remindLaterCount: this.remindLaterCount,
                    remindLaterAt: Math.floor(new Date().getTime() / 1000),
                    dismissed: true, // Set dismissed to true when rate us now is clicked
                };
                this.updateReviewData(remindLaterData);
                // Open the URL in a new tab
                window.open(  "https://www.webtoffee.com/testimonials/?review=true&product_id=196737",  "_blank" );
                window.location.reload(); // Force full page reload
            } catch (error) {
                console.log(error);
            }
        },
        async loadItems(force = false) {
            try {
                this.loading = true; // Start loading
                this.installedAt = this.$store.state.settings.options.site.installed || Math.floor(new Date().getTime() / 1000);
                this.remindLaterCount = this.$store.state.settings.info.review_reminder.data.remindLaterCount || 0;
                this.bannerDismissed = this.$store.state.settings.info.review_reminder.data.dismissed || false;
                const scans = this.$store.state.settings.info.scans.data || {};
                const scanKeys = Object.keys(scans);
                
                if (scanKeys.length > 0) {
                    // Get the last scan item based on the keys
                    const lastScanKey = scanKeys[scanKeys.length - 1];
                    const lastScan = scans[lastScanKey];
                    this.firstScanCompletedAt = lastScan.date_created || Math.floor(new Date().getTime() / 1000);
                } else {
                    this.firstScanCompletedAt = null;
                }
            } catch (error) {
                console.error(error);
                this.$root.$emit("triggerNotification", {
                    type: "error",
                    message: this.$i18n.__(
                        "An unexpected error occurred. Please try reloading the page or logging in again.",
                        "webtoffee-cookie-consent"
                    ),
                });
            }
            this.loading = false; // Stop loading
        },
    },
    computed: {
        ...mapState("settings", ["info"]),
        showReviewBanner() {
            const now = Math.floor(new Date().getTime() / 1000); // Current time in seconds

            // Check if the scan has been completed, otherwise use `now + 2 hours`
            const scanCompletedAt = this.firstScanCompletedAt || null;
            const twoHoursAfterScan = (scanCompletedAt !== null)
                ? scanCompletedAt + 2 * 60 * 60 // 2 hours after scan (in seconds)
                : now + 2 * 60 * 60; // 2 hours after now if scan not completed

            // 1 day after installation (in seconds)
            const oneDayAfterInstall = Number(this.installedAt) + (24 * 60 * 60); // 1 day after installation in seconds

            // Convert remindLaterAt to a number and calculate 5 days after it (in seconds)
            const remindLaterAt = Number(this.$store.state.settings.info.review_reminder.data.remindLaterAt || now);
            const fiveDaysAfterRemindLater = remindLaterAt + (5 * 24 * 60 * 60); // 5 days after "remind me later" (in seconds)

            // Adjust logic based on remindLaterCount
            let result;
            if (this.remindLaterCount > 0) {
                // Only check if now is >= fiveDaysAfterRemindLater
                result = (
                    this.info.review_reminder.data &&
                    now >= fiveDaysAfterRemindLater &&
                    this.remindLaterCount < 3 && 
                    this.bannerDismissed === false
                );
            } else {
                // Check all conditions
                result = (
                    this.info.review_reminder.data &&
                    (
                        now >= twoHoursAfterScan || // 2 hours after scan
                        now >= oneDayAfterInstall || // 1 day after install
                        now >= fiveDaysAfterRemindLater // 5 days after remind me later
                    ) &&
                    this.remindLaterCount < 3 && 
                    this.bannerDismissed === false
                );
            }

            return result;
        },
        isLoaded() {
            return !this.loading && this.info !== false;
        },
    },

    watch: {
        // Watch for changes in `this.$store.state.settings.info`
        info(newValue) {
            if (newValue !== false) {
                this.loadItems(); // Call loadItems when `info` is populated
            }
        },
    },
    created() {
        // If `info` is already populated, call loadItems immediately
        if (this.info !== false) {
            this.loadItems();
        }
    },
};
</script>


<style lang="scss" scoped>
.wcc-review-banner-inner-wrapper {
    position: relative;
    margin-top: 20px;
    margin-bottom: 10px;
}
.wcc-image-background {
    background: url("~@/assets/review-icon.svg") no-repeat bottom right;
    background-size: contain;
    /* Adjust as needed (e.g., cover, auto, 50% 50%) */
    width: 50%;
    height: 75%;
    position: absolute;
    bottom: 0;
    right: 0;
}
.wcc-review-banner {
    position: relative;
    width: 92%;
}
.wcc-review-banner-wrapper .wcc-admin-notice {
    border-left: 6px solid #3157A6;
    border-bottom: none;
    border-top: none;
    border-radius: unset;
    box-shadow: 0 0 15px 5px rgba(0, 0, 0, 0.2);
}

.wcc-app-wrap .wcc-admin-notice .wcc-admin-notice-content {
    padding: 0;
}

.wcc-review-action-buttons .wcc-button-outline,.wcc-review-action-buttons .wcc-button-link {
    margin-left: 15px;
}
</style>