'use client';

// Topbar lives at the top of every authenticated page. The search box
// navigates to /dashboard?q=... so the dashboard always handles search
// rendering. Logout posts to /api/auth/logout then hard-navigates.

import { useRouter } from 'next/navigation';
import { FormEvent, useState } from 'react';
import { Button } from '@/components/ui/Button';

export function Topbar({ user }: { user: { name: string; role: string } }) {
  const router = useRouter();
  const [q, setQ] = useState('');

  function onSearch(e: FormEvent) {
    e.preventDefault();
    const term = q.trim();
    if (!term) return;
    router.push(`/dashboard?q=${encodeURIComponent(term)}`);
  }

  async function logout() {
    await fetch('/api/auth/logout', { method: 'POST' });
    window.location.href = '/login';
  }

  return (
    <header className="flex h-16 shrink-0 items-center gap-4 border-b border-gray-200 bg-white px-6">
      <form onSubmit={onSearch} className="flex-1 max-w-xl">
        <input
          type="search"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Search questions, products, or keywords..."
          className="input"
        />
      </form>

      <div className="flex items-center gap-3">
        <div className="text-right">
          <div className="text-sm font-medium text-gray-900">{user.name}</div>
          <div className="text-xs text-gray-500">{user.role === 'ADMIN' ? 'Administrator' : 'Employee'}</div>
        </div>
        <Button variant="secondary" size="sm" onClick={logout}>
          Sign out
        </Button>
      </div>
    </header>
  );
}
