<script>
    import { onMount, onDestroy } from "svelte"

    let showButton = false

    const checkScroll = () => {
        // Change the visibility of the button based on the scroll position
        showButton = window.pageYOffset > 200
    }

    const scrollToTop = () => {
        if (typeof window !== "undefined") {
            // Scroll smoothly to the top
            window.scrollTo({ top: 0, behavior: "smooth" })
        }
    }

    onMount(() => {
        if (typeof window !== "undefined") {
            // Attach scroll event listener when component is mounted
            window.addEventListener("scroll", checkScroll)
        }
    })

    onDestroy(() => {
        if (typeof window !== "undefined") {
            // Remove scroll event listener when component is destroyed
            window.removeEventListener("scroll", checkScroll)
        }
    })
</script>

{#if showButton}
    <button on:click="{scrollToTop}" class="scroll-to-top"><img src="/media/ToTop.svg" alt="toTop" /> </button>
{/if}

<style lang="less">
    @import "../../assets/css/main.less";
    .scroll-to-top {
        /* Place your styles here */
        position: fixed;
        bottom: 5px;
        z-index: 9999;
        transform: scale(0.5);
        right: 5px;
        @media @tablet {
            bottom: 60px;
            right: 60px;
            transform: scale(1);
        }
    }
</style>
