document.addEventListener('DOMContentLoaded', () => {
  loadNavbar();
  initSlideshow();
  initTabs();
  initServiceTimedText();
  initServiceRequestForm();
  setFooterYear();
});

function loadNavbar() {
  fetch('/includes/navbar.html?v=2.2.8')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      return response.text();
    })
    .then(html => {
      const navContainer = document.getElementById('nav-container');

      if (!navContainer) {
        return;
      }

      navContainer.innerHTML = html;
      bindMobileMenu();
      bindDropdownMenus();
      highlightActiveLink();
    })
    .catch(err => console.error('Navbar include failed:', err));
}

function bindMobileMenu() {
  const menuToggle = document.querySelector('.menu-toggle');
  const navList = document.querySelector('.nav-list');

  if (!menuToggle || !navList) {
    return;
  }

  menuToggle.addEventListener('click', () => {
    navList.classList.toggle('active');
  });
}

function bindDropdownMenus() {
  const dropdowns = document.querySelectorAll('.dropdown');

  dropdowns.forEach(dropdown => {
    let closeTimer;

    dropdown.addEventListener('mouseenter', () => {
      clearTimeout(closeTimer);
      dropdown.classList.add('open');
    });

    dropdown.addEventListener('mouseleave', () => {
      closeTimer = setTimeout(() => {
        dropdown.classList.remove('open');
      }, 350);
    });
  });
}

function highlightActiveLink() {
  const currentPath = window.location.pathname;

  document.querySelectorAll('.nav-link[href]').forEach(link => {
  const linkPath = new URL(link.href, window.location.origin).pathname;

    if (
      currentPath === linkPath ||
      (linkPath !== '/' && currentPath.startsWith(linkPath))
    ) {
      link.classList.add('active');
    }
  });
}

function initSlideshow() {
  const slides = document.querySelectorAll('.slide');
  const prevSlide = document.querySelector('.prev-slide');
  const nextSlide = document.querySelector('.next-slide');

  if (!slides.length) {
    return;
  }

  let currentSlide = 0;

  function showSlide(index) {
    slides.forEach((slide, i) => {
      slide.classList.toggle('active', i === index);
    });
  }

  prevSlide?.addEventListener('click', () => {
    currentSlide = (currentSlide - 1 + slides.length) % slides.length;
    showSlide(currentSlide);
  });

  nextSlide?.addEventListener('click', () => {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide(currentSlide);
  });

  setInterval(() => {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide(currentSlide);
  }, 5000);
}

function initTabs() {
  const tabButtons = document.querySelectorAll('.tab-button');
  const tabContents = document.querySelectorAll('.tab-content');

  tabButtons.forEach(button => {
    button.addEventListener('click', () => {
      const tab = button.dataset.tab;
      const activeContent = document.getElementById(tab);

      tabButtons.forEach(btn => btn.classList.remove('active'));
      tabContents.forEach(content => content.classList.remove('active'));

      button.classList.add('active');
      activeContent?.classList.add('active');
    });
  });
}

function initServiceRequestForm() {
  const problemOptions = document.querySelectorAll('input[name="problem_type"]');
  const problemOther = document.getElementById('problem_other');

  if (!problemOptions.length || !problemOther) {
    return;
  }

  function updateProblemOtherRequirement() {
    const selectedProblem = document.querySelector('input[name="problem_type"]:checked');
    const requiresDescription = selectedProblem
      && ['Other', 'Error Code'].includes(selectedProblem.value);

    problemOther.required = Boolean(requiresDescription);

    if (selectedProblem?.value === 'Error Code') {
      problemOther.placeholder = 'Enter the error code or describe the error';
    } else if (selectedProblem?.value === 'Other') {
      problemOther.placeholder = 'Please describe the issue';
    } else {
      problemOther.placeholder = 'Required for Other or Error Code';
    }
  }

  problemOptions.forEach(option => {
    option.addEventListener('change', updateProblemOtherRequirement);
  });

  updateProblemOtherRequirement();
}

function initServiceTimedText() {
  const audio = document.getElementById('serviceAudio');
  const left = document.getElementById('timedTextLeft');
  const right = document.getElementById('timedTextRight');

  if (!audio || !left || !right) {
    return;
  }

audio.volume = 0.5;

  const cues = [
    { start: 0, side: 'left', text: 'IN A WORLD WHERE ONE MINUTE OF DOWNTIME CAN CHANGE EVERYTHING...' },
    { start: 4, side: 'right', text: 'WHAT IF YOUR PRINTERS COULD SEE A FAILURE BEFORE IT EVER HAPPENED?' },
    { start: 9, side: 'left', text: 'REMOTE MONITORING, PREDICTIVE DIAGNOSTICS, ZERO-DOWNTIME RESPONSE.' },
    { start: 14, side: 'right', text: 'Kyocera Fleet Services continuously scans your entire printer fleet, detecting issues, forecasting failures, and alerting IBS technicians BEFORE YOUR BUSINESS FEELS THE IMPACT.' },
    { start: 24, side: 'left', text: 'KYOCERA FLEET SERVICES; THE FUTURE KNOWS.' },
    { start: 30, side: 'right', text: 'PREDICT. PREVENT. PERFORM.' },
    { start: 34, side: 'left', text: 'An INDEPENDENT BUSINESS SYSTEMS PRODUCTION, starring Kyocera Technology.' },
    { start: 38, side: 'right', text: 'Real-Time Analytics, Predictive Alerts, Remote Repairs.' },
    { start: 42, side: 'left', text: 'Directed by future Intelligence.' },
    { start: 44, side: 'right', text: 'COMING TO YOUR OFFICE... TODAY.' }
  ];

  function resetTimedText() {
  left.innerHTML = '';
  right.innerHTML = '';
  left.classList.remove('has-ended');
  right.classList.remove('has-ended');

  cues.forEach(cue => {
    cue.shown = false;
  });
}

  function addCue(cue) {
    const line = document.createElement('div');
    line.className = 'timed-text-line';
    line.textContent = cue.text;

    const target = cue.side === 'left' ? left : right;
    target.appendChild(line);

    requestAnimationFrame(() => {
      line.classList.add('is-visible');
    });
  }

  function updateTimedText() {
    const currentTime = audio.currentTime;

    cues.forEach(cue => {
      if (!cue.shown && currentTime >= cue.start) {
        cue.shown = true;
        addCue(cue);
      }
    });
  }

  audio.addEventListener('timeupdate', updateTimedText);
  audio.addEventListener('play', updateTimedText);

  audio.addEventListener('seeked', () => {
    resetTimedText();
    updateTimedText();
  });

  audio.addEventListener('ended', () => {
   left.classList.add('has-ended');
   right.classList.add('has-ended');
  });
}
