import { useWaste } 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}`
}

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

  // Rooms = general + any DM threads that have messages
  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

  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>
        {card && <span className="peer-id" style={{ fontSize: '9px', opacity: 0.5 }}>click to copy card</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>
    </nav>
  )
}
