document.addEventListener('DOMContentLoaded', function () {
  console.log('DOMContentLoaded event fired');
  // Wait for the DOM to load
  // Load header and footer
  loadContent('/html/elements/header.html', document.getElementById('header-placeholder'))
    .then(() => {
      toggleHeaderColor();
      // After loading the header content, initialize toggle button and checkbox for header color
      const toggleButton = document.querySelector('button.toggle-button');
    });

  loadContent('/html/elements/footer.html', document.getElementById('footer-placeholder'));

  // Load external stylesheets
  loadStylesheet('/css/style.css'); // Add more stylesheets if needed
  loadStylesheet('/css/styleHF.css');

  // Retrieve the header element
  const header = document.querySelector('header');

  // Check if the header element exists before initializing the toggle button
  if (header) {
    // Call the function once to set the initial header color based on checkbox state
    toggleHeaderColor();
  }
});

async function loadContent(url, container) {
  try {
    const response = await fetch(url);
    const html = await response.text();
    container.innerHTML = html;

    // After loading the content, load any stylesheets within it
    const stylesheets = container.querySelectorAll('link[rel="stylesheet"]');
    stylesheets.forEach(stylesheet => {
      const href = stylesheet.getAttribute('href');
      loadStylesheet(href);
    });
  } catch (error) {
    console.error('Error loading content:', error);
  }
}

function loadStylesheet(href) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.type = 'text/css';
  link.href = href;
  document.head.appendChild(link);
}

let isLightMode = true;

function toggleHeaderColor() {
  const header = document.querySelector('header');
  const togglebutton = document.querySelector('.toggle-button');
  const body = document.querySelector('body');

  isLightMode = !isLightMode;

  if (!isLightMode) {
    header.style.backgroundColor = 'var(--background-color-dark)';
    header.style.color = 'var(--color-dark)';
    togglebutton.backgroundColor = 'var(--color-button-dark)';
    togglebutton.classList.add('dark-mode');
    togglebutton.classList.remove('light-mode');

    body.style.backgroundColor = 'var(--color-bg-body-dark)';
    body.style.color = 'var(--color-bg-body-light)';
  
  } else {
    header.style.backgroundColor = 'var(--background-color-light)';
    header.style.color = 'var(--color-light)';
    togglebutton.backgroundColor = 'var(--color-button-light)';
    togglebutton.classList.add('light-mode');
    togglebutton.classList.remove('dark-mode');

    body.style.backgroundColor = 'var(--color-bg-body-light)';
    body.style.color = 'var(--color-bg-body-dark)';
  }
}