<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useMeshStore } from '@/stores/mesh'
import { useTransportStore } from '@/stores/transport'
import type { MeshPeer, SessionStatus } from '@/stores/mesh'
import AnimatedLogo from '@/components/AnimatedLogo.vue'
import MeshMap from '@/components/MeshMap.vue'
import MeshBitcoinPanel from '@/views/mesh/MeshBitcoinPanel.vue'
import MeshDeadmanPanel from '@/views/mesh/MeshDeadmanPanel.vue'
import { rpcClient } from '@/api/rpc-client'
import '@/views/mesh/mesh-styles.css'

const mesh = useMeshStore()
const transport = useTransportStore()

// Responsive layout breakpoints
const isWideDesktop = ref(window.innerWidth >= 1536)
const isMobile = ref(window.innerWidth < 1280)

function handleResize() {
  isWideDesktop.value = window.innerWidth >= 1536
  isMobile.value = window.innerWidth < 1280
}

// Active chat: either a peer or a channel
const activeChatPeer = ref<MeshPeer | null>(null)
const activeChatChannel = ref<{ index: number; name: string } | null>(null)
const messageText = ref('')
const sendError = ref('')
const broadcasting = ref(false)
const configuring = ref(false)
const connectingDevice = ref<string | null>(null)
const chatScrollEl = ref<HTMLElement | null>(null)
const mobileShowChat = ref(false)
let pollInterval: ReturnType<typeof setInterval> | null = null

// The Public channel (always available on Meshcore)
const publicChannel = { index: 0, name: 'Public' }

// Channel contact_id convention: matches backend u32::MAX - channel_index
function channelContactId(channelIndex: number): number {
  return 4294967295 - channelIndex // u32::MAX - index
}

// Archipelago Channel — Tor-based messaging to all federated/peered nodes
const archChannelActive = ref(false)
const archMessages = ref<Array<{ from_pubkey: string; from_name?: string; message: string; timestamp: string; direction?: string }>>([])
const archUnread = ref(0)
let archPollInterval: ReturnType<typeof setInterval> | null = null
// Federation node name cache: pubkey -> node name
const fedNodeNames = ref<Record<string, string>>({})

async function openArchChannel() {
  activeChatPeer.value = null
  activeChatChannel.value = null
  archChannelActive.value = true
  archUnread.value = 0
  mobileShowChat.value = true
  // Load federation node names for resolving pubkeys to names
  try {
    const res = await rpcClient.federationListNodes()
    const names: Record<string, string> = {}
    for (const node of res.nodes) {
      if (node.pubkey) names[node.pubkey] = node.name || node.did.slice(0, 12) + '...'
    }
    fedNodeNames.value = names
  } catch { /* non-fatal */ }
  loadArchMessages()
  if (!archPollInterval) {
    archPollInterval = setInterval(loadArchMessages, 15000)
  }
}

async function loadArchMessages() {
  try {
    const res = await rpcClient.getReceivedMessages()
    const newMessages = res.messages || []
    // Track unread: count new received messages since last load
    if (archMessages.value.length > 0 && !archChannelActive.value) {
      const newReceived = newMessages.filter(
        m => m.direction !== 'sent' && m.from_pubkey !== 'me'
          && !archMessages.value.some(existing =>
            existing.from_pubkey === m.from_pubkey && existing.timestamp === m.timestamp
          )
      )
      archUnread.value += newReceived.length
    }
    archMessages.value = newMessages
  } catch { /* silent */ }
}

const sendingArch = ref(false)

async function sendArchMessage() {
  if (!messageText.value.trim()) return
  sendError.value = ''
  sendingArch.value = true
  try {
    const nodes = await rpcClient.federationListNodes()
    // Get our own onion address to skip sending to self
    let selfOnion: string | null = null
    try {
      const tor = await rpcClient.getTorAddress()
      selfOnion = tor.tor_address
    } catch { /* non-fatal */ }
    const msg = messageText.value.trim()
    let sent = 0
    for (const node of nodes.nodes) {
      const nodeOnion = node.onion || node.did
      // Skip sending to ourselves (would create duplicate received message)
      if (selfOnion && (nodeOnion === selfOnion || nodeOnion === selfOnion.replace('.onion', '') || selfOnion === nodeOnion + '.onion')) continue
      try {
        await rpcClient.sendMessageToPeer(nodeOnion, msg)
        sent++
      } catch { /* some peers may be offline */ }
    }
    try {
      await rpcClient.call({ method: 'node-store-sent', params: { message: msg } })
    } catch { /* non-fatal */ }
    messageText.value = ''
    if (sent === 0 && nodes.nodes.length <= 1) sendError.value = 'No other peers in federation — add nodes first'
    await loadArchMessages()
  } catch (e) {
    sendError.value = e instanceof Error ? e.message : 'Send failed'
  } finally {
    sendingArch.value = false
  }
}

const togglingOffGrid = ref(false)
const peerSessionInfo = ref<SessionStatus | null>(null)

// Phase 4: Off-grid Bitcoin + Dead Man's Switch
const activeTab = ref<'chat' | 'bitcoin' | 'deadman' | 'map'>('chat')

// Tools tab for 3rd column on wide desktop and mobile below-chat
const toolsTab = ref<'bitcoin' | 'deadman' | 'map'>('bitcoin')

// Panel visibility computeds
const showChatPanel = computed(() =>
  activeTab.value === 'chat' || isWideDesktop.value || (isMobile.value && mobileShowChat.value)
)
const showBitcoinPanel = computed(() => {
  if (isWideDesktop.value || (isMobile.value && !mobileShowChat.value)) return toolsTab.value === 'bitcoin'
  return activeTab.value === 'bitcoin'
})
const showDeadmanPanel = computed(() => {
  if (isWideDesktop.value || (isMobile.value && !mobileShowChat.value)) return toolsTab.value === 'deadman'
  return activeTab.value === 'deadman'
})
const showMapPanel = computed(() => {
  if (isWideDesktop.value || (isMobile.value && !mobileShowChat.value)) return toolsTab.value === 'map'
  return activeTab.value === 'map'
})
const showMobileTools = computed(() => isMobile.value && !mobileShowChat.value)
const showTabBar = computed(() => !isWideDesktop.value && !isMobile.value)

// Fetch session status when active peer changes
watch(() => activeChatPeer.value, async (peer) => {
  if (peer) {
    try {
      peerSessionInfo.value = await mesh.getSessionStatus(peer.contact_id)
    } catch {
      peerSessionInfo.value = null
    }
  } else {
    peerSessionInfo.value = null
  }
})

async function handleToggleOffGrid() {
  togglingOffGrid.value = true
  try {
    await transport.setMeshOnly(!transport.meshOnly)
  } finally { togglingOffGrid.value = false }
}

onMounted(async () => {
  window.addEventListener('resize', handleResize)
  window.addEventListener('archipelago:share-to-mesh', loadPendingFromSession)
  loadPendingFromSession()
  await Promise.all([mesh.refreshAll(), transport.fetchStatus()])
  // Start background polling for Archipelago (Tor) messages so unread count works
  loadArchMessages()
  if (!archPollInterval) {
    archPollInterval = setInterval(loadArchMessages, 15000)
  }
  pollInterval = setInterval(() => {
    mesh.fetchStatus()
    mesh.fetchPeers()
    mesh.fetchMessages()
    mesh.fetchDeadmanStatus()
    mesh.fetchBlockHeaders()
  }, 5000)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('archipelago:share-to-mesh', loadPendingFromSession)
  if (pollInterval) clearInterval(pollInterval)
  if (archPollInterval) { clearInterval(archPollInterval); archPollInterval = null }
})

// Active chat name for the header
const activeChatName = computed(() => {
  if (archChannelActive.value) return 'Archipelago'
  if (activeChatChannel.value) return activeChatChannel.value.name
  if (activeChatPeer.value) return activeChatPeer.value.advert_name
  return ''
})

const activeChatSub = computed(() => {
  if (archChannelActive.value) return 'All nodes over Tor'
  if (activeChatChannel.value) return 'Mesh radio'
  if (activeChatPeer.value) return truncatePubkey(activeChatPeer.value.pubkey_hex)
  return ''
})

const hasActiveChat = computed(() => !!activeChatPeer.value || !!activeChatChannel.value || archChannelActive.value)

// Messages filtered to the active chat
const chatMessages = computed(() => {
  if (archChannelActive.value) {
    return archMessages.value.map((m, i) => {
      const isSent = m.direction === 'sent' || m.from_pubkey === 'me'
      let peerName = 'Unknown'
      if (isSent) {
        peerName = 'You'
      } else if (m.from_name) {
        peerName = m.from_name
      } else if (fedNodeNames.value[m.from_pubkey]) {
        peerName = fedNodeNames.value[m.from_pubkey]!
      } else {
        peerName = m.from_pubkey.slice(0, 12) + '...'
      }
      return {
        id: i,
        peer_contact_id: -99,
        peer_name: peerName,
        direction: (isSent ? 'sent' : 'received') as 'sent' | 'received',
        plaintext: m.message,
        timestamp: m.timestamp,
        delivered: true,
        encrypted: false,
        message_type: undefined,
        typed_payload: undefined,
      }
    })
  }
  if (activeChatChannel.value) {
    const chanId = channelContactId(activeChatChannel.value.index)
    return mesh.messages.filter(m => m.peer_contact_id === chanId)
  }
  if (activeChatPeer.value) {
    const cid = activeChatPeer.value.contact_id
    return mesh.messages.filter(m => m.peer_contact_id === cid)
  }
  return []
})

function isArchyNode(peer: MeshPeer): boolean {
  return peer.advert_name.startsWith('Archy-')
}

const sortedPeers = computed(() => {
  return [...mesh.peers].sort((a, b) => {
    const aArchy = isArchyNode(a) ? 0 : 1
    const bArchy = isArchyNode(b) ? 0 : 1
    if (aArchy !== bArchy) return aArchy - bArchy
    return a.advert_name.localeCompare(b.advert_name)
  })
})

function openChat(peer: MeshPeer) {
  activeChatPeer.value = peer
  activeChatChannel.value = null
  archChannelActive.value = false
  sendError.value = ''
  messageText.value = ''
  activeTab.value = 'chat'
  mobileShowChat.value = true
  mesh.markChatRead(peer.contact_id)
  nextTick(() => scrollChatToBottom())
}

function openChannelChat(channel: { index: number; name: string }) {
  activeChatChannel.value = channel
  activeChatPeer.value = null
  archChannelActive.value = false
  sendError.value = ''
  messageText.value = ''
  activeTab.value = 'chat'
  mobileShowChat.value = true
  mesh.markChatRead(channelContactId(channel.index))
  nextTick(() => scrollChatToBottom())
}

function closeChat() {
  activeChatPeer.value = null
  activeChatChannel.value = null
  archChannelActive.value = false
  if (archPollInterval) { clearInterval(archPollInterval); archPollInterval = null }
  mobileShowChat.value = false
  mesh.clearViewingChat()
}

async function handleSendMessage() {
  if (archChannelActive.value) {
    await sendArchMessage()
    nextTick(() => scrollChatToBottom())
    return
  }
  // Pending share-to-mesh attachment: Send flushes the CID as a ContentRef
  // rather than a plain text message. Any text in the input becomes the
  // caption. Only valid for direct peers (channel broadcast of content_ref
  // isn't in scope for Phase 3c).
  if (pendingAttachment.value && activeChatPeer.value) {
    sendError.value = ''
    try {
      const caption = messageText.value.trim() || undefined
      await mesh.sendContent(activeChatPeer.value.contact_id, pendingAttachment.value.cid, caption)
      messageText.value = ''
      pendingAttachment.value = null
      nextTick(() => scrollChatToBottom())
    } catch (err: unknown) {
      sendError.value = err instanceof Error ? err.message : 'Share failed'
    }
    return
  }
  if (!messageText.value.trim()) return
  sendError.value = ''
  try {
    if (activeChatChannel.value) {
      await mesh.sendChannelMessage(activeChatChannel.value.index, messageText.value)
      messageText.value = ''
      nextTick(() => scrollChatToBottom())
    } else if (activeChatPeer.value) {
      await mesh.sendMessage(activeChatPeer.value.contact_id, messageText.value)
      messageText.value = ''
      nextTick(() => scrollChatToBottom())
    }
  } catch (err: unknown) {
    sendError.value = err instanceof Error ? err.message : 'Send failed'
  }
}

function scrollChatToBottom() {
  if (chatScrollEl.value) {
    chatScrollEl.value.scrollTop = chatScrollEl.value.scrollHeight
  }
}

async function handleBroadcast() {
  broadcasting.value = true
  try { await mesh.broadcastIdentity() } finally { broadcasting.value = false }
}

async function handleToggleEnabled() {
  configuring.value = true
  try {
    const newEnabled = !(mesh.status?.enabled ?? false)
    await mesh.configure({ enabled: newEnabled })
  } finally { configuring.value = false }
}

async function handleConnectDevice(devicePath: string) {
  connectingDevice.value = devicePath
  try {
    await mesh.configure({ enabled: true, device_path: devicePath } as Partial<import('@/stores/mesh').MeshStatus>)
  } finally {
    connectingDevice.value = null
  }
}

function signalBars(rssi: number | null): number {
  if (rssi === null) return 0
  if (rssi > -60) return 4
  if (rssi > -75) return 3
  if (rssi > -90) return 2
  return 1
}

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const secs = Math.floor(diff / 1000)
  if (secs < 60) return `${secs}s ago`
  const mins = Math.floor(secs / 60)
  if (mins < 60) return `${mins}m ago`
  const hours = Math.floor(mins / 60)
  return `${hours}h ago`
}

function truncatePubkey(hex: string | null): string {
  if (!hex) return ''
  return hex.slice(0, 8) + '...' + hex.slice(-6)
}

// ── Blob store test (Phase 3a) ────────────────────────────────────────────
// Minimal widget to exercise POST /api/blob + GET /blob/<cid> with a
// self-signed capability. Validates the round-trip before we wire
// ContentRef typed-envelope sending.
interface BlobUploadResult {
  cid: string
  size: number
  mime: string
  filename: string | null
  self_test_url: string
}
const blobUploading = ref(false)
const blobResult = ref<BlobUploadResult | null>(null)
const blobError = ref<string | null>(null)
const blobVerifyStatus = ref<string | null>(null)

async function handleBlobUpload(ev: Event) {
  const input = ev.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  blobUploading.value = true
  blobError.value = null
  blobResult.value = null
  blobVerifyStatus.value = null
  try {
    const buf = await file.arrayBuffer()
    const resp = await fetch('/api/blob', {
      method: 'POST',
      headers: {
        'X-Blob-Mime': file.type || 'application/octet-stream',
        'X-Blob-Filename': file.name,
        'Content-Type': 'application/octet-stream',
      },
      credentials: 'include',
      body: buf,
    })
    if (!resp.ok) {
      blobError.value = `upload failed: ${resp.status} ${await resp.text()}`
      return
    }
    blobResult.value = await resp.json()
  } catch (e) {
    blobError.value = e instanceof Error ? e.message : 'upload failed'
  } finally {
    blobUploading.value = false
    if (input) input.value = ''
  }
}

// ── share-to-mesh iframe intent (Phase 3c) ────────────────────────────────
// Marketplace app iframes POST a file to `/api/share-to-mesh` then call
// `window.parent.postMessage({type:'share-to-mesh', cid, ...})`. We park the
// CID as a pending attachment; next time the user picks a peer and hits Send
// (with optional caption text), we call mesh.send-content on that CID.
interface PendingAttachment {
  cid: string
  size: number
  mime: string
  filename: string | null
  self_url?: string
}
const pendingAttachment = ref<PendingAttachment | null>(null)

function loadPendingFromSession() {
  try {
    const raw = sessionStorage.getItem('archipelago_share_to_mesh')
    if (!raw) return
    sessionStorage.removeItem('archipelago_share_to_mesh')
    const data = JSON.parse(raw) as { cid?: string; size?: number; mime?: string; filename?: string | null; self_url?: string }
    if (!data.cid) return
    pendingAttachment.value = {
      cid: data.cid,
      size: data.size ?? 0,
      mime: data.mime ?? 'application/octet-stream',
      filename: data.filename ?? null,
      self_url: data.self_url,
    }
  } catch {
    /* ignore */
  }
}

function clearPendingAttachment() {
  pendingAttachment.value = null
}

// ── ContentRef attach + fetch (Phase 3b) ──────────────────────────────────
const attaching = ref(false)
const attachError = ref<string | null>(null)
const fetchingCids = ref<Set<string>>(new Set())
const fetchedUrls = ref<Map<string, string>>(new Map())

async function handleAttachFile(ev: Event) {
  const input = ev.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  if (!activeChatPeer.value) {
    attachError.value = 'Pick a peer first'
    if (input) input.value = ''
    return
  }
  attaching.value = true
  attachError.value = null
  try {
    const buf = await file.arrayBuffer()
    const up = await fetch('/api/blob', {
      method: 'POST',
      headers: {
        'X-Blob-Mime': file.type || 'application/octet-stream',
        'X-Blob-Filename': file.name,
        'Content-Type': 'application/octet-stream',
      },
      credentials: 'include',
      body: buf,
    })
    if (!up.ok) {
      attachError.value = `upload failed: ${up.status}`
      return
    }
    const { cid } = (await up.json()) as { cid: string }
    await mesh.sendContent(activeChatPeer.value.contact_id, cid, messageText.value.trim() || undefined)
    messageText.value = ''
    nextTick(() => scrollChatToBottom())
  } catch (e) {
    attachError.value = e instanceof Error ? e.message : 'attach failed'
  } finally {
    attaching.value = false
    if (input) input.value = ''
  }
}

async function handleFetchContent(payload: {
  cid: string
  sender_onion: string
  cap_token: string
  cap_exp: number
  mime?: string
  filename?: string | null
}) {
  if (fetchingCids.value.has(payload.cid)) return
  fetchingCids.value.add(payload.cid)
  try {
    const res = await mesh.fetchContent({
      cid: payload.cid,
      sender_onion: payload.sender_onion,
      cap_token: payload.cap_token,
      cap_exp: payload.cap_exp,
      mime: payload.mime,
      filename: payload.filename ?? undefined,
    })
    const r = res as { local_url?: string }
    if (r.local_url) {
      fetchedUrls.value.set(payload.cid, r.local_url)
      fetchedUrls.value = new Map(fetchedUrls.value)
    }
  } catch (e) {
    console.error('fetch-content failed', e)
  } finally {
    fetchingCids.value.delete(payload.cid)
  }
}

function isImageMime(mime?: string): boolean {
  return !!mime && mime.startsWith('image/')
}

async function verifyBlobRoundTrip() {
  if (!blobResult.value) return
  blobVerifyStatus.value = 'fetching...'
  try {
    const resp = await fetch(blobResult.value.self_test_url)
    if (!resp.ok) {
      blobVerifyStatus.value = `FAIL: ${resp.status} ${await resp.text()}`
      return
    }
    const got = await resp.arrayBuffer()
    const expected = blobResult.value.size
    if (got.byteLength === expected) {
      blobVerifyStatus.value = `OK — downloaded ${got.byteLength} bytes, CID verified`
    } else {
      blobVerifyStatus.value = `FAIL — got ${got.byteLength} bytes, expected ${expected}`
    }
  } catch (e) {
    blobVerifyStatus.value = `FAIL: ${e instanceof Error ? e.message : 'unknown'}`
  }
}
</script>

<template>
  <div class="mesh-view">
    <!-- Header (hidden on mobile) -->
    <div class="mesh-header hidden md:flex">
      <div class="mesh-header-left">
        <h1 class="mesh-title">Mesh Network</h1>
        <p class="mesh-subtitle">
          {{ mesh.status?.peer_count ?? 0 }} peer{{ (mesh.status?.peer_count ?? 0) !== 1 ? 's' : '' }}
          <span v-if="mesh.status?.device_connected" class="mesh-subtitle-badge">Live</span>
        </p>
      </div>
      <a
        href="https://flasher.meshcore.co.uk/"
        target="_blank"
        rel="noopener noreferrer"
        class="glass-button mesh-flasher-btn"
      >
        Flash Meshcore <span class="mesh-flasher-sep">|</span> Choose Companion USB
      </a>
    </div>

    <!-- Error banner -->
    <div v-if="mesh.error" class="mesh-error">{{ mesh.error }}</div>

    <!-- Responsive column layout -->
    <div class="mesh-columns" :class="{ 'mesh-columns-wide': isWideDesktop }">
      <!-- LEFT COLUMN: Status + Peers -->
      <div class="mesh-left" data-controller-zone="mesh-left" :class="{ 'mobile-hidden': mobileShowChat }">
        <!-- Device Status -->
        <div data-controller-container tabindex="0" class="glass-card mesh-status-card">
          <div class="mesh-status-header">
            <div class="mesh-status-indicator" :class="mesh.status?.device_connected ? 'connected' : 'disconnected'" />
            <h2 class="mesh-section-title">Device</h2>
          </div>

          <div v-if="mesh.loading && !mesh.status" class="mesh-loading">Loading...</div>

          <div v-else-if="mesh.status" class="mesh-status-grid">
            <div class="mesh-stat">
              <span class="mesh-stat-label">Status</span>
              <span class="mesh-stat-value" :class="mesh.status.device_connected ? 'text-green' : mesh.status.enabled ? 'text-orange' : 'text-muted'">
                {{ mesh.status.device_connected ? 'Broadcasting' : mesh.status.enabled ? 'Connecting...' : 'Disabled' }}
              </span>
            </div>
            <div class="mesh-stat">
              <span class="mesh-stat-label">Type</span>
              <span class="mesh-stat-value">{{ mesh.status.device_type === 'unknown' ? '—' : mesh.status.device_type }}</span>
            </div>
            <div class="mesh-stat">
              <span class="mesh-stat-label">Port</span>
              <span class="mesh-stat-value">{{ mesh.status.device_path ?? 'Auto' }}</span>
            </div>
            <div class="mesh-stat">
              <span class="mesh-stat-label">Sent</span>
              <span class="mesh-stat-value">{{ mesh.status.messages_sent }}</span>
            </div>
            <div class="mesh-stat">
              <span class="mesh-stat-label">Recv</span>
              <span class="mesh-stat-value">{{ mesh.status.messages_received }}</span>
            </div>
            <div class="mesh-stat">
              <span class="mesh-stat-label">Channel</span>
              <span class="mesh-stat-value">{{ mesh.status.channel_name }}</span>
            </div>
          </div>

          <!-- Detected USB devices -->
          <div v-if="mesh.status?.detected_devices?.length" class="mesh-detected-devices">
            <div v-for="dev in mesh.status.detected_devices" :key="dev" class="mesh-device-row">
              <div class="mesh-device-indicator" />
              <span class="mesh-device-path">{{ dev }}</span>
              <button
                v-if="!mesh.status?.device_connected"
                class="glass-button mesh-connect-btn"
                :disabled="connectingDevice !== null"
                @click="handleConnectDevice(dev)"
              >
                {{ connectingDevice === dev ? 'Connecting...' : 'Connect' }}
              </button>
            </div>
          </div>
        </div>

        <!-- Off-grid mode banner -->
        <div v-if="transport.meshOnly" class="mesh-offgrid-banner">
          <svg class="w-4 h-4 text-orange-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636a9 9 0 11-12.728 0M12 9v4m0 4h.01" />
          </svg>
          <span class="text-sm font-medium text-orange-300">OFF-GRID</span>
          <span class="text-xs text-white/50">Tor disabled — mesh only</span>
        </div>

        <!-- Actions row -->
        <div class="mesh-actions" data-controller-container tabindex="0">
          <button class="glass-button mesh-action-btn" :disabled="configuring" @click="handleToggleEnabled">
            {{ mesh.status?.enabled ? 'Disable' : 'Enable' }}
          </button>
          <button class="glass-button mesh-action-btn" :disabled="!mesh.status?.device_connected || broadcasting" @click="handleBroadcast">
            {{ broadcasting ? 'Sending...' : 'Broadcast' }}
          </button>
          <button
            class="glass-button mesh-action-btn"
            :class="transport.meshOnly ? 'mesh-offgrid-active' : ''"
            :disabled="togglingOffGrid"
            @click="handleToggleOffGrid"
          >
            {{ transport.meshOnly ? 'Go Online' : 'Off-Grid' }}
          </button>
          <button class="glass-button mesh-action-btn" @click="mesh.refreshAll()">Refresh</button>
        </div>

        <!-- Peers list -->
        <div data-controller-container tabindex="0" class="glass-card mesh-peers-card">
          <h2 class="mesh-section-title">Peers <span class="mesh-peer-count">{{ mesh.peers.length }}</span></h2>

          <div v-if="mesh.peers.length === 0 && !mesh.status?.device_connected" class="mesh-empty">
            No peers discovered yet.
          </div>

          <div v-else class="mesh-peer-list">
            <!-- Archipelago Channel -->
            <div
              class="mesh-peer-row is-channel"
              :class="{ active: archChannelActive }"
              tabindex="0"
              role="button"
              @click="openArchChannel"
              @keydown.enter="openArchChannel"
            >
              <div class="mesh-peer-avatar channel" style="background: rgba(251,146,60,0.2); color: #fb923c;">A</div>
              <div class="mesh-peer-info">
                <div class="mesh-peer-name">Archipelago</div>
                <div class="mesh-peer-sub">All nodes over Tor</div>
              </div>
              <span v-if="archUnread > 0" class="ml-auto text-[10px] px-1.5 py-0.5 rounded-full bg-orange-500/30 text-orange-300">{{ archUnread }}</span>
            </div>
            <!-- Public channel -->
            <div
              class="mesh-peer-row is-channel"
              :class="{ active: activeChatChannel?.index === 0 }"
              tabindex="0"
              role="button"
              @click="openChannelChat(publicChannel)"
              @keydown.enter="openChannelChat(publicChannel)"
            >
              <div class="mesh-peer-avatar channel">#</div>
              <div class="mesh-peer-info">
                <div class="mesh-peer-name">Public</div>
                <div class="mesh-peer-sub">Mesh radio</div>
              </div>
              <span v-if="mesh.unreadCounts[channelContactId(0)]" class="ml-auto text-[10px] px-1.5 py-0.5 rounded-full bg-orange-500/30 text-orange-300">{{ mesh.unreadCounts[channelContactId(0)] }}</span>
            </div>
            <div
              v-for="peer in sortedPeers" :key="peer.contact_id"
              class="mesh-peer-row"
              :class="{ active: activeChatPeer?.contact_id === peer.contact_id, 'is-archy': isArchyNode(peer) }"
              tabindex="0"
              role="button"
              @click="openChat(peer)"
              @keydown.enter="openChat(peer)"
            >
              <div class="mesh-peer-avatar" :class="{ archy: isArchyNode(peer) }">
                <AnimatedLogo v-if="isArchyNode(peer)" size="sm" />
                <template v-else>{{ peer.advert_name.charAt(0).toUpperCase() }}</template>
              </div>
              <div class="mesh-peer-info">
                <div class="mesh-peer-name">
                  {{ peer.advert_name || `Node #${peer.contact_id}` }}
                  <span v-if="isArchyNode(peer)" class="mesh-peer-archy-badge">Archy</span>
                </div>
                <div class="mesh-peer-sub">{{ truncatePubkey(peer.pubkey_hex) }}</div>
              </div>
              <span v-if="mesh.unreadCounts[peer.contact_id]" class="mesh-unread-badge">
                {{ mesh.unreadCounts[peer.contact_id] }}
              </span>
              <div class="mesh-peer-signal">
                <div class="mesh-signal-bars">
                  <div v-for="i in 4" :key="i" class="mesh-signal-bar" :class="{ active: i <= signalBars(peer.rssi) }" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- RIGHT COLUMN: Tabbed panels -->
      <div class="mesh-right" data-controller-zone="mesh-chat" :class="{ 'mobile-hidden': !mobileShowChat }">
        <!-- Tab bar (medium desktop only) -->
        <div v-if="showTabBar" class="mesh-tab-bar">
          <button class="mesh-tab" :class="{ active: activeTab === 'chat' }" @click="activeTab = 'chat'">Chat</button>
          <button class="mesh-tab" :class="{ active: activeTab === 'bitcoin' }" @click="activeTab = 'bitcoin'">
            Off-Grid Bitcoin
            <span v-if="mesh.latestBlockHeight > 0" class="mesh-tab-badge">{{ mesh.latestBlockHeight }}</span>
          </button>
          <button class="mesh-tab" :class="{ active: activeTab === 'deadman' }" @click="activeTab = 'deadman'">
            Dead Man
            <span v-if="mesh.deadmanStatus?.triggered" class="mesh-tab-badge mesh-tab-badge-alert">!</span>
          </button>
          <button class="mesh-tab" :class="{ active: activeTab === 'map' }" @click="activeTab = 'map'">
            Map
            <span v-if="mesh.nodePositions.size > 0" class="mesh-tab-badge">{{ mesh.nodePositions.size }}</span>
          </button>
        </div>

        <!-- Chat Panel -->
        <div v-if="showChatPanel" data-controller-container tabindex="0" class="glass-card mesh-chat-card">
          <div v-if="!hasActiveChat" class="mesh-chat-empty">
            <div class="mesh-chat-empty-icon">&#x1F4E1;</div>
            <p>Select a peer or channel to chat</p>
            <p class="mesh-chat-empty-sub">Messages are sent over LoRa mesh radio</p>
          </div>
          <template v-else>
            <div class="mesh-chat-header">
              <button class="mesh-chat-back" @click="closeChat">&larr;</button>
              <div class="mesh-chat-header-info">
                <div class="mesh-chat-header-name">
                  {{ activeChatName }}
                  <span v-if="activeChatPeer && isArchyNode(activeChatPeer)" class="mesh-peer-archy-badge">Archy</span>
                  <span v-if="activeChatChannel" class="mesh-peer-channel-badge">Channel</span>
                </div>
                <div class="mesh-chat-header-sub">{{ activeChatSub }}</div>
              </div>
              <div class="mesh-chat-header-status">
                <span v-if="activeChatPeer && peerSessionInfo" class="mesh-session-badge" :class="peerSessionInfo.forward_secrecy ? 'session-ratchet' : peerSessionInfo.has_session ? 'session-static' : 'session-none'" :title="peerSessionInfo.forward_secrecy ? 'Double Ratchet (forward secrecy)' : peerSessionInfo.has_session ? 'Static encryption' : 'No encryption'">&#x1F6E1;</span>
                <span v-if="activeChatPeer" class="mesh-chat-header-time">{{ timeAgo(activeChatPeer.last_heard) }}</span>
              </div>
            </div>
            <div ref="chatScrollEl" class="mesh-chat-messages">
              <div v-if="chatMessages.length === 0" class="mesh-chat-no-messages">
                No messages yet. Say hello!
              </div>
              <div
                v-for="msg in chatMessages" :key="msg.id"
                class="mesh-chat-bubble-wrapper"
                :class="msg.direction"
              >
                <div class="mesh-chat-bubble" :class="[msg.direction, msg.message_type ? 'typed-' + msg.message_type : '']">
                  <!-- Invoice card -->
                  <div v-if="msg.message_type === 'invoice' && msg.typed_payload" class="mesh-typed-invoice">
                    <div class="mesh-typed-invoice-header">
                      <span class="mesh-typed-icon">&#x26A1;</span>
                      <span class="mesh-typed-label">Lightning Invoice</span>
                      <span v-if="msg.typed_payload.paid" class="mesh-typed-paid">Paid</span>
                    </div>
                    <div class="mesh-typed-invoice-amount">{{ (msg.typed_payload.amount_sats || 0).toLocaleString() }} sats</div>
                    <div v-if="msg.typed_payload.memo" class="mesh-typed-invoice-memo">{{ msg.typed_payload.memo }}</div>
                    <div class="mesh-typed-invoice-bolt11">{{ (msg.typed_payload.bolt11 || '').substring(0, 40) }}...</div>
                  </div>
                  <!-- Alert card -->
                  <div v-else-if="msg.message_type === 'alert' && msg.typed_payload" class="mesh-typed-alert" :class="'alert-' + (msg.typed_payload.alert_type || 'status')">
                    <div class="mesh-typed-alert-header">
                      <span class="mesh-typed-icon">{{ msg.typed_payload.alert_type === 'emergency' ? '&#x1F6A8;' : msg.typed_payload.alert_type === 'dead_man' ? '&#x2620;' : '&#x2139;' }}</span>
                      <span class="mesh-typed-label">{{ msg.typed_payload.alert_type === 'emergency' ? 'EMERGENCY' : msg.typed_payload.alert_type === 'dead_man' ? 'DEAD MAN' : 'Status' }}</span>
                      <span v-if="msg.typed_payload.signed" class="mesh-typed-signed">Signed</span>
                    </div>
                    <div class="mesh-typed-alert-message">{{ msg.typed_payload.message }}</div>
                    <a v-if="msg.typed_payload.coordinate" class="mesh-typed-alert-location" :href="'https://www.openstreetmap.org/?mlat=' + (msg.typed_payload.coordinate.lat / 1000000) + '&mlon=' + (msg.typed_payload.coordinate.lng / 1000000) + '&zoom=14'" target="_blank" rel="noopener">
                      &#x1F4CD; {{ msg.typed_payload.coordinate.label || 'View location' }}
                    </a>
                  </div>
                  <!-- Coordinate card -->
                  <div v-else-if="msg.message_type === 'coordinate' && msg.typed_payload" class="mesh-typed-coordinate">
                    <div class="mesh-typed-coordinate-header">
                      <span class="mesh-typed-icon">&#x1F4CD;</span>
                      <span class="mesh-typed-label">Location</span>
                    </div>
                    <div class="mesh-typed-coordinate-value">{{ (msg.typed_payload.lat / 1000000).toFixed(4) }}, {{ (msg.typed_payload.lng / 1000000).toFixed(4) }}</div>
                    <div v-if="msg.typed_payload.label" class="mesh-typed-coordinate-label">{{ msg.typed_payload.label }}</div>
                    <a class="mesh-typed-coordinate-link" :href="'https://www.openstreetmap.org/?mlat=' + (msg.typed_payload.lat / 1000000) + '&mlon=' + (msg.typed_payload.lng / 1000000) + '&zoom=14'" target="_blank" rel="noopener">Open Map</a>
                  </div>
                  <!-- Block header -->
                  <div v-else-if="msg.message_type === 'block_header' && msg.typed_payload" class="mesh-typed-block">
                    <span class="mesh-typed-icon">&#x26D3;</span>
                    <span class="mesh-typed-label">{{ msg.typed_payload.message || msg.plaintext }}</span>
                  </div>
                  <!-- TX relay request -->
                  <div v-else-if="msg.message_type === 'tx_relay' && msg.typed_payload" class="mesh-typed-block">
                    <span class="mesh-typed-icon">&#x21AA;</span>
                    <span class="mesh-typed-label">TX relay #{{ msg.typed_payload.request_id }} ({{ (msg.typed_payload.tx_hex || '').length }} hex chars)</span>
                  </div>
                  <!-- TX relay response -->
                  <div v-else-if="msg.message_type === 'tx_relay_response' && msg.typed_payload" class="mesh-typed-block">
                    <span class="mesh-typed-icon">{{ msg.typed_payload.txid ? '&#x2705;' : '&#x274C;' }}</span>
                    <span class="mesh-typed-label">
                      <template v-if="msg.typed_payload.txid">Broadcast #{{ msg.typed_payload.request_id }}: {{ String(msg.typed_payload.txid).substring(0, 12) }}…</template>
                      <template v-else>TX relay failed #{{ msg.typed_payload.request_id }}: {{ msg.typed_payload.error || 'unknown' }}</template>
                    </span>
                  </div>
                  <!-- TX confirmation -->
                  <div v-else-if="msg.message_type === 'tx_confirmation' && msg.typed_payload" class="mesh-typed-block">
                    <span class="mesh-typed-icon">&#x26D3;</span>
                    <span class="mesh-typed-label">{{ msg.typed_payload.confirmations }} conf @ block {{ msg.typed_payload.block_height }} — {{ String(msg.typed_payload.txid || '').substring(0, 12) }}…</span>
                  </div>
                  <!-- Lightning relay request -->
                  <div v-else-if="msg.message_type === 'lightning_relay' && msg.typed_payload" class="mesh-typed-invoice">
                    <div class="mesh-typed-invoice-header">
                      <span class="mesh-typed-icon">&#x26A1;</span>
                      <span class="mesh-typed-label">Lightning Relay Request</span>
                    </div>
                    <div class="mesh-typed-invoice-amount">{{ (msg.typed_payload.amount_sats || 0).toLocaleString() }} sats</div>
                    <div class="mesh-typed-invoice-bolt11">{{ (msg.typed_payload.bolt11 || '').substring(0, 40) }}…</div>
                  </div>
                  <!-- Lightning relay response -->
                  <div v-else-if="msg.message_type === 'lightning_relay_response' && msg.typed_payload" class="mesh-typed-invoice">
                    <div class="mesh-typed-invoice-header">
                      <span class="mesh-typed-icon">{{ msg.typed_payload.preimage ? '&#x2705;' : '&#x274C;' }}</span>
                      <span class="mesh-typed-label">
                        <template v-if="msg.typed_payload.preimage">Lightning Paid</template>
                        <template v-else>Lightning Failed</template>
                      </span>
                    </div>
                    <div v-if="msg.typed_payload.payment_hash" class="mesh-typed-invoice-bolt11">hash: {{ String(msg.typed_payload.payment_hash).substring(0, 20) }}…</div>
                    <div v-if="msg.typed_payload.preimage" class="mesh-typed-invoice-bolt11">preimage: {{ String(msg.typed_payload.preimage).substring(0, 20) }}…</div>
                    <div v-if="msg.typed_payload.error" class="mesh-typed-invoice-memo">{{ msg.typed_payload.error }}</div>
                  </div>
                  <div v-else-if="msg.message_type === 'content_ref' && msg.typed_payload" class="mesh-typed-content">
                    <div class="mesh-typed-content-meta">
                      <span class="mesh-typed-icon">📎</span>
                      <span class="mesh-typed-label">{{ msg.typed_payload.filename || msg.typed_payload.mime }}</span>
                      <span class="mesh-typed-content-size">{{ msg.typed_payload.size }} B</span>
                    </div>
                    <div v-if="msg.typed_payload.caption" class="mesh-typed-content-caption">{{ msg.typed_payload.caption }}</div>
                    <template v-if="fetchedUrls.get(msg.typed_payload.cid)">
                      <img
                        v-if="isImageMime(msg.typed_payload.mime)"
                        :src="fetchedUrls.get(msg.typed_payload.cid)"
                        class="mesh-typed-content-preview"
                        alt="attachment"
                      />
                      <a v-else :href="fetchedUrls.get(msg.typed_payload.cid)" target="_blank" class="btn">Open</a>
                    </template>
                    <template v-else-if="msg.direction === 'sent'">
                      <span class="mesh-typed-content-hint">(shared from this node)</span>
                    </template>
                    <template v-else>
                      <button
                        class="btn"
                        :disabled="fetchingCids.has(msg.typed_payload.cid)"
                        @click="handleFetchContent(msg.typed_payload as any)"
                      >
                        {{ fetchingCids.has(msg.typed_payload.cid) ? 'Fetching…' : 'Download' }}
                      </button>
                    </template>
                  </div>
                  <!-- Default: plain text -->
                  <div v-else class="mesh-chat-bubble-text">{{ msg.plaintext }}</div>
                  <div class="mesh-chat-bubble-meta">
                    <span v-if="msg.encrypted" class="mesh-chat-e2e">E2E</span>
                    <span v-if="msg.delivered && msg.direction === 'sent'" class="mesh-chat-ack">&#x2713;&#x2713;</span>
                    <span class="mesh-chat-bubble-time">{{ timeAgo(msg.timestamp) }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="mesh-chat-compose">
              <div v-if="sendError" class="mesh-chat-send-error">{{ sendError }}</div>
              <div v-if="attachError" class="mesh-chat-send-error">{{ attachError }}</div>
              <div v-if="pendingAttachment" class="mesh-chat-pending-attachment">
                <span class="mesh-typed-icon">📎</span>
                <span class="mesh-chat-pending-name">{{ pendingAttachment.filename || pendingAttachment.mime }}</span>
                <span class="mesh-chat-pending-size">{{ pendingAttachment.size }} B</span>
                <button class="mesh-chat-pending-clear" @click="clearPendingAttachment" title="Discard attachment">✕</button>
              </div>
              <div class="mesh-chat-compose-row">
                <label
                  v-if="activeChatPeer"
                  class="glass-button mesh-chat-attach-btn"
                  :title="attaching ? 'uploading…' : 'Attach file'"
                >
                  <input type="file" @change="handleAttachFile" style="display:none;" :disabled="attaching" />
                  {{ attaching ? '…' : '📎' }}
                </label>
                <input
                  v-model="messageText"
                  class="mesh-chat-input"
                  :placeholder="activeChatPeer ? 'Type a message or pick a file…' : 'Type a message...'"
                  maxlength="160"
                  @keydown.enter.exact.prevent="handleSendMessage"
                />
                <button
                  class="glass-button mesh-chat-send-btn"
                  :disabled="(!messageText.trim() && !pendingAttachment) || mesh.sending || sendingArch"
                  @click="handleSendMessage"
                >
                  {{ (mesh.sending || sendingArch) ? '...' : (pendingAttachment ? 'Share' : 'Send') }}
                </button>
              </div>
            </div>
          </template>
        </div>

        <!-- Tools panels (3rd column on wide screens) -->
        <div class="mesh-tools-wrapper" data-controller-zone="mesh-tools">
          <!-- Tools tab bar (wide desktop only) -->
          <div v-if="isWideDesktop" class="mesh-tools-tab-bar">
            <button class="mesh-tab" :class="{ active: toolsTab === 'bitcoin' }" @click="toolsTab = 'bitcoin'">
              Off-Grid Bitcoin
              <span v-if="mesh.latestBlockHeight > 0" class="mesh-tab-badge">{{ mesh.latestBlockHeight }}</span>
            </button>
            <button class="mesh-tab" :class="{ active: toolsTab === 'deadman' }" @click="toolsTab = 'deadman'">
              Dead Man
              <span v-if="mesh.deadmanStatus?.triggered" class="mesh-tab-badge mesh-tab-badge-alert">!</span>
            </button>
            <button class="mesh-tab" :class="{ active: toolsTab === 'map' }" @click="toolsTab = 'map'">
              Map
              <span v-if="mesh.nodePositions.size > 0" class="mesh-tab-badge">{{ mesh.nodePositions.size }}</span>
            </button>
          </div>

          <div v-if="showMapPanel" class="glass-card mesh-map-panel"><MeshMap /></div>
          <MeshBitcoinPanel v-if="showBitcoinPanel" />
          <MeshDeadmanPanel v-if="showDeadmanPanel" />
        </div>
      </div>

      <!-- Mobile tools: show under peers list on first view -->
      <div v-if="showMobileTools" class="mesh-mobile-tools">
        <div class="mesh-tools-tab-bar">
          <button class="mesh-tab" :class="{ active: toolsTab === 'bitcoin' }" @click="toolsTab = 'bitcoin'">
            Off-Grid Bitcoin
            <span v-if="mesh.latestBlockHeight > 0" class="mesh-tab-badge">{{ mesh.latestBlockHeight }}</span>
          </button>
          <button class="mesh-tab" :class="{ active: toolsTab === 'deadman' }" @click="toolsTab = 'deadman'">
            Dead Man
            <span v-if="mesh.deadmanStatus?.triggered" class="mesh-tab-badge mesh-tab-badge-alert">!</span>
          </button>
          <button class="mesh-tab" :class="{ active: toolsTab === 'map' }" @click="toolsTab = 'map'">
            Map
            <span v-if="mesh.nodePositions.size > 0" class="mesh-tab-badge">{{ mesh.nodePositions.size }}</span>
          </button>
        </div>
        <div v-if="showMapPanel" class="glass-card mesh-map-panel"><MeshMap /></div>
        <MeshBitcoinPanel v-if="showBitcoinPanel" />
        <MeshDeadmanPanel v-if="showDeadmanPanel" />
      </div>
    </div>

    <!-- Blob store round-trip test (Phase 3a) -->
    <div class="glass-card" style="margin-top: 1rem; padding: 1rem;">
      <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
        <strong>Attachment test (blob store)</strong>
        <span style="font-size: 0.8rem; opacity: 0.7;">Phase 3a — upload, self-signed cap, round-trip verify</span>
      </div>
      <div style="display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap;">
        <label class="btn" style="cursor: pointer;">
          <input type="file" @change="handleBlobUpload" style="display: none;" />
          Pick file
        </label>
        <span v-if="blobUploading">uploading…</span>
        <span v-if="blobError" style="color: #f87171;">{{ blobError }}</span>
      </div>
      <div v-if="blobResult" style="margin-top: 0.75rem; font-family: monospace; font-size: 0.85rem;">
        <div><strong>cid:</strong> {{ blobResult.cid }}</div>
        <div><strong>size:</strong> {{ blobResult.size }} &nbsp; <strong>mime:</strong> {{ blobResult.mime }} &nbsp; <strong>filename:</strong> {{ blobResult.filename || '(none)' }}</div>
        <div style="word-break: break-all;"><strong>url:</strong> {{ blobResult.self_test_url }}</div>
        <div style="margin-top: 0.5rem; display: flex; gap: 0.75rem; align-items: center;">
          <button class="btn" @click="verifyBlobRoundTrip">Verify round-trip</button>
          <a :href="blobResult.self_test_url" target="_blank" class="btn">Open in new tab</a>
          <span v-if="blobVerifyStatus" :style="{ color: blobVerifyStatus.startsWith('OK') ? '#4ade80' : '#f87171' }">{{ blobVerifyStatus }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<!-- Styles extracted to mesh/mesh-styles.css -->
