<template>
    <div class="progress-bar-outer">
        <div class="progress-bar-inner" :style="progressStyle"></div>
    </div>
</template>

<script>
import store from "@/store";
import { getProgressBarPercentage } from "@/constants/progress-bar-mapper";

// Module-level variable to persist progress across component lifecycles
let lastProgress = 0;

export default {
    name: "progress-bar",
    props: {
        page: {
            type: String,
            required: true,
        },
    },
    data() {
        return {
            displayedProgress: lastProgress,
            timeoutId: null,
        };
    },
    watch: {
        page: {
            immediate: true,
            handler(newPage) {
                const target = getProgressBarPercentage(newPage);
                if (this.timeoutId) clearTimeout(this.timeoutId);

                // Animate from current value to new value
                this.timeoutId = setTimeout(() => {
                    this.displayedProgress = target;
                    lastProgress = target; // Update the module-level variable
                }, 150);
            },
        },
    },
    beforeUnmount() {
        if (this.timeoutId) clearTimeout(this.timeoutId);
    },
    computed: {
        progressStyle() {
            return {
                width: this.displayedProgress + "%",
            };
        },
    },
};
</script>
<style lang="scss">
.progress-bar-outer {
    background: $blue-100;
    height: 10px;
    position: relative;
    border-radius: 10px;
    width: 100%;
    margin-top: 1rem;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075);
    .progress-bar-inner {
        transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1); /* Smooth width transition */
        will-change: width;
        height: 10px;
        background-color: $blue;
        position: absolute;
        top: 0;
        left: 0;
        border-radius: 10px;
    }

    progress {
        height: 10px;
        width: 100%;

        /* Firefox */
        appearance: none;
        background-color: $blue-100;
        border: 0;
        border-radius: $border-radius-pill;
        box-shadow: $box-shadow-inset;

        &::-moz-progress-bar {
            background-color: $blue;
            border-radius: $border-radius-pill;
        }

        /* Webkit */
        -webkit-appearance: none;
        &::-webkit-progress-bar {
            background-color: $blue-100;
            border-radius: $border-radius-pill;
            box-shadow: $box-shadow-inset;
        }
        &::-webkit-progress-value {
            background-color: $blue;
            border-radius: $border-radius-pill;
        }
    }
}
</style>
