'use client'

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

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

  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
  }

  return (
    <div className="header-actions">
      <a className="header-cta header-cta--left" href="/feedback">Send feedback</a>
      <a href="/">Requests</a>
      <a href="/how-it-works">How it works</a>
      {role === 'admin' && <a href="/admin">Settings</a>}
    </div>
  )
}
