<template>
    <div :class="barClass">
        <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,
        },
        vertical: {
            type: Boolean,
            default: false,
        },
    },
    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() {
            if (this.vertical) {
                return {
                    height: this.displayedProgress + "%",
                    width: "100%",
                };
            } else {
                return {
                    width: this.displayedProgress + "%",
                    height: "100%",
                };
            }
        },
        barClass() {
            return this.vertical ? "progress-bar-outer-vertical" : "progress-bar-outer";
        },
    },
};
</script>
<style lang="scss">
.progress-bar-outer {
    background: $blue-100;
    height: 5px;
    position: relative;
    border-radius: 0;
    width: 100%;
    margin-top: 0;
    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);
        will-change: width;
        height: 100%;
        background-color: $red;
        position: absolute;
        top: 0;
        left: 0;
        border-radius: 0;
    }
}

.progress-bar-outer-vertical {
    background: $blue-100;
    width: 24px;
    height: 356px;
    position: relative;
    border-radius: 0;
    margin-top: 0;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075);
    overflow: hidden;
    border-radius: 50rem;
    .progress-bar-inner {
        transition: height 0.5s cubic-bezier(0.4, 0, 0.2, 1) !important;
        will-change: height !important;
        width: 100%;
        background-color: $red;
        position: absolute;
        left: 0;
        top: 0;
        border-radius: 50rem;
    }
}
</style>
