"use client";

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

export function LogoutButton({ className = "" }: { className?: string }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  async function onClick() {
    setBusy(true);
    try {
      await fetch("/api/visitor-auth/logout", { method: "POST" });
    } catch {
      /* noop */
    }
    router.replace("/");
    router.refresh();
  }

  return (
    <button
      type="button"
      onClick={onClick}
      disabled={busy}
      className={
        className ||
        "inline-flex items-center gap-1.5 rounded-full border border-[#ede8e3] bg-white px-3.5 py-1.5 text-xs font-bold text-[#6b7280] transition hover:border-red-300 hover:bg-red-50 hover:text-red-700 disabled:opacity-60"
      }
    >
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
        <polyline points="16 17 21 12 16 7" />
        <line x1="21" y1="12" x2="9" y2="12" />
      </svg>
      {busy ? "Odjavljujem..." : "Odjavi se"}
    </button>
  );
}
