"use client"

import { useEffect, useCallback, useRef } from "react"
import { useRouter } from "next/navigation"
import { createClient } from "@/lib/supabase-browser"
import { toast } from "sonner"

const INACTIVITY_TIMEOUT = 15 * 60 * 1000 // 15 minutes

export function AutoLogoutHandler() {
    const router = useRouter()
    const supabase = createClient()
    const timerRef = useRef<NodeJS.Timeout | null>(null)

    const handleLogout = useCallback(async () => {
        await supabase.auth.signOut()
        toast.info("Oturumunuz uzun süre işlem yapılmadığı için sonlandırıldı.")
        router.push("/login")
        router.refresh()
    }, [router, supabase])

    const resetTimer = useCallback(() => {
        if (timerRef.current) {
            clearTimeout(timerRef.current)
        }
        timerRef.current = setTimeout(handleLogout, INACTIVITY_TIMEOUT)
    }, [handleLogout])

    useEffect(() => {
        // Events to listen for
        const events = [
            "mousedown",
            "mousemove",
            "keydown",
            "scroll",
            "touchstart",
        ]

        // Initial set
        resetTimer()

        // Event listener wrapper to debounce slightly/reset
        const onUserActivity = () => {
            resetTimer()
        }

        events.forEach((event) => {
            window.addEventListener(event, onUserActivity)
        })

        return () => {
            if (timerRef.current) clearTimeout(timerRef.current)
            events.forEach((event) => {
                window.removeEventListener(event, onUserActivity)
            })
        }
    }, [resetTimer])

    return null
}
