<template>
  <div
    ref="containerRef"
    class="flex-grow-1 terminal-area"
    @contextmenu="$emit('context-menu', $event)"
  >
    <div
      v-for="tab in sessions"
      :key="tab.id"
      :ref="(el) => onPaneRef(el, tab.id)"
      class="terminal-area__pane"
      :style="paneStyle(tab.id)"
    />

    <div
      v-if="showEmpty"
      class="d-flex flex-column align-center justify-center fill-height pa-6"
    >
      <v-icon size="56" color="primary" class="mb-3">mdi-console-network</v-icon>
      <div class="text-h6 mb-1 text-center">WebSSH 终端</div>
      <div class="text-body-2 text-medium-emphasis mb-4 text-center">
        选择一台服务器开始会话，或从服务器页点击「终端」
      </div>
      <slot name="empty-picker" />
    </div>

    <v-overlay
      v-if="activeSession?.showOverlay"
      :model-value="true"
      contained
      class="terminal-area__overlay d-flex align-center justify-center"
      persistent
      scrim="rgba(0, 0, 0, 0.72)"
    >
      <div class="text-center">
        <div class="text-h6 mb-2">{{ activeSession.overlayMsg }}</div>
        <div v-if="activeSession.reconnectCountdown" class="text-body-2 text-medium-emphasis mb-4">
          {{ activeSession.reconnectCountdown }}
        </div>
        <div class="d-flex ga-3 justify-center">
          <v-btn color="primary" variant="flat" @click="$emit('reconnect')">重新连接</v-btn>
          <v-btn variant="outlined" @click="$emit('go-servers')">返回列表</v-btn>
        </div>
      </div>
    </v-overlay>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { TermSessionData } from '@/composables/terminal/types'

const props = defineProps<{
  sessions: TermSessionData[]
  activeSessionId: string
  activeSession: TermSessionData | null
  showEmpty: boolean
}>()

const emit = defineEmits<{
  'context-menu': [event: MouseEvent]
  reconnect: []
  'go-servers': []
  'pane-ref': [el: unknown, sessionId: string]
}>()

const containerRef = ref<HTMLElement | null>(null)

function paneStyle(sessionId: string): Record<string, string | number> {
  const active = sessionId === props.activeSessionId
  return {
    position: 'absolute',
    top: '0',
    right: '0',
    bottom: '0',
    left: '0',
    zIndex: active ? 1 : 0,
    pointerEvents: active ? 'auto' : 'none',
    opacity: active ? 1 : 0,
  }
}

function onPaneRef(el: unknown, sessionId: string) {
  emit('pane-ref', el, sessionId)
}

defineExpose({ containerRef })
</script>

<style scoped>
.terminal-area {
  position: relative;
  min-height: 0;
  overflow: hidden;
  background: #000000;
}
.terminal-area__overlay {
  z-index: 4;
}
.terminal-area__pane {
  position: absolute;
  inset: 0;
}
.fill-height {
  flex: 1 1 auto;
  min-height: 200px;
}
</style>
