import { useGame } from '../store/gameStore'
import { isBalanced } from '../lib/judge'
import { BalanceBar } from './BalanceBar'
import { EventCard } from './EventCard'
import { DropZone } from './DropZone'
import { CardTray } from './CardTray'
import { Result } from './Result'

export function GameScreen() {
  const phase  = useGame((s) => s.phase)
  const submit = useGame((s) => s.submit)
  const back   = useGame((s) => s.backToSelect)
  const debit  = useGame((s) => s.placedDebit)
  const credit = useGame((s) => s.placedCredit)

  const canSubmit  = debit.length > 0 && credit.length > 0 && isBalanced(debit, credit)
  const showResult = phase === 'result'

  return (
    <div className="mx-auto flex min-h-screen max-w-4xl flex-col gap-4 px-4 py-5">
      <div className="flex items-center justify-between">
        <button
          onClick={back}
          className="text-sm text-slate-400 hover:text-slate-200"
        >
          ← 論点選択
        </button>
        <ScoreBadge />
      </div>

      <BalanceBar />
      <EventCard />

      <div className="flex flex-col gap-4 sm:flex-row">
        <DropZone side="debit" />
        <DropZone side="credit" />
      </div>

      {showResult ? (
        <Result />
      ) : (
        <>
          <CardTray />
          <button
            onClick={submit}
            disabled={!canSubmit}
            className="rounded-2xl bg-emerald-500 py-4 text-lg font-black text-slate-900 shadow-lg transition enabled:hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-700 disabled:text-slate-500"
          >
            {canSubmit
              ? '仕訳を確定する ✓'
              : debit.length === 0 || credit.length === 0
                ? '借方・貸方の両方にカードを置こう'
                : '借方合計と貸方合計を一致させよう'}
          </button>
        </>
      )}
    </div>
  )
}

function ScoreBadge() {
  const solved  = useGame((s) => s.solved)
  const correct = useGame((s) => s.correct)
  if (solved === 0) return <span />
  return (
    <span className="rounded-full bg-slate-800 px-3 py-1 text-xs text-slate-300">
      {correct} / {solved} 正解
    </span>
  )
}
