<script setup lang="ts">
import { ref } from 'vue'
import { useSessionStore } from '~/stores/session.store'

const sessions = useSessionStore()

function isRealSession(id: string) {
  return !id.startsWith('pending-')
}

const rdpCanvasRefs = ref<Record<string, any>>({})

function setRdpRef(sessionId: string, el: any) {
  if (el) {
    rdpCanvasRefs.value[sessionId] = el
  } else {
    delete rdpCanvasRefs.value[sessionId]
  }
}

function handleRdpDisconnect(sessionId: string) {
  rdpCanvasRefs.value[sessionId]?.disconnect()
}

function handleRdpClipboard(sessionId: string, text: string) {
  rdpCanvasRefs.value[sessionId]?.sendClipboard(text)
}
</script>

<template>
  <div class="absolute inset-0 flex flex-col bg-gray-950">
    <div class="flex-1 overflow-hidden relative">
      <div
        v-for="session in sessions.sessions"
        :key="session.key"
        v-show="session.id === sessions.activeSessionId"
        class="absolute inset-0 flex"
      >
        <!-- SSH session: SFTP sidebar + terminal -->
        <template v-if="session.protocol === 'ssh'">
          <SftpSidebar
            v-if="isRealSession(session.id)"
            :session-id="session.id"
          />
          <div class="flex-1 overflow-hidden">
            <TerminalInstance
              :session-id="session.id"
              :host-id="session.hostId"
              :host-name="session.hostName"
              :color="session.color"
            />
          </div>
        </template>

        <!-- RDP session: Guacamole canvas + floating toolbar -->
        <template v-else-if="session.protocol === 'rdp'">
          <div class="flex-1 overflow-hidden relative">
            <RdpCanvas
              :ref="(el) => setRdpRef(session.id, el)"
              :host-id="session.hostId"
              :host-name="session.hostName"
              :session-id="session.id"
              :color="session.color"
            />
            <RdpToolbar
              :host-name="session.hostName"
              @disconnect="handleRdpDisconnect(session.id)"
              @send-clipboard="(text) => handleRdpClipboard(session.id, text)"
            />
          </div>
        </template>
      </div>
    </div>

    <TransferStatus :transfers="[]" />
  </div>
</template>
