import { useWaste } from '../store'
import type { PeerStatus } from '../store'

function makeYawCard(id: string, alias: string): string {
  const nick = encodeURIComponent(alias.trim().slice(0, 40))
  return nick ? `yaw:${id}?n=${nick}` : `yaw:${id}`
}

function connDot(status: PeerStatus | undefined): { color: string; label: string } {
  const ct = status?.candidateType
  const cs = status?.connState
  if (cs === 'failed' || cs === 'closed') return { color: '#e06060', label: 'failed' }
  if (cs === 'connecting' || cs === 'new') return { color: '#c8a020', label: 'connecting…' }
  if (ct === 'relay') return { color: '#c8a020', label: 'relayed (TURN)' }
  if (ct === 'srflx') return { color: '#60c060', label: 'NAT punched' }
  if (ct === 'host') return { color: '#60c060', label: 'direct (LAN)' }
  if (cs === 'connected') return { color: '#60c060', label: 'connected' }
  return { color: 'var(--muted)', label: 'unknown' }
}

function formatTs(ts: number | undefined): string {
  if (!ts) return '—'
  return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

export function Sidebar() {
  const {
    localPeer, masterId, masterAlias,
    networks, activeNetworkId, activeRoom,
    connectedPeers, peerStatus,
    setActiveRoom, setActiveNetwork, messages, send,
  } = useWaste()

  const rooms = ['general']
  Object.keys(messages).forEach(r => {
    if (r.startsWith('dm:') && !rooms.includes(r)) rooms.push(r)
  })

  const displayAlias = localPeer?.alias ?? masterAlias ?? ''
  const displayId = localPeer?.id ?? masterId ?? ''
  const card = displayId ? makeYawCard(displayId, displayAlias) : null

  function openDM(peerId: string) {
    setActiveRoom(`dm:${peerId}`)
  }

  function requestFiles(peerId: string) {
    send({ type: 'get_file_list', network_id: activeNetworkId ?? undefined, peer_id: peerId })
  }

  return (
    <nav className="sidebar">
      <div
        className="sidebar-identity"
        title={card ?? undefined}
        onClick={() => card && navigator.clipboard?.writeText(card)}
        style={{ cursor: card ? 'pointer' : undefined }}
      >
        <span className="alias">{displayAlias || '…'}</span>
        <span className="peer-id">{displayId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim()}</span>
      </div>

      <div className="sidebar-section">
        <span className="sidebar-label">Networks</span>
        {networks.map(n => (
          <button
            key={n.network_id}
            className={`sidebar-item ${n.network_id === activeNetworkId ? 'active' : ''}`}
            onClick={() => setActiveNetwork(n.network_id)}
          >
            {n.network_name}
          </button>
        ))}
      </div>

      <div className="sidebar-section">
        <span className="sidebar-label">Rooms</span>
        {rooms.map(r => (
          <button
            key={r}
            className={`sidebar-item ${r === activeRoom ? 'active' : ''}`}
            onClick={() => setActiveRoom(r)}
          >
            {r.startsWith('dm:') ? `@ ${r.slice(3, 11)}…` : `# ${r}`}
          </button>
        ))}
      </div>

      <div className="sidebar-section sidebar-peers">
        <span className="sidebar-label">Peers · {connectedPeers.length + 1}</span>

        {/* Self */}
        <div className="peer-row peer-row-self">
          <span className="peer-dot" style={{ background: 'var(--accent)' }} />
          <span className="peer-row-alias" style={{ fontWeight: 700 }}>{displayAlias || '…'}</span>
          <span className="peer-row-id">{displayId.slice(0, 8)}</span>
        </div>

        {connectedPeers.length === 0 && (
          <span className="sidebar-empty">no peers connected</span>
        )}
        {connectedPeers.map(p => {
          const st = peerStatus[p.id]
          const dot = connDot(st)
          const tooltip = [
            p.alias,
            p.id,
            `connection: ${dot.label}`,
            st?.remoteAddress ? `remote: ${st.remoteAddress}` : null,
            st?.lastSeen ? `last seen: ${formatTs(st.lastSeen)}` : null,
          ].filter(Boolean).join('\n')
          return (
            <div key={p.id} className="peer-row" title={tooltip}>
              <span className="peer-dot" style={{ background: dot.color }} />
              <span className="peer-row-alias">{p.alias}</span>
              <span className="peer-row-id">{p.id.slice(0, 8)}</span>
              <span className="peer-row-actions">
                <button className="peer-action" onClick={() => openDM(p.id)} title="DM">↩</button>
                <button className="peer-action" onClick={() => requestFiles(p.id)} title="Files">⊞</button>
              </span>
            </div>
          )
        })}
      </div>
    </nav>
  )
}
