import { Component } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import { setState } from './core/store.js'
import { loadRemoteGames, remoteReady } from './core/remote.js'
import './styles.css'

// 화면에 문제가 생겨도 하얀 화면 대신 돌아갈 길을 보여 줌
class Guard extends Component {
  state = { err: null }
  static getDerivedStateFromError(err) { return { err } }
  render() {
    if (!this.state.err) return this.props.children
    return (
      <div className="app"><div className="screen"><div className="pad">
        <h1>화면을 그리다 문제가 생겼어요</h1>
        <p>등록한 게임과 기록은 그대로 있어요. 아래 버튼으로 첫 화면으로 돌아가 주세요.</p>
        <button className="btn p" onClick={() => { location.replace('#scan'); location.reload() }}>첫 화면으로</button>
      </div></div></div>
    )
  }
}
createRoot(document.getElementById('root')).render(<Guard><App /></Guard>)

// 서버가 연결되어 있으면 서버의 게임 목록을 받아 씁니다.
if (remoteReady()) {
  loadRemoteGames()
    .then((games) => { if (games && games.length) setState({ games, remote: true }) })
    .catch(() => {})
}
