import {useEffect, useState} from 'react'
import {shortId} from '../util'

type Props = {
  roomId: string
  selfId: string
  selfName: string
  onChangeName: (name: string) => void
  peerCount: number
  relayCount: number
}

export function Header({
  roomId,
  selfId,
  selfName,
  onChangeName,
  peerCount,
  relayCount
}: Props) {
  const [draft, setDraft] = useState(selfName)

  // keep the input in sync if the committed name changes elsewhere
  useEffect(() => setDraft(selfName), [selfName])

  const commit = () => {
    if (draft !== selfName) onChangeName(draft)
  }

  return (
    <header className="header">
      <div className="header-title">
        <h1>
          🤝 Trystero P2P Messaging
        </h1>
        <p className="subtitle">
          Serverless WebRTC over Nostr — no backend, no accounts. Open this page
          in another tab or on another device to see peers appear.
        </p>
      </div>

      <div className="identity">
        <label className="field">
          <span className="field-label">Your name</span>
          <input
            className="name-input"
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onBlur={commit}
            onKeyDown={e => {
              if (e.key === 'Enter') {
                e.currentTarget.blur()
              }
            }}
            maxLength={32}
          />
        </label>
        <div className="identity-meta">
          <span title={selfId}>
            id <code>{shortId(selfId)}</code>
          </span>
          <span>
            room <code>{roomId}</code>
          </span>
          <span>
            <b>{peerCount}</b> peer{peerCount === 1 ? '' : 's'} connected
          </span>
          <span className={relayCount > 0 ? 'dot ok' : 'dot'}>
            {relayCount} nostr relay{relayCount === 1 ? '' : 's'}
          </span>
        </div>
      </div>
    </header>
  )
}
