---
const { date } = Astro.props;
const uniqueId = `time-since-${Math.random().toString(36).substring(2, 9)}`;
---

<span id={uniqueId} data-date={date.getTime()}></span>

<script define:vars={{ uniqueId, dateMS: date.getTime() }}>
    let rafId = null;

    function roundToDp(num, dp) {
        const factor = Math.pow(10, dp);
        return Math.floor(num * factor) / factor;
    }

    function render(milliseconds) {
        const years = roundToDp(
            milliseconds / (60 * 60 * 24 * 365.25 * 1000),
            2
        );

        const element = document.getElementById(uniqueId);
        if (element) {
            element.innerText = `${years}y or ${milliseconds}ms`;
        }
    }

    function tick() {
        const now = Date.now();
        const milliseconds = now - dateMS;
        render(milliseconds);
        rafId = requestAnimationFrame(tick);
    }

    render(Math.max(0, Date.now() - dateMS));
    rafId = requestAnimationFrame(tick);

    function onVisibilityChange() {
        if (document.hidden) {
            if (rafId) {
                cancelAnimationFrame(rafId);
                rafId = null;
            }
        } else {
            if (!rafId) {
                rafId = requestAnimationFrame(tick);
            }
        }
    }

    function cleanup() {
        if (rafId) {
            cancelAnimationFrame(rafId);
            rafId = null;
        }
        window.removeEventListener("visibilitychange", onVisibilityChange);
        window.removeEventListener("unload", cleanup);
    }

    window.addEventListener("visibilitychange", onVisibilityChange);
    window.addEventListener("unload", cleanup);
</script>
