<template>
  <span>{{ counter }}</span>
</template>

<script>
export default {
    data() {
        return {
            counter: 0,
            observer: null,
            isAnimationTriggered: false,
        };
    },
    props: {
        endNumber: {
            type: Number,
            required: true
        },
        speed: {
            type: Number,
            default: 1000
        }
    },
    mounted() {
        this.initObserver();
    },
    unmounted() {
        if (this.observer) {
            this.observer.disconnect();
        }
    },
    methods: {
        initObserver() {
            const options = {
                root: null,
                threshold: 0.5,
            };
            this.observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        this.startCounter();
                        this.observer.disconnect();
                    }
                });
            }, options);

            const area2 = document.querySelector('.area2');
            this.observer.observe(area2);
        },
        startCounter() {
            const interval = setInterval(() => {
                if (this.counter < this.endNumber) {
                    this.counter += 1;
                } else {
                    clearInterval(interval);
                }
            }, this.speed / this.endNumber);
        }
        // checkScroll() {
        //     const area2 = document.querySelector('.area2');
        //     const top = area2.getBoundingClientRect().top;
        //     const windowHeight = window.innerHeight;

        //     // 當 area2 進入視窗時，觸發動畫
        //     if (top <= windowHeight && !this.isAnimationTriggered) {
        //         this.startCounter();
        //         this.isAnimationTriggered = true; // 標記動畫已觸發
        //     }
        // },
        // startCounter() {
        //     const interval = setInterval(() => {
        //     if (this.counter < this.endNumber) {
        //         this.counter += 1;
        //     } else {
        //         clearInterval(interval);
        //     }
        //     }, this.speed / this.endNumber);
        // }
    }
};
</script>