import { useWaste } from '../store'
import { BrowserAdapter } from '../adapter/browser'

function fmt(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

export function FileBrowser() {
  const { activeFilePeer, fileLists, setActiveFilePeer, adapter, connectedPeers } = useWaste()

  if (!activeFilePeer) return null

  const peer = connectedPeers.find(p => p.id === activeFilePeer)
  const files = fileLists[activeFilePeer] ?? null

  function download(name: string) {
    if (adapter instanceof BrowserAdapter) {
      adapter.requestGet(activeFilePeer!, name)
    }
  }

  return (
    <div className="file-browser">
      <div className="file-browser-header">
        <span className="file-browser-title">Files · {peer?.alias ?? activeFilePeer.slice(0, 8)}</span>
        <button className="file-browser-close" onClick={() => setActiveFilePeer(null)}>✕</button>
      </div>

      {files === null ? (
        <div className="file-browser-empty">Loading…</div>
      ) : files.length === 0 ? (
        <div className="file-browser-empty">No files shared</div>
      ) : (
        <ul className="file-list">
          {files.map(f => (
            <li key={f.name} className="file-entry">
              <span className="file-entry-name">{f.name}</span>
              <span className="file-entry-size">{fmt(f.size_bytes)}</span>
              <button className="file-entry-dl" onClick={() => download(f.name)}>↓</button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
