<template>
  <div
    ref="containerRef"
    class="terminal-container"
    @focus="handleFocus"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useTerminal } from "@/composables/useTerminal";
import { useSessionStore } from "@/stores/session.store";
import "@/assets/css/terminal.css";

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

const sessionStore = useSessionStore();
const containerRef = ref<HTMLElement | null>(null);
const { terminal, mount, fit } = useTerminal(props.sessionId);

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

  // Apply the current theme immediately if one is already active
  if (sessionStore.activeTheme) {
    applyTheme();
  }

  // Track terminal dimensions in the session store
  terminal.onResize(({ cols, rows }) => {
    sessionStore.setTerminalDimensions(props.sessionId, cols, rows);
  });
});

// Re-fit and focus terminal when this tab becomes active
watch(
  () => props.isActive,
  (active) => {
    if (active) {
      // nextTick is not needed — fit and focus happen after the DOM update
      setTimeout(() => {
        fit();
        terminal.focus();
      }, 0);
    }
  },
);

/** Apply the session store's active theme to this terminal instance. */
function applyTheme(): void {
  const theme = sessionStore.activeTheme;
  if (!theme) return;
  terminal.options.theme = {
    background: theme.background,
    foreground: theme.foreground,
    cursor: theme.cursor,
    black: theme.black,
    red: theme.red,
    green: theme.green,
    yellow: theme.yellow,
    blue: theme.blue,
    magenta: theme.magenta,
    cyan: theme.cyan,
    white: theme.white,
    brightBlack: theme.brightBlack,
    brightRed: theme.brightRed,
    brightGreen: theme.brightGreen,
    brightYellow: theme.brightYellow,
    brightBlue: theme.brightBlue,
    brightMagenta: theme.brightMagenta,
    brightCyan: theme.brightCyan,
    brightWhite: theme.brightWhite,
  };
}

// Watch for theme changes in the session store and apply to this terminal
watch(() => sessionStore.activeTheme, (newTheme) => {
  if (newTheme) applyTheme();
});

function handleFocus(): void {
  terminal.focus();
}
</script>
