import { useEffect } from 'react';
import { useSilkeIframeContext } from './silke-iframe-context';

type SilkeIframeScriptProps = { src?: string; children?: string };

export function SilkeIframeScript({ src, children }: SilkeIframeScriptProps) {
  const { doc } = useSilkeIframeContext();
  useEffect(() => {
    const body = doc?.body;
    if (body) {
      const script = doc.createElement('script');
      if (src) script.src = src;
      else if (children) script.innerHTML = children;
      body.appendChild(script);

      return () => script.remove();
    }
  }, [src, children, doc]);
  return null;
}
