'use client'

import { createAuthClient } from 'better-auth/react'
import { useRouter, usePathname } from 'next/navigation'
import { LogOut } from 'lucide-react'

const authClient = createAuthClient({
  // Keep auth requests on the current origin (important for tenant subdomains).
  baseURL: typeof window !== 'undefined'
    ? window.location.origin
    : (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3032'),
})

const PAGE_TITLES: Record<string, string> = {
  '/dashboard': 'Übersicht',
  '/dashboard/mitglieder': 'Mitglieder',
  '/dashboard/news': 'News',
  '/dashboard/termine': 'Termine',
  '/dashboard/stellen': 'Lehrlingsbörse',
  '/dashboard/einstellungen': 'Einstellungen',
}

export function Header() {
  const router = useRouter()
  const pathname = usePathname()

  const title = Object.entries(PAGE_TITLES)
    .sort((a, b) => b[0].length - a[0].length)
    .find(([path]) => pathname === path || pathname.startsWith(path + '/'))?.[1] ?? 'Dashboard'

  async function handleSignOut() {
    await authClient.signOut()
    router.push('/login')
  }

  return (
    <header className="h-14 bg-white border-b flex items-center justify-between px-6 flex-shrink-0">
      <h2
        className="text-sm font-semibold text-gray-700 tracking-tight"
        style={{ fontFamily: "'Syne', system-ui, sans-serif" }}
      >
        {title}
      </h2>
      <div className="flex items-center gap-3">
        <button
          onClick={handleSignOut}
          className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-900 transition-colors"
        >
          <LogOut size={14} />
          Abmelden
        </button>
      </div>
    </header>
  )
}
