'use client'

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

export default function HeaderActions() {
  const [signedIn, setSignedIn] = useState(false)

  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)
          return
        }
        await response.json()
      } 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>
      <div className="header-actions-center">
        <a href="/how-it-works">How it works</a>
      </div>
      <div className="header-actions-right">
        <a href="/">Requests</a>
        <a href="/profile/invites">Invites</a>
        <a href="/portal/requests">Portal</a>
        <a href="/portal/issues">Issues</a>
      </div>
    </div>
  )
}
