const siteNav = document.querySelector('.site-nav');
const navToggle = document.querySelector('.nav-toggle');

const setNavState = (open) => {
  if (!siteNav || !navToggle) return;
  siteNav.classList.toggle('open', open);
  navToggle.setAttribute('aria-expanded', String(open));
  document.body.classList.toggle('nav-open', open);
};

if (siteNav) {
  let navTicking = false;
  const syncNavState = () => {
    siteNav.classList.toggle('scrolled', window.scrollY > 10);
    navTicking = false;
  };
  const onScroll = () => {
    if (!navTicking) {
      navTicking = true;
      requestAnimationFrame(syncNavState);
    }
  };
  window.addEventListener('scroll', onScroll, { passive: true });
  syncNavState();
}

if (siteNav && navToggle) {
  navToggle.addEventListener('click', () => {
    const expanded = navToggle.getAttribute('aria-expanded') === 'true';
    setNavState(!expanded);
  });
}

const dropdowns = document.querySelectorAll('.nav-dropdown');
const closeDropdown = (dropdown) => {
  const toggle = dropdown.querySelector('.nav-dropdown-toggle');
  dropdown.dataset.open = 'false';
  if (toggle) toggle.setAttribute('aria-expanded', 'false');
};

const closeNavMenu = () => {
  setNavState(false);
  dropdowns.forEach((dropdown) => closeDropdown(dropdown));
};

dropdowns.forEach((dropdown) => {
  const toggle = dropdown.querySelector('.nav-dropdown-toggle');
  if (!toggle) return;
  toggle.addEventListener('click', (event) => {
    event.preventDefault();
    const isOpen = dropdown.dataset.open === 'true';
    dropdowns.forEach((item) => {
      if (item !== dropdown) closeDropdown(item);
    });
    dropdown.dataset.open = String(!isOpen);
    toggle.setAttribute('aria-expanded', String(!isOpen));
  });
});

document.addEventListener('click', (event) => {
  dropdowns.forEach((dropdown) => {
    if (!dropdown.contains(event.target)) closeDropdown(dropdown);
  });
});

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') {
    dropdowns.forEach((dropdown) => closeDropdown(dropdown));
    closeNavMenu();
  }
});

document.querySelectorAll('.nav-menu a').forEach((link) => {
  link.addEventListener('click', closeNavMenu);
});

document.addEventListener('click', (event) => {
  if (!siteNav || !siteNav.classList.contains('open')) return;
  if (!siteNav.contains(event.target)) closeNavMenu();
});

// Highlight current nav link based on body data attribute
const activePage = document.body.dataset.page;
const navItems = document.querySelectorAll('.site-nav [data-page]');
navItems.forEach((item) => {
  if (activePage && item.dataset.page === activePage) {
    item.setAttribute('aria-current', 'page');
  } else {
    item.removeAttribute('aria-current');
  }
});

const toolPages = [
  'google-map-scraper',
  'email-finder',
  'email-sender',
  'email-verifier',
  'social-link-extractors',
  'yellow-pages-scraper',
  'yelp-scraper',
];
if (activePage && toolPages.includes(activePage)) {
  const toolsToggle = document.querySelector('.nav-dropdown-toggle[data-page="tools"]');
  if (toolsToggle) toolsToggle.setAttribute('aria-current', 'page');
}

// Smooth scroll helpers for CTA buttons
const scrollButtons = document.querySelectorAll('[data-scroll]');
scrollButtons.forEach((btn) => {
  btn.addEventListener('click', () => {
    const target = document.querySelector(btn.dataset.scroll || '');
    if (target) target.scrollIntoView({ behavior: 'smooth' });
  });
});

// Tabs
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanels = document.querySelectorAll('.tab-panel');

tabButtons.forEach((button) => {
  button.addEventListener('click', () => {
    const tab = button.dataset.tab;
    tabButtons.forEach((btn) => {
      btn.classList.toggle('active', btn === button);
      btn.setAttribute('aria-selected', btn === button ? 'true' : 'false');
    });
    tabPanels.forEach((panel) => {
      panel.classList.toggle('active', panel.id === tab);
    });
  });
});

// FAQ accordion
const faqItems = document.querySelectorAll('.faq-item');
faqItems.forEach((item) => {
  item.addEventListener('click', () => {
    const expanded = item.getAttribute('aria-expanded') === 'true';
    item.setAttribute('aria-expanded', String(!expanded));
  });
});

const API_BASE = 'api/index.php';
const endpoints = {
  signup: `${API_BASE}?action=signup`,
  contact: `${API_BASE}?action=contact`,
  signin: `${API_BASE}?action=signin`,
};

const updateStatus = (form, message, type = '') => {
  const status = form.querySelector('[data-status]');
  if (!status) return;
  status.textContent = message;
  status.classList.remove('error', 'success');
  if (type) status.classList.add(type);
};

const forms = document.querySelectorAll('form[data-form]');
forms.forEach((form) => {
  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    const type = form.dataset.form;
    const endpoint = endpoints[type];
    if (!endpoint) return;
    const payload = Object.fromEntries(new FormData(form).entries());
    updateStatus(form, 'Sending...', '');
    try {
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error('Request failed');
      const data = await response.json();
      updateStatus(form, data?.message || 'Thanks! We will be in touch shortly.', 'success');
      if (type === 'signin' && data?.redirect) {
        setTimeout(() => {
          window.location.href = data.redirect;
        }, 600);
      }
      if (type !== 'signin') {
        form.reset();
      }
    } catch (error) {
      updateStatus(form, 'Something went wrong. Try again or email hello@leadsniper.com.', 'error');
    }
  });
});

// Footer year
const footerYearTargets = document.querySelectorAll('[data-year], #year');
if (footerYearTargets.length) {
  const yearValue = new Date().getFullYear();
  footerYearTargets.forEach((node) => {
    node.textContent = yearValue;
  });
}

// Mascot eye tracking on sign-in
const trackedEyes = document.querySelectorAll('[data-eye]');
if (trackedEyes.length) {
  let frame;
  let pointerX = window.innerWidth / 2;
  let pointerY = window.innerHeight / 2;

  const updateEyes = () => {
    trackedEyes.forEach((eye) => {
      const rect = eye.getBoundingClientRect();
      const centerX = rect.left + rect.width / 2;
      const centerY = rect.top + rect.height / 2;
      const dx = pointerX - centerX;
      const dy = pointerY - centerY;
      const angle = Math.atan2(dy, dx);
      const maxOffset = 10;
      const distance = Math.min(maxOffset, Math.hypot(dx, dy) / 15);
      const offsetX = Math.cos(angle) * distance;
      const offsetY = Math.sin(angle) * distance;
      eye.style.setProperty('--eye-translate-x', `${offsetX}px`);
      eye.style.setProperty('--eye-translate-y', `${offsetY}px`);
    });
    frame = null;
  };

  const handlePointer = (event) => {
    pointerX = event.clientX;
    pointerY = event.clientY;
    if (!frame) frame = requestAnimationFrame(updateEyes);
  };

  const resetEyes = () => {
    trackedEyes.forEach((eye) => {
      eye.style.setProperty('--eye-translate-x', '0px');
      eye.style.setProperty('--eye-translate-y', '0px');
    });
  };

  window.addEventListener('pointermove', handlePointer, { passive: true });
  window.addEventListener('pointerleave', resetEyes);
}

// Password visibility toggles
const passwordToggles = document.querySelectorAll('[data-password-toggle]');
passwordToggles.forEach((button) => {
  const wrapper = button.closest('.password-input');
  const input = wrapper ? wrapper.querySelector('[data-password-input]') : null;
  if (!input) return;

  const updateState = (visible) => {
    button.setAttribute('data-visible', visible ? 'true' : 'false');
    button.setAttribute('aria-pressed', visible ? 'true' : 'false');
    button.setAttribute('aria-label', visible ? 'Hide password' : 'Show password');
    input.type = visible ? 'text' : 'password';
  };

  button.addEventListener('click', () => {
    const isVisible = button.getAttribute('data-visible') === 'true';
    updateState(!isVisible);
  });

  updateState(false);
});
