import { useState, useEffect } from 'react'
import { generateToken, loadState, saveState } from './api.js'
import { createState } from './gameState.js'
import Ledger from './screens/Ledger.jsx'
import './App.css'

const TOKEN_KEY = 'otivm_token'
const SCREENS = ['ledger', 'map']

export default function App() {
  const [state, setState] = useState(null)
  const [token, setToken] = useState(null)
  const [loading, setLoading] = useState(true)
  const [screen, setScreen] = useState('ledger')

  useEffect(() => {
    async function bootstrap() {
      let tok = localStorage.getItem(TOKEN_KEY)
      if (!tok) {
        tok = generateToken()
        localStorage.setItem(TOKEN_KEY, tok)
      }
      setToken(tok)
      const saved = await loadState(tok)
      if (saved) {
        setState(saved)
      } else {
        const fresh = createState(tok)
        setState(fresh)
        await saveState(tok, fresh)
      }
      setLoading(false)
    }
    bootstrap()
  }, [])

  async function onStateChange(newState) {
    setState(newState)
    await saveState(token, newState)
  }

  if (loading) {
    return (
      <div className="loading">
        <span>Consulting the ledger...</span>
      </div>
    )
  }

  return (
    <div>
      <nav className="main-nav">
        <span className="nav-title">OTIVM</span>
        <div className="nav-links">
          <button
            className={`nav-btn${screen === 'ledger' ? ' active' : ''}`}
            onClick={() => setScreen('ledger')}
          >
            Ledger
          </button>
          <button
            className={`nav-btn${screen === 'map' ? ' active' : ''}`}
            onClick={() => setScreen('map')}
          >
            Map
          </button>
        </div>
      </nav>
      <div className="screen-wrap">
        <div style={{ display: screen === 'ledger' ? 'block' : 'none' }}>
          <Ledger state={state} onStateChange={onStateChange} />
        </div>
        <div style={{ display: screen === 'map' ? 'block' : 'none' }}>
          <div className="placeholder">
            <p>Map — coming in OTIVM-II</p>
          </div>
        </div>
      </div>
    </div>
  )
}
