import React, { useEffect, useState } from 'react'
import CreationDemo from './pages/CreationDemo.jsx'
import CreationQueryDetail from './pages/CreationQueryDetail.jsx'
import DecodeItemDetail from './pages/DecodeItemDetail.jsx'

function parseRoute() {
  const hash = window.location.hash || '#/'
  if (hash.startsWith('#/query/')) {
    const [, runId, queryId] = hash.match(/^#\/query\/([^/]+)\/([^/]+)/) || []
    return { name: 'query', runId: decodeURIComponent(runId || ''), queryId: decodeURIComponent(queryId || '') }
  }
  if (hash.startsWith('#/decode-item/')) {
    const [, itemId] = hash.match(/^#\/decode-item\/([^/]+)/) || []
    return { name: 'decodeItem', itemId: decodeURIComponent(itemId || '') }
  }
  return { name: 'demo' }
}

export default function App() {
  const [route, setRoute] = useState(parseRoute)
  useEffect(() => {
    const onHash = () => setRoute(parseRoute())
    window.addEventListener('hashchange', onHash)
    return () => window.removeEventListener('hashchange', onHash)
  }, [])
  const shellClass = route.name === 'decodeItem' ? 'decode-shell' : 'wrap'
  return (
    <div className={shellClass}>
      {route.name === 'query' ? (
        <CreationQueryDetail runId={route.runId} queryId={route.queryId} />
      ) : route.name === 'decodeItem' ? (
        <DecodeItemDetail itemId={route.itemId} />
      ) : (
        <CreationDemo />
      )}
    </div>
  )
}
