<template>
  <div class="pb-6">
    <!-- Header with back button -->
    <div class="shrink-0 mb-4">
      <button @click="goBack" class="hidden md:flex mb-4 items-center gap-2 text-white/70 hover:text-white transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
        Back to Cloud
      </button>

      <!-- Mobile Back Button -->
      <Teleport to="body">
        <button
          @click="goBack"
          class="md:hidden mobile-back-btn glass-button px-6 py-3 rounded-lg font-medium shadow-2xl flex items-center justify-center gap-2"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          <span>Back to Cloud</span>
        </button>
      </Teleport>

      <!-- Peer Header -->
      <div class="flex items-center gap-4">
        <div class="flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center bg-purple-500/15">
          <svg class="w-7 h-7 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2" />
          </svg>
        </div>
        <div class="hidden md:block">
          <div class="flex items-center gap-2">
            <h1 class="text-2xl font-bold text-white">{{ peerDisplayName }}</h1>
            <span
              v-if="transportPill"
              :class="transportPill.cls"
              :title="transportPill.title"
              class="text-xs px-2 py-0.5 rounded-full font-medium"
            >{{ transportPill.label }}</span>
          </div>
          <p v-if="currentPeer?.did" class="text-sm text-white/50 font-mono truncate max-w-md" :title="currentPeer.did">{{ currentPeer.did }}</p>
          <p v-else class="text-sm text-white/50">Peer files</p>
        </div>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading && catalogItems.length === 0" class="glass-card p-8 text-center">
      <svg class="animate-spin h-6 w-6 text-purple-400 mx-auto mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
      <p class="text-white/50 text-sm">Connecting to peer… This may take a few seconds.</p>
    </div>

    <!-- Error -->
    <div v-else-if="catalogError && catalogItems.length === 0" class="glass-card p-6">
      <div class="alert-error mb-4">{{ catalogError }}</div>
      <button class="glass-button px-4 py-2 rounded-lg text-sm" @click="loadCatalog">Retry</button>
    </div>

    <!-- Empty -->
    <div v-else-if="catalogItems.length === 0 && !loading" class="glass-card p-8 text-center">
      <p class="text-white/50">This peer has no shared files.</p>
    </div>

    <!-- Purchase error -->
    <div v-if="purchaseError" class="glass-card p-3 mb-4 flex items-center gap-3 border border-red-500/30">
      <svg class="w-4 h-4 text-red-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <span class="text-sm text-red-400 flex-1">{{ purchaseError }}</span>
      <button class="text-xs text-white/50 hover:text-white" @click="purchaseError = null">Dismiss</button>
    </div>

    <!-- File Grid -->
    <div v-if="catalogItems.length > 0" class="space-y-3">
      <div v-if="loading" class="p-2 text-center text-white/45 text-xs flex items-center justify-center gap-2">
        <svg class="animate-spin h-3.5 w-3.5" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        Refreshing peer files...
      </div>
      <div v-else-if="catalogError" class="p-3 rounded-lg border border-red-400/20 bg-red-500/10 text-red-200/85 text-sm">
        {{ catalogError }}
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div
          v-for="item in catalogItems"
          :key="item.id"
          class="glass-card overflow-hidden flex flex-col h-full"
        >
        <!-- Media preview (images / videos / audio) -->
        <div
          v-if="isMediaMime(item.mime_type)"
          class="relative aspect-video overflow-hidden cursor-pointer group"
          @click="isPlayable(item.mime_type) ? playMedia(item) : undefined"
        >
          <img
            v-if="item.mime_type.startsWith('image/') && previewUrls[item.id]"
            :src="previewUrls[item.id]"
            :alt="item.filename"
            class="w-full h-full object-cover"
            :style="isPaidItem(item.access) ? 'filter: blur(16px); transform: scale(1.15);' : ''"
          />
          <video
            v-else-if="item.mime_type.startsWith('video/') && previewUrls[item.id]"
            :src="previewUrls[item.id]"
            class="w-full h-full object-cover pointer-events-none"
            muted
            autoplay
            loop
            playsinline
          />
          <!-- Audio waveform placeholder -->
          <div v-else-if="item.mime_type.startsWith('audio/')" class="w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-orange-500/10 to-orange-600/5">
            <svg class="w-12 h-12 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" />
            </svg>
            <p class="mt-2 text-xs text-white/50 truncate max-w-[80%]">{{ item.filename.split('/').pop() }}</p>
          </div>
          <div v-else class="w-full h-full flex items-center justify-center" :class="fileIconBg(item.mime_type)">
            <svg class="w-10 h-10" :class="fileIconColor(item.mime_type)" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="fileIconPath(item.mime_type)" />
            </svg>
          </div>
          <!-- Play button overlay for video/audio -->
          <div
            v-if="isPlayable(item.mime_type)"
            class="absolute inset-0 flex items-center justify-center bg-black/0 group-hover:bg-black/30 transition-colors"
          >
            <div class="w-12 h-12 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
              <svg class="w-6 h-6 text-white ml-0.5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M8 5v14l11-7L8 5z" />
              </svg>
            </div>
          </div>
          <!-- Paid badge (top-right) -->
          <div v-if="isPaidItem(item.access)" class="absolute top-2 right-2 flex items-center gap-1.5 px-2 py-1 rounded-lg bg-black/60 backdrop-blur-sm">
            <svg class="w-4 h-4 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
            <span class="text-xs font-medium text-orange-400">{{ getItemPrice(item.access) }} sats</span>
          </div>
          <!-- Preview badge for paid playable items -->
          <div v-if="isPaidItem(item.access) && isPlayable(item.mime_type)" class="absolute bottom-2 left-2 px-2 py-0.5 rounded bg-black/60 backdrop-blur-sm">
            <span class="text-xs text-white/70">10% preview</span>
          </div>
        </div>

        <!-- Card body — pinned to the bottom so the filename + action buttons
             line up across cards of differing preview heights. -->
        <div class="p-4 flex items-center gap-4 mt-auto">
          <div v-if="!isMediaMime(item.mime_type)" class="flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center" :class="fileIconBg(item.mime_type)">
            <svg class="w-5 h-5" :class="fileIconColor(item.mime_type)" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="fileIconPath(item.mime_type)" />
            </svg>
          </div>
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-white truncate">{{ item.filename }}</p>
            <p class="text-xs text-white/40">{{ formatSize(item.size_bytes) }}</p>
          </div>
          <div class="flex items-center gap-2">
            <span
              v-if="!isPaidItem(item.access)"
              class="text-xs px-2 py-0.5 rounded-full"
              :class="accessBadgeClass(item.access)"
            >
              {{ accessLabel(item.access) }}
            </span>
            <!-- Play button for audio/video -->
            <button
              v-if="isPlayable(item.mime_type)"
              class="glass-button px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1.5"
              :disabled="playing === item.id"
              @click="playMedia(item)"
            >
              <template v-if="playing === item.id">
                <div class="w-3 h-3 border-2 border-white/20 border-t-white/80 rounded-full animate-spin"></div>
                <span>Loading...</span>
              </template>
              <template v-else>
                <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M8 5v14l11-7L8 5z" />
                </svg>
                <span>{{ isPaidItem(item.access) ? 'Preview' : 'Play' }}</span>
              </template>
            </button>
            <button
              class="glass-button px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1.5"
              :disabled="downloading === item.id"
              @click="downloadFile(item)"
            >
              <template v-if="downloading === item.id">
                <div class="w-3 h-3 border-2 border-white/20 border-t-white/80 rounded-full animate-spin"></div>
                <span>{{ isPaidItem(item.access) ? 'Paying...' : 'Loading...' }}</span>
              </template>
              <template v-else-if="isPaidItem(item.access)">
                <svg class="w-3.5 h-3.5 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span>Buy {{ getItemPrice(item.access) }} sats</span>
              </template>
              <template v-else>
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                <span>Download</span>
              </template>
            </button>
          </div>
        </div>
        </div>
      </div>
    </div>

    <!-- Video player modal -->
    <Teleport to="body">
      <Transition name="fade">
        <div
          v-if="videoPlayerUrl && videoPlayerItem"
          class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm"
          @click.self="closeVideoPlayer"
        >
          <div class="relative w-full max-w-4xl mx-4">
            <!-- Close button -->
            <button
              class="absolute -top-10 right-0 text-white/60 hover:text-white transition-colors"
              @click="closeVideoPlayer"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
            <!-- Video element -->
            <div class="relative">
              <video
                :src="videoPlayerUrl"
                class="w-full rounded-xl bg-black"
                controls
                autoplay
                @playing="videoLoading = false"
                @canplay="videoLoading = false"
                @error="videoLoading = false; videoError = true"
              />
              <!-- Loader while the stream connects over mesh/Tor -->
              <div v-if="videoLoading && !videoError" class="absolute inset-0 flex flex-col items-center justify-center gap-3 rounded-xl bg-black/60 pointer-events-none">
                <svg class="w-8 h-8 animate-spin text-white/80" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.4 0 0 5.4 0 12h4z" />
                </svg>
                <span class="text-sm text-white/70">Connecting to peer…</span>
              </div>
              <!-- Error state -->
              <div v-if="videoError" class="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-xl bg-black/70 text-center px-4">
                <p class="text-sm text-white/80">Couldn't play this video</p>
                <p class="text-xs text-white/50">The peer may be offline, or this preview can't be played. Try downloading it instead.</p>
              </div>
            </div>
            <!-- Info bar -->
            <div class="mt-3 flex items-center justify-between">
              <div>
                <p class="text-sm font-medium text-white">{{ videoPlayerItem.filename.split('/').pop() }}</p>
                <p class="text-xs text-white/40">{{ formatSize(videoPlayerItem.size_bytes) }}</p>
              </div>
              <div v-if="videoPlayerPaid" class="flex items-center gap-1.5 px-2 py-1 rounded-lg bg-orange-500/15">
                <svg class="w-3.5 h-3.5 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                <span class="text-xs text-orange-400">10% preview - Buy to unlock full</span>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { rpcClient } from '@/api/rpc-client'
import { useAudioPlayer } from '@/composables/useAudioPlayer'

const props = defineProps<{
  peerId?: string
}>()

const router = useRouter()

interface PeerNode {
  did: string
  pubkey: string
  onion: string
  name?: string
  trust_level: string
}

interface CatalogItem {
  id: string
  filename: string
  mime_type: string
  size_bytes: number
  description: string
  access: string | { paid: { price_sats: number } }
}

const loading = ref(true)
const currentPeer = ref<PeerNode | null>(null)
const catalogError = ref('')
const catalogItems = ref<CatalogItem[]>([])
const downloading = ref<string | null>(null)
const playing = ref<string | null>(null)
const purchaseError = ref<string | null>(null)
// Transport actually used to reach this peer (returned by content.browse-peer)
// so we can show a FIPS/Tor pill instead of always assuming Tor (B21).
const transport = ref<string | null>(null)
const transportPill = computed(() => {
  switch (transport.value) {
    case 'fips':
      return { label: 'FIPS', cls: 'bg-green-500/20 text-green-300', title: 'Connected over the fast encrypted mesh (FIPS)' }
    case 'mesh':
      return { label: 'Mesh', cls: 'bg-green-500/20 text-green-300', title: 'Connected over the mesh' }
    case 'lan':
      return { label: 'LAN', cls: 'bg-blue-500/20 text-blue-300', title: 'Connected over the local network' }
    case 'tor':
      return { label: 'Tor', cls: 'bg-amber-500/20 text-amber-300', title: 'Connected over Tor (slower)' }
    default:
      return null
  }
})
const previewUrls = reactive<Record<string, string>>({})
const audioPlayer = useAudioPlayer()

// Video player modal state
const videoPlayerItem = ref<CatalogItem | null>(null)
const videoPlayerUrl = ref<string | null>(null)
const videoPlayerPaid = ref(false)
// Streaming a peer's file connects over mesh/Tor before the first frame, so
// show a loader until the element can actually play (or errors).
const videoLoading = ref(false)
const videoError = ref(false)

const peerDisplayName = computed(() => {
  if (currentPeer.value?.name) return currentPeer.value.name
  if (currentPeer.value?.did) return truncateDid(currentPeer.value.did)
  return props.peerId ? truncateOnion(props.peerId) : 'Peer Files'
})

function goBack() {
  router.push({ name: 'cloud' })
}

onMounted(async () => {
  if (props.peerId) {
    // Find the peer by onion address
    try {
      const result = await rpcClient.federationListNodes()
      const peers = result?.nodes ?? []
      currentPeer.value = peers.find((p: PeerNode) => p.onion === props.peerId) || null
    } catch {
      // Continue with just the onion address
    }
    await loadCatalog()
  } else {
    loading.value = false
  }
})

async function loadCatalog() {
  const onion = props.peerId || currentPeer.value?.onion
  if (!onion) return
  const hadItems = catalogItems.value.length > 0
  loading.value = true
  catalogError.value = ''
  try {
    const result = await rpcClient.call<{ items?: CatalogItem[]; transport?: string }>({
      method: 'content.browse-peer',
      params: { onion },
      timeout: 30000,
    })
    catalogItems.value = result?.items ?? []
    transport.value = result?.transport ?? null
  } catch (e: unknown) {
    catalogError.value = e instanceof Error ? e.message : 'Failed to connect to peer'
    if (!hadItems) catalogItems.value = []
  } finally {
    loading.value = false
  }
}

// Load visual previews for image and video items when catalog loads
// Audio files don't need visual thumbnails — they show a waveform icon
watch(catalogItems, async (items) => {
  const onion = props.peerId || currentPeer.value?.onion
  if (!onion) return
  for (const item of items) {
    if ((item.mime_type.startsWith('image/') || item.mime_type.startsWith('video/')) && !previewUrls[item.id]) {
      loadPreview(onion, item)
    }
  }
})

async function loadPreview(onion: string, item: CatalogItem) {
  try {
    const result = await rpcClient.call<{ data?: string; content_type?: string }>({
      method: 'content.preview-peer',
      params: { onion, content_id: item.id },
      timeout: 30000,
    })
    if (result?.data) {
      const mime = result.content_type || item.mime_type
      const bytes = Uint8Array.from(atob(result.data), c => c.charCodeAt(0))
      const blob = new Blob([bytes], { type: mime })
      previewUrls[item.id] = URL.createObjectURL(blob)
    }
  } catch {
    // Preview not available — icon fallback is fine
  }
}

function truncateDid(did: string): string {
  if (did.length <= 24) return did
  return did.slice(0, 16) + '...' + did.slice(-8)
}

function truncateOnion(onion: string): string {
  if (onion.length <= 20) return onion
  return onion.slice(0, 12) + '...'
}

function formatSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0) + ' ' + units[i]
}

function fileIconBg(mime: string): string {
  if (mime.startsWith('image/')) return 'bg-blue-500/15'
  if (mime.startsWith('audio/')) return 'bg-orange-500/15'
  if (mime.startsWith('video/')) return 'bg-pink-500/15'
  if (mime.startsWith('text/')) return 'bg-green-500/15'
  return 'bg-white/10'
}

function fileIconColor(mime: string): string {
  if (mime.startsWith('image/')) return 'text-blue-400'
  if (mime.startsWith('audio/')) return 'text-orange-400'
  if (mime.startsWith('video/')) return 'text-pink-400'
  if (mime.startsWith('text/')) return 'text-green-400'
  return 'text-white/60'
}

function fileIconPath(mime: string): string {
  if (mime.startsWith('image/')) return 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z'
  if (mime.startsWith('audio/')) return 'M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3'
  if (mime.startsWith('video/')) return 'M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z'
  return 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'
}

function accessLabel(access: CatalogItem['access']): string {
  if (access === 'free') return 'Free'
  if (access === 'peersonly') return 'Peers Only'
  if (typeof access === 'object' && 'paid' in access) return `${access.paid.price_sats} sats`
  return String(access)
}

function accessBadgeClass(access: CatalogItem['access']): string {
  if (access === 'free') return 'bg-green-500/15 text-green-400'
  if (access === 'peersonly') return 'bg-blue-500/15 text-blue-400'
  if (typeof access === 'object' && 'paid' in access) return 'bg-orange-500/15 text-orange-400'
  return 'bg-white/10 text-white/50'
}

function isMediaMime(mime: string): boolean {
  return mime.startsWith('image/') || mime.startsWith('video/') || mime.startsWith('audio/')
}

function isPlayable(mime: string): boolean {
  return mime.startsWith('video/') || mime.startsWith('audio/')
}

function isPaidItem(access: CatalogItem['access']): boolean {
  return typeof access === 'object' && 'paid' in access
}

function getItemPrice(access: CatalogItem['access']): number {
  if (typeof access === 'object' && 'paid' in access) return access.paid.price_sats
  return 0
}

async function downloadFile(item: CatalogItem) {
  const onion = props.peerId || currentPeer.value?.onion
  if (!onion) return
  downloading.value = item.id
  purchaseError.value = null

  try {
    const price = getItemPrice(item.access)

    if (price > 0) {
      // Check ecash balance first
      try {
        const balanceRes = await rpcClient.call<{ balance_sats?: number }>({
          method: 'wallet.ecash-balance',
        })
        const balance = balanceRes?.balance_sats ?? 0
        if (balance < price) {
          purchaseError.value = `Insufficient ecash balance (${balance} sats). Need ${price} sats. Fund your wallet first.`
          return
        }
      } catch {
        // Balance check failed — try the purchase anyway
      }

      // Paid download: mint ecash + download atomically
      const result = await rpcClient.call<{ data?: string; error?: string; price_sats?: number }>({
        method: 'content.download-peer-paid',
        params: { onion, content_id: item.id, price_sats: price },
        timeout: 120000,
      })

      if (result?.data) {
        triggerDownload(result.data, item)
      } else if (result?.error) {
        purchaseError.value = `Payment failed: ${result.error}`
      }
    } else {
      // Free / peers-only download
      const result = await rpcClient.call<{ data?: string; error?: string; price_sats?: number }>({
        method: 'content.download-peer',
        params: { onion, content_id: item.id },
        timeout: 120000,
      })

      if (result?.error === 'payment_required') {
        purchaseError.value = `This content requires payment: ${result.price_sats ?? 0} sats`
        return
      }

      if (result?.data) {
        triggerDownload(result.data, item)
      }
    }
  } catch (e: unknown) {
    purchaseError.value = e instanceof Error ? e.message : 'Download failed'
  } finally {
    downloading.value = null
  }
}

/** Play audio/video inline. For free items, downloads full file; for paid, uses the preview. */
async function playMedia(item: CatalogItem) {
  const onion = props.peerId || currentPeer.value?.onion
  if (!onion) return

  const paid = isPaidItem(item.access)

  // Free content: stream via the Range-capable proxy (B3) so the player can
  // seek and start instantly, instead of downloading the whole file as a
  // base64 blob into a non-seekable Blob URL (which broke video/large audio).
  if (!paid) {
    const streamUrl = `/api/peer-content/${encodeURIComponent(onion)}/${encodeURIComponent(item.id)}`
    if (item.mime_type.startsWith('audio/')) {
      audioPlayer.play(streamUrl, item.filename.split('/').pop() || item.filename)
    } else if (item.mime_type.startsWith('video/')) {
      videoPlayerItem.value = item
      videoPlayerUrl.value = streamUrl
      videoPlayerPaid.value = false
    }
    return
  }

  // Paid content: use the preview/download flow below.
  // If we already have a preview blob URL, use it
  const existingUrl = previewUrls[item.id]
  if (existingUrl) {
    if (item.mime_type.startsWith('audio/')) {
      audioPlayer.play(existingUrl, item.filename.split('/').pop() || item.filename)
    } else if (item.mime_type.startsWith('video/')) {
      videoPlayerItem.value = item
      videoPlayerUrl.value = existingUrl
      videoPlayerPaid.value = paid
    }
    return
  }

  // Download the content (preview for paid, full for free)
  playing.value = item.id
  try {
    const method = paid ? 'content.preview-peer' : 'content.download-peer'
    const result = await rpcClient.call<{ data?: string; content_type?: string }>({
      method,
      params: { onion, content_id: item.id },
      timeout: 120000,
    })

    if (result?.data) {
      const mime = result.content_type || item.mime_type
      const bytes = Uint8Array.from(atob(result.data), c => c.charCodeAt(0))
      const blob = new Blob([bytes], { type: mime })
      const blobUrl = URL.createObjectURL(blob)
      previewUrls[item.id] = blobUrl

      if (item.mime_type.startsWith('audio/')) {
        audioPlayer.play(blobUrl, item.filename.split('/').pop() || item.filename)
      } else if (item.mime_type.startsWith('video/')) {
        videoPlayerItem.value = item
        videoPlayerUrl.value = blobUrl
        videoPlayerPaid.value = paid
      }
    } else {
      purchaseError.value = 'No preview data returned — peer may be offline'
    }
  } catch (e: unknown) {
    purchaseError.value = e instanceof Error ? e.message : 'Failed to load media — peer may be offline'
  } finally {
    playing.value = null
  }
}

function closeVideoPlayer() {
  videoPlayerItem.value = null
  videoPlayerUrl.value = null
  videoPlayerPaid.value = false
  videoLoading.value = false
  videoError.value = false
}

// Show the loader the moment a video opens; the element's playing/canplay/error
// events clear it.
watch(videoPlayerUrl, (url) => {
  if (url) {
    videoLoading.value = true
    videoError.value = false
  }
})

function triggerDownload(base64Data: string, item: CatalogItem) {
  const blob = new Blob(
    [Uint8Array.from(atob(base64Data), c => c.charCodeAt(0))],
    { type: item.mime_type },
  )
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = item.filename.split('/').pop() || item.filename
  a.click()
  URL.revokeObjectURL(url)
}

defineExpose({ loadCatalog })
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
