import { useState, useEffect } from 'react';

const useScript = ({
  src,
  async = true,
  type = 'text/javascript',
  noModule = false,
}) => {
  const [status, setStatus] = useState(src ? 'loading' : 'idle');

  useEffect(() => {
    if (!src) {
      setStatus('idle');
      return;
    }

    // Check if the script is already present
    let script = document.querySelector(`script[src="${src}"]`);

    if (!script) {
      // Create script element and add it to the document head
      script = document.createElement('script');
      script.src = src;
      script.async = async;
      script.type = type;
      script.noModule = noModule;

      // Set initial status
      setStatus('loading');

      // Script event listeners
      const onScriptLoad = () => setStatus('ready');
      const onScriptError = () => setStatus('error');

      script.addEventListener('load', onScriptLoad);
      script.addEventListener('error', onScriptError);

      document.head.appendChild(script);

      // Cleanup function
      return () => {
        script.removeEventListener('load', onScriptLoad);
        script.removeEventListener('error', onScriptError);
        document.head.removeChild(script);
      };
    } else {
      // If script is already present, update status accordingly
      setStatus('ready');
    }
  }, [src, async, type, noModule]);

  return status;
};

export default useScript;
