'use client';

import { useRouter } from 'next/navigation';
import useAuth from '../../hooks/useAuth';

export default function LogoutButton({ variant = 'button' }: { variant?: 'button' | 'text' }) {
  const router = useRouter();
  const { loading, logout } = useAuth();

  const handleLogout = async () => {
    try {
      const result = await logout();
      // prefer client navigation using replace to avoid back history
      router.replace('/login');
    } catch (error) {
      console.error('Error al cerrar sesión:', error);
      // fallback to full reload to ensure server state is cleared
      try {
        window.location.href = '/login';
      } catch {
        /* ignore */
      }
    }
  };

  return (
    <button
      type="button"
      onClick={handleLogout}
      disabled={loading}
      className={variant === 'text'
        ? 'w-full px-3 py-2 text-left text-xs font-semibold text-rose-600 transition hover:bg-rose-50 hover:text-rose-700 disabled:cursor-not-allowed disabled:opacity-70'
        : 'rounded-3xl bg-rose-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-rose-700 disabled:cursor-not-allowed disabled:opacity-70'}
    >
      Cerrar sesión
    </button>
  );
}
