// components/SignOutButton.tsx
"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

export default function SignOutButton({
    className,
    redirectTo = "/sign-in",
    children = "Sign out",
}: {
    className?: string;
    redirectTo?: string;
    children?: React.ReactNode;
}) {
    const r = useRouter();
    const [busy, setBusy] = useState(false);

    async function onClick() {
        if (busy) return;
        setBusy(true);
        try {
            await fetch("/api/auth/logout", { method: "POST" });
            r.push(redirectTo);
            r.refresh();
        } catch {
            // ignore; worst case user can hard-refresh
        } finally {
            setBusy(false);
        }
    }

    return (
        <button
        type="button"
        onClick={onClick}
        className={className ?? "text-sm underline hover:opacity-80"}
        disabled={busy}
        >
        {busy ? "Signing out…" : children}
        </button>
    );
}
