import {useEffect, useState} from 'react'
import {useRoom} from './useRoom'
import {getRoomFromUrl} from './config'
import {Header} from './components/Header'
import {PeerList} from './components/PeerList'
import {Composer} from './components/Composer'
import {TransferList} from './components/TransferList'
import {MessageLog} from './components/MessageLog'

export default function App() {
  const [roomId, setRoomId] = useState<string>(getRoomFromUrl)

  // keep room in sync with the URL hash so #room links work and are shareable
  useEffect(() => {
    const onHashChange = () => setRoomId(getRoomFromUrl())
    window.addEventListener('hashchange', onHashChange)
    return () => window.removeEventListener('hashchange', onHashChange)
  }, [])

  const room = useRoom(roomId)

  // The currently selected message target: a peer id, or null for "everyone".
  const [target, setTarget] = useState<string | null>(null)

  // If the selected target leaves, fall back to broadcast.
  useEffect(() => {
    if (target && !room.others.some(p => p.id === target)) {
      setTarget(null)
    }
  }, [room.others, target])

  return (
    <div className="app">
      <Header
        roomId={roomId}
        selfId={room.selfId}
        selfName={room.selfName}
        onChangeName={room.setSelfName}
        peerCount={room.others.length}
        relayCount={room.relayCount}
      />

      <main className="layout">
        <aside className="col-peers">
          <PeerList
            others={room.others}
            target={target}
            onSelectTarget={setTarget}
          />
        </aside>

        <section className="col-main">
          <Composer
            target={target}
            targetName={
              target
                ? room.others.find(p => p.id === target)?.name ?? target
                : 'Everyone'
            }
            onSendText={room.sendText}
            onSendBinary={room.sendBinary}
          />
          <TransferList transfers={room.transfers} />
          <MessageLog log={room.log} onClear={room.clearLog} />
        </section>
      </main>
    </div>
  )
}
