import React, { useEffect, useRef } from "react";
import { getWidget } from "../core/registry";

export interface BaseWidgetProps {
  widgetId: string;
  config: Record<string, unknown>;
  className?: string;
}

export function Widget({ widgetId, config, className }: BaseWidgetProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const instanceRef = useRef<{ destroy?: () => void } | null>(null);
  const configRef = useRef(config);
  const callbacksRef = useRef<Record<string, unknown>>({});

  // Extract and wrap callbacks to always use latest version
  useEffect(() => {
    const wrappedConfig = { ...config };
    
    // Find all callback props (functions starting with 'on')
    Object.keys(config).forEach(key => {
      if (key.startsWith('on') && typeof config[key] === 'function') {
        callbacksRef.current[key] = config[key];
        // Wrap callback to always call the latest version
        wrappedConfig[key] = (...args: unknown[]) => {
          const fn = callbacksRef.current[key] as Function;
          if (fn) fn(...args);
        };
      }
    });
    
    configRef.current = wrappedConfig;
  });

  // Initialize widget only once
  useEffect(() => {
    if (!containerRef.current) return;

    const widget = getWidget(widgetId);
    const instance = widget.init(containerRef.current, configRef.current);
    instanceRef.current = instance || null;

    return () => {
      instanceRef.current?.destroy?.();
    };
  }, [widgetId]);

  return <div ref={containerRef} className={className} />;
}
