document.addEventListener('DOMContentLoaded', function () {
  const tabs = document.querySelectorAll('.looking-tab');
  const panels = document.querySelectorAll('.looking-panel');

  if (tabs.length && panels.length) {
    tabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        const target = tab.getAttribute('data-tab');

        tabs.forEach(function (item) {
          item.classList.remove('active');
          item.setAttribute('aria-selected', 'false');
        });

        panels.forEach(function (panel) {
          panel.classList.remove('active');
        });

        tab.classList.add('active');
        tab.setAttribute('aria-selected', 'true');

        const activePanel = document.querySelector('[data-panel="' + target + '"]');
        if (activePanel) {
          activePanel.classList.add('active');
        }
      });
    });
  }

  const ambitiousTags = document.querySelectorAll('.ambitious-tag');

  if (ambitiousTags.length) {
    ambitiousTags.forEach(function (tag) {
      tag.addEventListener('click', function () {
        ambitiousTags.forEach(function (item) {
          item.classList.remove('active');
          item.setAttribute('aria-selected', 'false');
        });

        tag.classList.add('active');
        tag.setAttribute('aria-selected', 'true');
      });
    });
  }

  const processToggleBtns = document.querySelectorAll('.process-timeline-toggle-btn');
  const processPanels = document.querySelectorAll('.process-timeline-panel');

  if (processToggleBtns.length && processPanels.length) {
    processToggleBtns.forEach(function (btn) {
      btn.addEventListener('click', function () {
        const target = btn.getAttribute('data-journey');

        processToggleBtns.forEach(function (item) {
          item.classList.remove('is-active');
          item.setAttribute('aria-selected', 'false');
        });

        processPanels.forEach(function (panel) {
          panel.classList.remove('is-active');
          panel.setAttribute('hidden', '');
        });

        btn.classList.add('is-active');
        btn.setAttribute('aria-selected', 'true');

        const activePanel = document.querySelector('[data-journey-panel="' + target + '"]');
        if (activePanel) {
          activePanel.classList.add('is-active');
          activePanel.removeAttribute('hidden');
        }
      });
    });
  }

  if (typeof Fancybox !== 'undefined') {
    Fancybox.bind('[data-fancybox="portfolio-home"]', {
      Carousel: {
        infinite: true,
      },
    });
  }

  const industriesServeTabs = document.querySelectorAll('.industries-serve-tab');
  const industriesServePanels = document.querySelectorAll('.industries-serve-panel');

  if (industriesServeTabs.length && industriesServePanels.length) {
    industriesServeTabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        const target = tab.getAttribute('data-industry');

        industriesServeTabs.forEach(function (item) {
          item.classList.remove('is-active');
          item.setAttribute('aria-selected', 'false');
        });

        industriesServePanels.forEach(function (panel) {
          panel.classList.remove('is-active');
          panel.setAttribute('hidden', '');
        });

        tab.classList.add('is-active');
        tab.setAttribute('aria-selected', 'true');

        const activePanel = document.querySelector('[data-industry-panel="' + target + '"]');
        if (activePanel) {
          activePanel.classList.add('is-active');
          activePanel.removeAttribute('hidden');
        }
      });
    });
  }

  const partnerLogosSlider = document.querySelector('.partner-logos-slider');

  if (partnerLogosSlider && typeof Swiper !== 'undefined') {
    new Swiper('.partner-logos-slider', {
      slidesPerView: 2,
      spaceBetween: 30,
      loop: true,
      speed: 600,
      autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
      breakpoints: {
        576: {
          slidesPerView: 3,
          spaceBetween: 40,
        },
        768: {
          slidesPerView: 4,
          spaceBetween: 50,
        },
        992: {
          slidesPerView: 5,
          spaceBetween: 60,
        },
        1200: {
          slidesPerView: 5,
          spaceBetween: 60,
        },
      },
    });
  }

  const platformLogosSlider = document.querySelector('.platform-logos-slider');

  if (platformLogosSlider && typeof Swiper !== 'undefined') {
    new Swiper('.platform-logos-slider', {
      slidesPerView: 2,
      spaceBetween: 24,
      loop: true,
      loopAdditionalSlides: 4,
      speed: 600,
      grabCursor: true,
      autoplay: {
        delay: 2500,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
      },
      breakpoints: {
        576: {
          slidesPerView: 3,
          spaceBetween: 32,
        },
        768: {
          slidesPerView: 4,
          spaceBetween: 40,
        },
        992: {
          slidesPerView: 5,
          spaceBetween: 48,
        },
        1200: {
          slidesPerView: 5,
          spaceBetween: 56,
        },
        1500: {
          slidesPerView: 7,
          spaceBetween: 60,
        },
      },
    });
  }

  const portfolioSliderEl = document.querySelector('.portfolio-slider');
  let portfolioSwiper;

  function getPortfolioGalleryItems() {
    if (!portfolioSliderEl) {
      return [];
    }

    try {
      const slides = JSON.parse(portfolioSliderEl.getAttribute('data-gallery') || '[]');

      return slides.map(function (slide) {
        return {
          src: slide.src,
          type: 'image',
          caption: slide.alt || '',
        };
      });
    } catch (error) {
      return [];
    }
  }

  function openPortfolioFancybox(triggerLink) {
    if (typeof Fancybox === 'undefined' || !triggerLink) {
      return;
    }

    const items = getPortfolioGalleryItems();
    if (!items.length) {
      return;
    }

    const href = triggerLink.getAttribute('href');
    const startIndex = items.findIndex(function (item) {
      return item.src === href;
    });

    Fancybox.show(items, {
      startIndex: startIndex >= 0 ? startIndex : 0,
      Carousel: {
        infinite: true,
      },
    });
  }

  if (portfolioSliderEl) {
    portfolioSliderEl.addEventListener('click', function (event) {
      const link = event.target.closest('.portfolio-lightbox');
      if (!link) {
        return;
      }

      if (portfolioSwiper && portfolioSwiper.allowClick === false) {
        event.preventDefault();
        return;
      }

      event.preventDefault();
      openPortfolioFancybox(link);
    });

    if (typeof Swiper !== 'undefined') {
      portfolioSwiper = new Swiper('.portfolio-slider', {
        effect: 'coverflow',
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: 3.5,
        loop: true,
        speed: 700,
        preventClicks: false,
        preventClicksPropagation: false,
        slideToClickedSlide: false,
        coverflowEffect: {
          rotate: 25,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true,
        },
        breakpoints: {
          320: {
            slidesPerView: 2,
          },
          640: {
            slidesPerView: 2.5,
          },
          768: {
            slidesPerView: 3.5,
          },
        },
      });
    }
  }

  const videoTestimonialsSlider = document.querySelector('.video-testimonials-slider');

  if (videoTestimonialsSlider && typeof Swiper !== 'undefined') {
    new Swiper('.video-testimonials-slider', {
      slidesPerView: 1.15,
      centeredSlides: true,
      spaceBetween: 16,
      loop: false,
      speed: 500,
      initialSlide: 1,
      watchSlidesProgress: true,
      grabCursor: true,
      noSwipingClass: 'swiper-no-swiping',
      navigation: {
        nextEl: '.video-testimonials-nav--next',
        prevEl: '.video-testimonials-nav--prev',
      },
      breakpoints: {
        768: {
          slidesPerView: 2.2,
          spaceBetween: 24,
        },
        1200: {
          slidesPerView: 3,
          centeredSlides: true,
          spaceBetween: 28,
        },
      },
    });
  }

  const videoTestimonialCards = document.querySelectorAll('.video-testimonial-card');

  function formatVideoTime(seconds) {
    if (!Number.isFinite(seconds)) {
      return '0:00';
    }

    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);

    return mins + ':' + String(secs).padStart(2, '0');
  }

  function pauseOtherVideos(activeVideo) {
    document.querySelectorAll('.video-testimonial-video').forEach(function (video) {
      if (video !== activeVideo && !video.paused) {
        video.pause();
        const otherCard = video.closest('.video-testimonial-card');
        if (otherCard) {
          otherCard.classList.remove('is-playing');
        }
      }
    });
  }

  function updateVideoUi(card, video) {
    const timeEl = card.querySelector('.video-testimonial-time');
    const progressEl = card.querySelector('.video-testimonial-progress span');
    const playBtn = card.querySelector('.video-testimonial-play');
    const duration = video.duration || 0;
    const progress = duration ? (video.currentTime / duration) * 100 : 0;

    if (timeEl) {
      timeEl.textContent = formatVideoTime(video.currentTime);
    }

    if (progressEl) {
      progressEl.style.width = progress + '%';
    }

    if (playBtn) {
      playBtn.setAttribute('aria-label', video.paused ? 'Play video' : 'Pause video');
    }

    card.classList.toggle('is-playing', !video.paused);
  }

  function toggleVideo(card) {
    const video = card.querySelector('.video-testimonial-video');

    if (!video) {
      return;
    }

    if (video.paused) {
      pauseOtherVideos(video);

      if (video.readyState === 0) {
        video.load();
      }

      video.play().then(function () {
        updateVideoUi(card, video);
      }).catch(function () {
        card.classList.remove('is-playing');
      });
    } else {
      video.pause();
      updateVideoUi(card, video);
    }
  }

  videoTestimonialCards.forEach(function (card) {
    const video = card.querySelector('.video-testimonial-video');
    const playBtn = card.querySelector('.video-testimonial-play');
    const muteBtn = card.querySelector('.video-testimonial-mute');

    if (!video) {
      return;
    }

    card.addEventListener('click', function (event) {
      if (event.target.closest('.video-testimonial-mute')) {
        return;
      }

      toggleVideo(card);
    });

    if (muteBtn) {
      muteBtn.addEventListener('click', function (event) {
        event.stopPropagation();
        video.muted = !video.muted;
        muteBtn.classList.toggle('is-muted', video.muted);
        muteBtn.setAttribute('aria-label', video.muted ? 'Unmute video' : 'Mute video');
      });
    }

    video.addEventListener('timeupdate', function () {
      updateVideoUi(card, video);
    });

    video.addEventListener('loadedmetadata', function () {
      updateVideoUi(card, video);
    });

    video.addEventListener('ended', function () {
      video.currentTime = 0;
      updateVideoUi(card, video);
    });

    video.addEventListener('pause', function () {
      updateVideoUi(card, video);
    });

    video.addEventListener('play', function () {
      updateVideoUi(card, video);
    });
  });

  const heroHome = document.querySelector('.hero-home');

  if (heroHome) {
    const heroTestimonial = heroHome.querySelector('.hero-testimonial');
    const heroBooksShowcase = heroHome.querySelector('.hero-books-showcase');
    const heroBookItems = heroBooksShowcase ? heroBooksShowcase.querySelectorAll('.hero-book-item') : [];
    const prevBtn = heroHome.querySelector('.hero-books-nav-prev');
    const nextBtn = heroHome.querySelector('.hero-books-nav-next');
    let activeBookIndex = 1;

    function updateHeroBook(index) {
      const total = heroBookItems.length;
      if (!total) {
        return;
      }

      activeBookIndex = ((index % total) + total) % total;
      const item = heroBookItems[activeBookIndex];

      heroBookItems.forEach(function (book, bookIndex) {
        book.classList.toggle('is-active', bookIndex === activeBookIndex);
      });

      if (heroTestimonial && item) {
        const avatar = heroTestimonial.querySelector('.hero-testimonial-avatar');
        const name = heroTestimonial.querySelector('.hero-testimonial-name');
        const role = heroTestimonial.querySelector('.hero-testimonial-role');
        const quote = heroTestimonial.querySelector('.hero-testimonial-quote');
        const bookCounter = document.querySelector('.platform-showcase-count-current');

        if (avatar) {
          avatar.src = item.dataset.authorImage || '';
          avatar.alt = item.dataset.authorName || '';
        }

        if (name) {
          name.textContent = item.dataset.authorName || '';
        }

        if (role) {
          role.textContent = item.dataset.authorRole || '';
        }

        if (quote) {
          quote.innerHTML = item.dataset.authorQuote || '';
        }

        if (bookCounter) {
          bookCounter.textContent = String(activeBookIndex + 1).padStart(2, '0');
        }

        heroTestimonial.classList.add('is-updating');
        window.setTimeout(function () {
          heroTestimonial.classList.remove('is-updating');
        }, 250);
      }

      if (window.matchMedia('(max-width: 991.98px)').matches) {
        item.scrollIntoView({
          behavior: 'smooth',
          inline: 'center',
          block: 'nearest',
        });
      }
    }

    if (prevBtn) {
      prevBtn.addEventListener('click', function () {
        updateHeroBook(activeBookIndex - 1);
      });
    }

    if (nextBtn) {
      nextBtn.addEventListener('click', function () {
        updateHeroBook(activeBookIndex + 1);
      });
    }

    heroBookItems.forEach(function (item, index) {
      item.addEventListener('click', function () {
        updateHeroBook(index);
      });
    });

    updateHeroBook(activeBookIndex);
  }

  const clientReviewsSlider = document.querySelector('.client-reviews-slider');

  if (clientReviewsSlider && typeof Swiper !== 'undefined') {
    new Swiper('.client-reviews-slider', {
      slidesPerView: 1,
      spaceBetween: 24,
      loop: false,
      speed: 500,
      grabCursor: true,
      slidesPerGroup: 1,
      pagination: {
        el: '.client-reviews-pagination',
        clickable: true,
      },
      breakpoints: {
        768: {
          slidesPerView: 2,
          spaceBetween: 30,
        },
        1200: {
          slidesPerView: 3,
          spaceBetween: 40,
        },
      },
    });
  }

  const quoteModalEl = document.getElementById('quoteModal');

  if (quoteModalEl && typeof bootstrap !== 'undefined') {
    const quoteModal = new bootstrap.Modal(quoteModalEl);
    const quoteServiceSelect = quoteModalEl.querySelector('#quote-modal-service');
    const pageService = document.body.getAttribute('data-current-service') || '';

    function openQuoteModal(serviceSlug) {
      if (quoteServiceSelect && serviceSlug) {
        const option = quoteServiceSelect.querySelector('option[value="' + serviceSlug + '"]');
        if (option) {
          quoteServiceSelect.value = serviceSlug;
        }
      }

      quoteModal.show();
    }

    const quoteTriggerSelectors = [
      '.quote-modal-trigger',
      '.service-prepare-btn',
      '.btn-journey',
      '.btn-panel',
      '.page-pricing-btn',
      '.hero-buttons .btn-primary',
      '.cta-banner-buttons .btn-primary:not(.btn-cta-outline)',
    ];

    document.querySelectorAll(quoteTriggerSelectors.join(',')).forEach(function (trigger) {
      trigger.addEventListener('click', function (event) {
        event.preventDefault();
        const service = trigger.getAttribute('data-service') || pageService;
        openQuoteModal(service);
      });
    });
  }
});
