document.addEventListener('DOMContentLoaded', () => {
  loadNavbar();
  initSlideshow();
  initTabs();
  initServiceTimedText();
  initChatbotServiceForm();
  initServiceRequestForm();
  initHomeSupportChatbot();
  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');
  });
}

function initHomeSupportChatbot() {
  const path = window.location.pathname;
  const isHomePage =
    document.body.classList.contains('home-page') ||
    path === '/' ||
    path === '/index.html';

  if (!isHomePage) {
    return;
  }

  initSupportChatbot();
}

function initSupportChatbot() {
  if (document.querySelector('.support-chatbot')) {
    return;
  }

  const supportFlows = {
    'Paper Jam': {
      image: '/images/kyocerapaperjam-bot.png',
      steps: [
        'Switch the machine off, wait 10 seconds, then open the covers and remove any visible paper slowly in the direction it feeds.',
        'Check the paper tray. Remove damaged or curled paper, fan the stack, and make sure the guides sit snugly against the paper.',
        'Close all covers firmly, switch the machine back on, and check whether the jam message clears from the display.'
      ]
    },
    'Print Quality': {
      image: '/images/kyoceraprintquality-bot.png',
      steps: [
        'Print a test page and check whether the issue is lines, faded print, spots, smudges, or missing colours.',
        'Check toner levels and confirm the correct paper type is selected on the machine and in the print driver.',
        'Run the machine cleaning or calibration option from the device menu if available, then print another test page.'
      ]
    },
    'Not Printing': {
      image: '/images/kyoceraprinteroffline-bot.png',
      steps: [
        'Confirm the printer is powered on, shows Ready, and has no paper, toner, or cover warnings on the screen.',
        'Check whether the printer is connected by network, Wi-Fi, or USB, and confirm your computer is on the same network if needed.',
        'Open the print queue, clear stuck jobs, then send a fresh test print from a simple document.'
      ]
    },
    'Scanning Issue': {
      image: '/images/kyocerascannerdisconnect-bot.png',
      steps: [
        'Confirm whether scanning fails from the machine panel, the computer software, or both.',
        'Check that the destination email, folder, or computer is reachable and that the network connection is active.',
        'Restart the machine and try one simple scan to email or scan to folder test.'
      ]
    },
    'Error Code': {
      image: '/images/kyoceraerrorcode-bot.png',
      steps: [
        'Write down the exact error code and message shown on the machine display.',
        'Restart the machine once and check whether the same error code returns.',
        'If the code returns, avoid repeated restarts and prepare the model, serial number, and error code for the service desk.'
      ]
    },
    'Network Issue': {
      image: '/images/kyoceranetworkissues-bot.png',
      steps: [
        'Check whether other users can print or scan to the same device.',
        'Confirm the network cable is connected or Wi-Fi is active, then check whether the device has an IP address.',
        'Restart the printer and test printing again after the device reconnects to the network.'
      ]
    },
    Other: {
      image: '/images/servicerequest.png',
      steps: [
        'Briefly identify what is not working and whether the issue affects one person or multiple users.',
        'Check for any visible warning lights, error messages, unusual sounds, or recent changes.',
        'Gather the model number, serial number, and a short description before sending the request to the service desk.'
      ]
    }
  };

  let selectedIssue = '';
  let currentStep = 0;
  const conversation = [];

  const widget = document.createElement('section');
  widget.className = 'support-chatbot';
  widget.setAttribute('aria-label', 'IBS support chatbot');
  widget.innerHTML = `
    <button class="support-chatbot-toggle" type="button" aria-expanded="false" aria-controls="supportChatbotPanel">
      <span>DIGITAL ASSISTANT</span>
    </button>
    <div class="support-chatbot-panel" id="supportChatbotPanel" hidden>
      <div class="support-chatbot-header">
        <div>
          <strong>IBS Support Assistant</strong>
          <span>Three quick checks, then service desk</span>
        </div>
        <button class="support-chatbot-close" type="button" aria-label="Close support chat">x</button>
      </div>
      <div class="support-chatbot-messages" aria-live="polite"></div>
      <div class="support-chatbot-actions"></div>
    </div>
  `;

  document.body.appendChild(widget);

  const toggle = widget.querySelector('.support-chatbot-toggle');
  const panel = widget.querySelector('.support-chatbot-panel');
  const close = widget.querySelector('.support-chatbot-close');
  const messages = widget.querySelector('.support-chatbot-messages');
  const actions = widget.querySelector('.support-chatbot-actions');

  function setOpen(isOpen) {
    panel.hidden = !isOpen;
    toggle.setAttribute('aria-expanded', String(isOpen));

    if (isOpen && !messages.children.length) {
      startChat();
    }
  }

  function addMessage(type, text, image) {
    const message = document.createElement('div');
    message.className = `support-chatbot-message ${type}`;

    const bubble = document.createElement('div');
    bubble.className = 'support-chatbot-bubble';
    bubble.textContent = text;
    message.appendChild(bubble);

    if (image) {
      const img = document.createElement('img');
      img.src = image;
      img.alt = `${selectedIssue || 'Support'} reference image`;
      img.loading = 'lazy';
      message.appendChild(img);
    }

    messages.appendChild(message);
    messages.scrollTop = messages.scrollHeight;

    conversation.push({
      sender: type === 'bot' ? 'IBS Support Assistant' : 'Visitor',
      message: text
    });
  }

  function setActions(items) {
    actions.innerHTML = '';

    items.forEach(item => {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = item.primary ? 'support-chatbot-action primary' : 'support-chatbot-action';
      button.textContent = item.label;
      button.addEventListener('click', item.onClick);
      actions.appendChild(button);
    });
  }

  function startChat() {
    selectedIssue = '';
    currentStep = 0;
    conversation.length = 0;
    messages.innerHTML = '';
    addMessage('bot', 'Hi, I can guide you through three quick checks before sending a service request. What problem are you having?');
    showCategories();
  }

  function showCategories() {
    setActions(Object.keys(supportFlows).map(issue => ({
      label: issue,
      onClick: () => chooseIssue(issue)
    })));
  }

  function chooseIssue(issue) {
    selectedIssue = issue;
    currentStep = 0;
    addMessage('user', issue);
    addMessage('bot', `Let us try ${supportFlows[issue].steps.length} quick checks for ${issue}.`);
    showStep();
  }

  function showStep() {
    const flow = supportFlows[selectedIssue];
    const stepText = `Step ${currentStep + 1}: ${flow.steps[currentStep]}`;
    addMessage('bot', stepText, currentStep === 0 ? flow.image : '');

    setActions([
      {
        label: 'That fixed it',
        onClick: () => {
          addMessage('user', 'That fixed it');
          addMessage('bot', 'Great. I am glad this was resolved. You can reopen this assistant anytime if the issue comes back.');
          setActions([{ label: 'Start over', onClick: startChat }]);
        }
      },
      {
        label: currentStep < 2 ? 'Next check' : 'Request service',
        primary: true,
        onClick: () => {
          addMessage('user', currentStep < 2 ? 'Next check' : 'Request service');
          currentStep += 1;

          if (currentStep < 3) {
            showStep();
          } else {
            escalateToService();
          }
        }
      }
    ]);
  }

  function escalateToService() {
  addMessage('bot', 'This needs the service desk. I will take you to the request form and include a summary of these checks.', '/images/servicerequest.png');
  setActions([]);

  window.setTimeout(() => {
    openServiceRequest();
  }, 1800);
}

  function openServiceRequest() {
    const flow = supportFlows[selectedIssue] || supportFlows.Other;
    const summary = [
      `Chatbot issue category: ${selectedIssue || 'Other'}`,
      'Troubleshooting completed:',
      ...flow.steps.map((step, index) => `${index + 1}. ${step}`)
    ].join('\n');

    sessionStorage.setItem('ibsChatbotSummary', summary);
    sessionStorage.setItem('ibsChatbotIssue', selectedIssue || 'Other');
    sessionStorage.setItem('ibsChatbotTranscript', conversation.map(entry => `${entry.sender}: ${entry.message}`).join('\n'));
    window.location.href = '/Contact/?fromChatbot=1';
  }

  toggle.addEventListener('click', () => setOpen(panel.hidden));
  close.addEventListener('click', () => setOpen(false));
}

function initChatbotServiceForm() {
  const form = document.querySelector('.service-request-form');

  if (!form) {
    return;
  }

  const summary = sessionStorage.getItem('ibsChatbotSummary') || '';
  const issue = sessionStorage.getItem('ibsChatbotIssue') || '';
  const transcript = sessionStorage.getItem('ibsChatbotTranscript') || '';

  if (!summary) {
    return;
  }

  const summaryField = document.getElementById('chatbot-summary');
  const transcriptField = document.getElementById('chatbot-transcript');

  if (summaryField) {
    summaryField.value = summary;
  }

  if (transcriptField) {
    transcriptField.value = transcript;
  }

  const matchingProblem = form.querySelector(`input[name="problem_type"][value="${CSS.escape(issue)}"]`);
  const otherProblem = document.getElementById('problem_other');

  if (matchingProblem) {
    matchingProblem.checked = true;

    if (issue === 'Error Code' && otherProblem && otherProblem.value === '') {
      otherProblem.value = 'Escalated from chatbot troubleshooting. See troubleshooting summary below.';
    }
  } else {
    const otherRadio = form.querySelector('input[name="problem_type"][value="Other"]');

    if (otherRadio) {
      otherRadio.checked = true;
    }

    if (otherProblem) {
      otherProblem.value = issue || 'Escalated from chatbot troubleshooting. See troubleshooting summary below.';
    }
  }
}