import { Link, useNavigate } from 'react-router-dom'
import { useAuthStore } from '../store/auth'
import { apiFetch } from '../api/client'

export function ForumHeader() {
  const { user, logout } = useAuthStore()
  const navigate = useNavigate()

  async function handleLogout() {
    // Clear the HttpOnly fingerprint cookie server-side first; without it the
    // JWT becomes unusable per the OWASP token-sidejacking defense even if a
    // copy of the token leaked.
    await apiFetch('/auth/logout', { method: 'POST' }).catch(() => {})
    logout()
    navigate('/')
  }

  return (
    <table
      width="100%"
      cellPadding={0}
      cellSpacing={0}
      style={{ background: '#003399', marginBottom: 4 }}
    >
      <tbody>
        <tr>
          <td style={{ padding: '8px 12px' }}>
            <span
              style={{
                color: '#ffffff',
                fontFamily: 'Verdana, Arial, sans-serif',
                fontSize: 18,
                fontWeight: 'bold',
                letterSpacing: 1,
              }}
            >
              <Link to="/" style={{ color: '#fff', textDecoration: 'none' }}>
                ForumZ
              </Link>
            </span>
            <span
              style={{
                color: '#aabbff',
                fontFamily: 'Verdana, Arial, sans-serif',
                fontSize: 10,
                marginLeft: 10,
              }}
            >
              Your Community Since 2003
            </span>
          </td>
          <td style={{ padding: '8px 12px', textAlign: 'right' }}>
            {user ? (
              <span style={{ fontFamily: 'Verdana, sans-serif', fontSize: 11, color: '#fff' }}>
                Welcome, <strong>{user.username}</strong> &nbsp;|&nbsp;
                <button
                  onClick={handleLogout}
                  style={{
                    background: 'none',
                    border: 'none',
                    color: '#aabbff',
                    cursor: 'pointer',
                    fontFamily: 'Verdana, sans-serif',
                    fontSize: 11,
                    padding: 0,
                  }}
                >
                  Logout
                </button>
              </span>
            ) : (
              <span style={{ fontFamily: 'Verdana, sans-serif', fontSize: 11, color: '#fff' }}>
                <Link to="/login" style={{ color: '#aabbff' }}>Login</Link>
                &nbsp;|&nbsp;
                <Link to="/register" style={{ color: '#aabbff' }}>Register</Link>
              </span>
            )}
          </td>
        </tr>
      </tbody>
    </table>
  )
}
