import { useWaste } from '../store'

export function Sidebar() {
  const { localPeer, 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)
  })

  return (
    <nav className="sidebar">
      <div className="sidebar-identity">
        <span className="alias">{localPeer?.alias}</span>
        <span className="peer-id">{localPeer?.id.slice(0, 8)}…</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>
  )
}
