"use client";

import { useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Button } from "@/components/ui/button";

type Props = {
    className?: string;
    /** Where to send users after logout */
    redirectTo?: string; // default /auth/sign-in
};

export default function SignOutButton({
    className,
    redirectTo = "/auth/sign-in",
}: Props) {
    const [pending, setPending] = useState(false);
    const router = useRouter();
    const pathname = usePathname();

    async function onClick() {
        if (pending) return;
        setPending(true);
        try {
            await fetch("/api/auth/logout", { method: "POST" });
            // include ?next= so they can land back here after re-auth if desired
            const next = pathname ? `?next=${encodeURIComponent(pathname)}` : "";
            router.push(redirectTo + next);
            router.refresh(); // ensure cookies are revalidated client-side
        } catch {
            router.push(redirectTo);
        } finally {
            setPending(false);
        }
    }

    return (
        <Button
        type="button"
        onClick={onClick}
        className={className}
        variant="ghost"
        size="sm"
        disabled={pending}
        >
        {pending ? "Signing out…" : "Sign out"}
        </Button>
    );
}
