import { useState } from 'react';
import { logout as apiLogout } from '../../lib/api';

export default function LogoutButton() {
  const [busy, setBusy] = useState(false);

  async function handleClick() {
    if (busy) return;
    setBusy(true);
    try {
      await apiLogout();
    } catch {
      /* clear UI anyway */
    }
    window.location.href = '/';
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={busy}
      title="Sign out"
      aria-label="Sign out"
      className="topbar-control topbar-control--danger tc-collapse-sm"
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <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" x2="9" y1="12" y2="12" />
      </svg>
      <span className="tc-label">{busy ? 'Signing out…' : 'Sign out'}</span>
    </button>
  );
}
