"use client";
import React, { useEffect, useState } from "react";

const BackToTop = () => {
    const [active, setActive] = useState(false);
    const [progress, setProgress] = useState(0);

    useEffect(() => {
        const handleScroll = () => {
            const scroll = window.scrollY;
            const height = document.documentElement.scrollHeight - window.innerHeight;
            const progressValue = 307.919 - (scroll * 307.919 / height);

            setProgress(progressValue);

            if (scroll > 150) {
                setActive(true);
            } else {
                setActive(false);
            }
        };

        window.addEventListener("scroll", handleScroll);
        return () => window.removeEventListener("scroll", handleScroll);
    }, []);

    const scrollToTop = () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
    };

    return (
        <div
            className={`backtotop-wrap cursor-pointer ${active ? 'active-progress' : ''}`}
            onClick={scrollToTop}
        >
            <svg className="backtotop-circle svg-content" width="100%" height="100%" viewBox="-1 -1 102 102">
                <path
                    d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98"
                    style={{
                        transition: 'stroke-dashoffset 10ms linear',
                        strokeDasharray: '307.919, 307.919',
                        strokeDashoffset: progress
                    }}
                />
            </svg>
        </div>
    );
};

export default BackToTop;
