/* eslint-disable react/no-danger */
import { useRef, useEffect } from 'react';
import separateScripts from './separateScripts';
import injectInlineScript from './injectInlineScript';
import injectRemoteScript from './injectRemoteScript';
const Code = function Code(props) {
  const {
    code: rawCode,
    active,
    className
  } = props;
  const injectedInline = useRef();
  const injectedRemote = useRef(new Set());
  const {
    code,
    inline,
    remotes
  } = separateScripts(rawCode);
  useEffect(() => {
    if (!active) return;
    if (inline !== injectedInline.current) {
      injectInlineScript(inline);
      injectedInline.current = inline;
    }
    remotes.forEach(src => {
      if (injectedRemote.current.has(src)) return;
      injectRemoteScript(src);
      injectedRemote.current.add(src);
    });
  }, [active, inline, ...remotes]);
  return <div className={className} dangerouslySetInnerHTML={{
    __html: code
  }} />;
};
Code.nodeToProps = (node, context) => ({
  code: node.data.code,
  active: context.active
});
export default Code;