<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import { getWidget } from "../core/registry";

interface Props {
  widgetId: string;
  config: Record<string, unknown>;
}

const props = defineProps<Props>();
const container = ref<HTMLDivElement | null>(null);
let instance: { destroy?: () => void } | null = null;
const callbacksRef: Record<string, unknown> = {};

// Initialize widget only once on mount with wrapped callbacks
onMounted(() => {
  if (!container.value) return;
  
  // Create wrapped config with stable callback wrappers
  const wrappedConfig = { ...props.config };
  Object.keys(props.config).forEach(key => {
    if (key.startsWith('on') && typeof props.config[key] === 'function') {
      callbacksRef[key] = props.config[key];
      // Wrap callback to always call the latest version
      wrappedConfig[key] = (...args: unknown[]) => {
        const fn = callbacksRef[key] as Function;
        if (fn) fn(...args);
      };
    }
  });
  
  const widget = getWidget(props.widgetId);
  const result = widget.init(container.value, wrappedConfig);
  instance = result || null;
});

// Update callback refs when props change (without reinitializing widget)
watch(() => props.config, (newConfig) => {
  Object.keys(newConfig).forEach(key => {
    if (key.startsWith('on') && typeof newConfig[key] === 'function') {
      callbacksRef[key] = newConfig[key];
    }
  });
}, { deep: true });

onUnmounted(() => {
  instance?.destroy?.();
});
</script>

<template>
  <div ref="container"></div>
</template>
