'use client'

import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'

export default function HeaderActions() {
  const [signedIn, setSignedIn] = useState(false)
  const [role, setRole] = useState<string | null>(null)
  const pathname = usePathname()

  useEffect(() => {
    const token = getToken()
    setSignedIn(Boolean(token))
    if (!token) {
      return
    }
    const load = async () => {
      try {
        const baseUrl = getApiBase()
        const response = await authFetch(`${baseUrl}/auth/me`)
        if (!response.ok) {
          clearToken()
          setSignedIn(false)
          setRole(null)
          return
        }
        const data = await response.json()
        setRole(data?.role ?? null)
      } catch (err) {
        console.error(err)
      }
    }
    void load()
  }, [])

  if (!signedIn) {
    return null
  }

  const items = [
    { href: '/', label: 'Health', icon: '01', match: (path: string) => path === '/' },
    {
      href: '/portal/requests',
      label: 'Requests',
      icon: '02',
      match: (path: string) => path === '/portal/requests' || path.startsWith('/requests/'),
    },
    {
      href: '/portal/issues',
      label: 'Issues',
      icon: '03',
      match: (path: string) => path === '/portal/issues' || path === '/admin/issues',
    },
    {
      href: role === 'admin' ? '/users' : '/profile',
      label: role === 'admin' ? 'Users' : 'Profile',
      icon: '04',
      match: (path: string) => path.startsWith('/users') || path.startsWith('/profile'),
    },
    {
      href: role === 'admin' ? '/admin' : '/profile/invites',
      label: role === 'admin' ? 'Config' : 'Invites',
      icon: '05',
      match: (path: string) => path.startsWith('/admin') || path.startsWith('/profile/invites'),
    },
  ]

  return (
    <nav className="header-actions" aria-label="Primary">
      {items.map((item) => {
        const active = item.match(pathname)
        return (
          <a key={item.href} href={item.href} className={active ? 'is-active' : undefined}>
            <span aria-hidden="true">{item.icon}</span>
            {item.label}
          </a>
        )
      })}
    </nav>
  )
}
