import { useParams, Link } from 'react-router-dom'
import { Loading, ErrorState } from '../../components/PageState.jsx'
import CharacterSheet from '../../components/CharacterSheet.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { api } from '../../api/client.js'

// A player's character sheet inside the portal. Owner-checked: the endpoint only
// returns a sheet for a character on an account linked to the caller.
export default function PlayerCharacter() {
  const { serial } = useParams()
  const { loading, error, data } = useAsync(() => api.player.shard.char(serial), [serial])
  const restarting = error && error.status === 503
  const forbidden = error && error.status === 403

  return (
    <div>
      <p style={{ margin: '0 0 18px' }}>
        <Link to="/player" className="sans" style={{ color: 'var(--accent)', textDecoration: 'none', fontSize: '0.86rem' }}>
          ← Back to characters
        </Link>
      </p>
      {loading && <Loading />}
      {restarting && <ErrorState message="The game server is restarting — try again shortly." />}
      {forbidden && <ErrorState message="That character is not on an account linked to you." />}
      {error && !restarting && !forbidden && <ErrorState message="Could not load that character right now." />}
      {!loading && !error && data && <CharacterSheet char={data} />}
    </div>
  )
}
