// src/components/ExternalScripts.js

import React, { useEffect } from 'react';

const ExternalScripts = () => {
  useEffect(() => {
    // Menambahkan FontAwesome script secara dinamis
    const fontAwesomeScript = document.createElement('script');
    fontAwesomeScript.src = "https://use.fontawesome.com/releases/v6.3.0/js/all.js";
    fontAwesomeScript.crossOrigin = "anonymous";
    fontAwesomeScript.async = true;
    document.body.appendChild(fontAwesomeScript);

    // Menambahkan Chart.js script secara dinamis
    const chartJsScript = document.createElement('script');
    chartJsScript.src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js";
    chartJsScript.crossOrigin = "anonymous";
    chartJsScript.async = true;
    document.body.appendChild(chartJsScript);

    // Menambahkan Simple DataTables JS script secara dinamis
    const simpleDatatablesScript = document.createElement('script');
    simpleDatatablesScript.src = "https://cdn.jsdelivr.net/npm/simple-datatables@7.1.2/dist/umd/simple-datatables.min.js";
    simpleDatatablesScript.crossOrigin = "anonymous";
    simpleDatatablesScript.async = true;
    document.body.appendChild(simpleDatatablesScript);

    // Fungsi untuk menangani event DOMContentLoaded
    const handleDOMContentLoaded = () => {
      console.log('JS Activated');
  
      // Toggle the side navigation
      const sidebarToggle = document.body.querySelector('#sidebarToggle');
      if (sidebarToggle) {
        sidebarToggle.addEventListener('click', event => {
          event.preventDefault();
          document.body.classList.toggle('sb-sidenav-toggled');
          localStorage.setItem('sb|sidebar-toggle', document.body.classList.contains('sb-sidenav-toggled'));
        });
      }
    };

    // Menunggu dokumen siap sebelum menambahkan event listener
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', handleDOMContentLoaded);
    } else {
      handleDOMContentLoaded();
    }

    // Cleanup function untuk menghapus script dan event listener saat komponen unmount
    return () => {
      document.body.removeChild(fontAwesomeScript);
      document.body.removeChild(chartJsScript);
      document.body.removeChild(simpleDatatablesScript);
      document.removeEventListener('DOMContentLoaded', handleDOMContentLoaded);
    };
  }, []);

  return (
    <>
      {/* Link CSS untuk Simple DataTables */}
      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/simple-datatables@7.1.2/dist/style.min.css"
      />
    </>
  );
};

export default ExternalScripts;
