<template>
  <div class="terminal-page">
    <div v-if="loading" class="loading">Loading terminal...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <iframe
      v-else-if="ttydUrl"
      :src="ttydUrl"
      class="terminal-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 ttydUrl = ref(null)
const loading = ref(true)
const error = ref(null)
let heartbeatInterval = null

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

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

    if (status.status === 'ready' && status.ttyd_port) {
      // Backend проксирует WebSocket на localhost ttyd
      ttydUrl.value = `http://192.168.5.4:8000/api/v1/superadmin/tunnels/sessions/${sessionUuid}/terminal`
      loading.value = false

      // Start heartbeat
      startHeartbeat()
    } else if (status.status === 'failed') {
      error.value = 'Tunnel connection failed'
      loading.value = false
    } else {
      error.value = 'Terminal not ready yet'
      loading.value = false
    }
  } catch (err) {
    console.error('Failed to load terminal:', err)
    error.value = err.response?.data?.detail || 'Failed to load terminal'
    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('Terminal loaded')
}

onMounted(() => {
  loadTerminal()
})

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

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

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

.error {
  color: #ff6b6b;
}

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