'use strict';

// navbar toggle
const header = document.querySelector("[data-header]");
const navToggleBtn = document.querySelector("[data-nav-toggle-btn]");

navToggleBtn.addEventListener("click", function () {
  header.classList.toggle("nav-active");
  this.classList.toggle("active");
});

// Close navbar when clicking outside on mobile
document.addEventListener('click', (event) => {
  if (window.innerWidth < 800 &&
    !event.target.closest('[data-nav-toggle-btn]') &&
    !event.target.closest('[data-navbar]')) {
    header.classList.remove("nav-active");
    navToggleBtn.classList.remove("active");
  }
});

// toggle the navbar when click any navbar link

const navbarLinks = document.querySelectorAll("[data-nav-link]");

for (let i = 0; i < navbarLinks.length; i++) {
  navbarLinks[i].addEventListener("click", function () {
    header.classList.toggle("nav-active");
    navToggleBtn.classList.toggle("active");
  });
}


//-------- PORTFOLIO FILTER ----------#

document.addEventListener('DOMContentLoaded', () => {
  const filterButtons = document.querySelectorAll('.filter-button-group button');
  const portfolioItems = document.querySelectorAll('.portfolio-item');
  const workContainer = document.querySelector('.Work-container');

  // Store original positions
  const originalPositions = new Map();
  portfolioItems.forEach(item => {
    const position = {
      topClass: item.classList.contains('portfolio-item-top') ? 'portfolio-item-top' : 'portfolio-item-bottom',
      sideClass: item.classList.contains('portfolio-item-left') ? 'portfolio-item-left' : 'portfolio-item-right',
    };
    originalPositions.set(item, position);
  });

  // Filter cards function with smooth animations and repositioning
  function filterCards(category) {
    // Reset all items to hidden
    portfolioItems.forEach(item => {
      item.classList.add('hidden');

      // Restore original position classes
      const original = originalPositions.get(item);
      item.classList.remove('moving', 'portfolio-item-top', 'portfolio-item-bottom', 'portfolio-item-left', 'portfolio-item-right');
      item.classList.add(original.topClass, original.sideClass);
    });

    // Show matching items with delay for animation
    setTimeout(() => {
      const visibleItems = [];

      portfolioItems.forEach(item => {
        const shouldShow = category === '*' ||
          item.classList.contains(category);

        if (shouldShow) {
          visibleItems.push(item);
        }
      });

      if (category === '*') {
        // Show all items in original positions
        visibleItems.forEach(item => {
          item.classList.remove('hidden');
        });

        // Adjust container height for all items
        if (window.matchMedia("(min-width: 800px)").matches) {
          workContainer.style.height = '1000px';
        } else {
          workContainer.style.height = 'auto';
        }
      } else {
        // Position visible items in the top row
        visibleItems.forEach((item, index) => {
          // Add moving class for transition
          item.classList.add('moving');

          // Remove original position classes
          item.classList.remove('portfolio-item-top', 'portfolio-item-bottom', 'portfolio-item-left', 'portfolio-item-right');

          // Position in top row
          item.classList.add('portfolio-item-top');

          // Position left/right based on index
          if (index % 2 === 0) {
            item.classList.add('portfolio-item-left');
          } else {
            item.classList.add('portfolio-item-right');
          }

          // Remove hidden class after positioning
          setTimeout(() => {
            item.classList.remove('hidden');
          }, 100);
        });

        // Adjust container height based on number of rows needed
        const rowsNeeded = Math.ceil(visibleItems.length / 2);
        workContainer.style.height = `${rowsNeeded * 450}px`;
      }
    }, 50);
  }

  // Click handler for filter buttons
  function handleFilterClick(e) {
    const button = e.target;

    // Update active button
    filterButtons.forEach(btn => btn.classList.remove('active'));
    button.classList.add('active');

    // Get filter category
    const category = button.dataset.filter;

    // Filter cards
    filterCards(category);
  }

  // Add event listeners to buttons
  filterButtons.forEach(button => {
    button.addEventListener('click', handleFilterClick);
  });

  // Initialize with all items shown
  filterCards('*');
});

// #---------- CONTACT SELECT ----------#

const formGroups = document.querySelectorAll('.form-group');

formGroups.forEach(group => {
  const niceSelect = group.querySelector('.nice-select');
  const list = group.querySelector('.list');
  const ion = niceSelect.querySelector('.ion-icon');
  const current = niceSelect.querySelector('.current');
  const options = group.querySelectorAll('.option');

  niceSelect.addEventListener('click', () => {
    list.style.opacity = list.style.opacity === "1" ? "0" : "1";
    list.style.visibility = list.style.visibility === "visible" ? "hidden" : "visible";
    list.style.top = list.style.top === "70px" ? "0px" : "70px";
    ion.style.rotate = ion.style.rotate === "180deg" ? "0deg" : "180deg";
  });

  options.forEach(option => {
    option.addEventListener("click", () => {
      const selectedValue = option.getAttribute("data-value");
      current.textContent = option.textContent;
      list.style.display = "block";
    });
  });

});

// Services Hidden Field Selector

const options = document.querySelectorAll('.option');
const current = document.querySelector('.current');
const hiddenInput = document.getElementById('selected-service');

options.forEach(option => {
  option.addEventListener("click", () => {
    const value = option.getAttribute("data-value");
    current.textContent = option.textContent;
    hiddenInput.value = value; // This is the key line!
  });
});


// #---------- ANIMTIONS ----------#

// Intersection Observer for Scroll Animations
const animateOnScroll = () => {
  const elements = document.querySelectorAll('[data-animate]');

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('animate');
      }
    });
  }, {
    rootMargin: '0px',
    threshold: 0.2
  });

  elements.forEach(element => observer.observe(element));
}

// Initialize animation observer
document.addEventListener('DOMContentLoaded', animateOnScroll);

// Optional: Add smooth scroll behavior
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    document.querySelector(this.getAttribute('href')).scrollIntoView({
      behavior: 'smooth'
    });
  });
});

// #---------- BACK TO TOP & HEADER ----------#


const backTopBtn = document.querySelector("[data-back-to-top]");

window.addEventListener("scroll", function () {
  if (this.window.scrollY >= 100) {
    header.classList.add("active");
    backTopBtn.classList.add("active");
  } else {
    header.classList.remove("active");
    backTopBtn.classList.remove("active");
  }
});

