// frontend/src/App.tsx
import React from 'react'
import Uploader from './Uploader'
import Login from './Login'
import { api } from './api'

export default function App() {
  const [authed, setAuthed] = React.useState<boolean | undefined>(undefined)

  React.useEffect(() => {
    api('/api/whoami')
      .then(() => setAuthed(true))
      .catch(() => setAuthed(false))
  }, [])

  async function logout() {
    try {
      await api('/api/logout', { method: 'POST' })
    } finally {
      try {
        location.reload()
      } catch {
        // JSDOM can block navigation APIs; browsers still reload normally.
      }
    }
  }

  return (
    <main>
      <header className="app-header">
        <div className="brand">
          <span className="wing" aria-hidden>🪽</span>
          <strong>Pegasus</strong>
        </div>
        {authed && <button onClick={logout}>Logout</button>}
      </header>

      {authed ? <Uploader /> : <Login onLogin={() => setAuthed(true)} />}
    </main>
  )
}
