<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";
import type { HistoryWindowState } from "../viewerHudState";

const props = defineProps<{
  windows: HistoryWindowState[];
}>();

const emit = defineEmits<{
  resize: [id: string, width: number, height: number];
}>();

const windowRefs = useTemplateRef<HTMLElement[]>("historyWindows");
let resizeObserver: ResizeObserver | undefined;

onMounted(() => {
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const id = (entry.target as HTMLElement).dataset.historyWindowId;
      if (!id) {
        continue;
      }

      emit("resize", id, entry.contentRect.width, entry.contentRect.height);
    }
  });

  for (const element of windowRefs.value ?? []) {
    resizeObserver.observe(element);
  }
});

watch(
  () => props.windows.map((windowState) => `${windowState.id}:${windowState.width}:${windowState.height}`).join("|"),
  async () => {
    await nextTick();
    resizeObserver?.disconnect();
    for (const element of windowRefs.value ?? []) {
      resizeObserver?.observe(element);
    }
  },
);

onBeforeUnmount(() => {
  resizeObserver?.disconnect();
});
</script>

<template>
  <div class="history-layer">
    <aside
      v-for="windowState in props.windows"
      :key="windowState.id"
      ref="historyWindows"
      class="history-window"
      :data-history-window-id="windowState.id"
      :style="{
        left: `${windowState.x}px`,
        top: `${windowState.y}px`,
        width: `${windowState.width}px`,
        height: `${windowState.height}px`,
        zIndex: windowState.zIndex.toString(),
      }"
    >
      <div class="history-window-header">
        <h2 class="history-window-title">{{ windowState.title }}</h2>
        <div class="history-window-actions">
          <button
            type="button"
            class="history-window-copy"
          >
            {{ windowState.copyLabel }}
          </button>
          <button
            type="button"
            class="history-window-close"
          >
            Close
          </button>
        </div>
      </div>
      <div
        class="history-window-body"
        v-html="windowState.bodyHtml"
      />
    </aside>
  </div>
</template>
