<script lang="ts" setup>
import { ref, onMounted } from 'vue'

interface Props {
  url: string
  type?: 'vnc' | 'websocket'
}

const props = withDefaults(defineProps<Props>(), {
  type: 'vnc',
})

const loading = ref<boolean>(true)
const error = ref<string | null>(null)

function onIframeLoad(): void {
  loading.value = false
}

function onIframeError(): void {
  loading.value = false
  error.value = 'Failed to load the console. Please try again.'
}
</script>

<template>
  <div class="web-console">
    <div v-if="loading" class="console-loading d-flex align-center justify-center">
      <div class="text-center">
        <VProgressCircular indeterminate color="primary" size="48" class="mb-4" />
        <div class="text-body-1 text-medium-emphasis">
          Connecting to console...
        </div>
      </div>
    </div>

    <VAlert v-if="error" type="error" variant="tonal" class="ma-4">
      {{ error }}
    </VAlert>

    <iframe
      v-if="url && !error"
      :src="url"
      class="console-iframe"
      allow="clipboard-read; clipboard-write"
      sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
      @load="onIframeLoad"
      @error="onIframeError"
    />

    <div v-if="!url && !loading" class="console-unavailable d-flex align-center justify-center">
      <div class="text-center pa-8">
        <VIcon icon="tabler-terminal-2" size="64" class="text-medium-emphasis mb-4" />
        <h3 class="text-h6 font-weight-bold mb-2">Console Not Available</h3>
        <p class="text-body-2 text-medium-emphasis">
          The console URL could not be retrieved. Please ensure the server is running and try again.
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.web-console {
  position: relative;
  width: 100%;
  min-height: 500px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.console-iframe {
  width: 100%;
  height: 600px;
  border: none;
  display: block;
}

.console-loading,
.console-unavailable {
  position: absolute;
  inset: 0;
  background: rgba(var(--v-theme-surface), 0.95);
  z-index: 1;
}
</style>
