<template>
  <div class="flex flex-col h-full">
    <div
      ref="containerRef"
      class="terminal-container flex-1"
      @click="terminal.focus()"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { useTerminal } from "@/composables/useTerminal";
import "@/assets/css/terminal.css";

const props = defineProps<{
  sessionId: string;
  isActive: boolean;
}>();

const containerRef = ref<HTMLElement | null>(null);
const { terminal, mount, fit, destroy } = useTerminal(props.sessionId, "pty");
let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  if (containerRef.value) {
    mount(containerRef.value);

    // Watch container size changes and refit terminal
    resizeObserver = new ResizeObserver(() => {
      if (props.isActive) {
        fit();
      }
    });
    resizeObserver.observe(containerRef.value);
  }
  setTimeout(() => {
    fit();
    terminal.focus();
    invoke("pty_resize", {
      sessionId: props.sessionId,
      cols: terminal.cols,
      rows: terminal.rows,
    }).catch(() => {});
  }, 50);
});

watch(
  () => props.isActive,
  (active) => {
    if (active) {
      setTimeout(() => {
        fit();
        terminal.focus();
      }, 0);
    }
  },
);

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
  destroy();
});
</script>
