<template>
  <div class="dashboard-page">
    <div v-if="loading" class="loading">Loading dashboard...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <iframe
      v-else-if="dashboardUrl"
      :src="dashboardUrl"
      class="dashboard-iframe"
      @load="onIframeLoad"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import tunnelsApi from '@/api/tunnels'

const route = useRoute()
const sessionUuid = route.params.uuid
const dashboardUrl = ref(null)
const loading = ref(true)
const error = ref(null)
let heartbeatInterval = null

async function loadDashboard() {
  loading.value = true
  error.value = null

  try {
    const status = await tunnelsApi.getSessionStatus(sessionUuid)

    if (status.status === 'ready' && status.device_tunnel_port) {
      // Backend proxies dashboard through tunnel
      dashboardUrl.value = `http://192.168.5.4:8000/api/v1/superadmin/tunnels/sessions/${sessionUuid}/dashboard/`
      loading.value = false

      // Start heartbeat
      startHeartbeat()
    } else if (status.status === 'failed') {
      error.value = 'Tunnel connection failed'
      loading.value = false
    } else {
      error.value = 'Dashboard not ready yet'
      loading.value = false
    }
  } catch (err) {
    console.error('Failed to load dashboard:', err)
    error.value = err.response?.data?.detail || 'Failed to load dashboard'
    loading.value = false
  }
}

function startHeartbeat() {
  // Send heartbeat every 30 seconds
  heartbeatInterval = setInterval(async () => {
    try {
      await tunnelsApi.sendHeartbeat(sessionUuid)
      console.log('Heartbeat sent')
    } catch (err) {
      console.error('Heartbeat failed:', err)
    }
  }, 30000)
}

function onIframeLoad() {
  console.log('Dashboard loaded')
}

onMounted(() => {
  loadDashboard()
})

onBeforeUnmount(() => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval)
  }
})
</script>

<style scoped>
.dashboard-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading, .error {
  font-size: 18px;
  padding: 40px;
  text-align: center;
}

.error {
  color: #ff6b6b;
}

.dashboard-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>
