/* ==========================================================================
   Deutsche Bank Holdings Delaware - Public Landing Pages
   Shared JavaScript - Navigation, Animations, Tabs, FAQ, Interactions
   ========================================================================== */

(function () {
  'use strict';

  function ready(fn) {
    if (document.readyState !== 'loading') { fn(); }
    else { document.addEventListener('DOMContentLoaded', fn); }
  }

  ready(function () {
    initMobileNav();
    initHeaderScroll();
    initScrollAnimations();
    initSmoothScroll();
    initFAQ();
    initTabs();
    initAnnouncement();
    initActiveNavLinks();
  });

  // ── Mobile Navigation (expandable categories) ──────────────────────────
  function initMobileNav() {
    var toggle = document.querySelector('.db-nav-toggle');
    var menu = document.querySelector('.db-mobile-menu');
    var body = document.body;

    if (!toggle || !menu) return;

    toggle.replaceWith(toggle.cloneNode(true));
    toggle = document.querySelector('.db-nav-toggle');

    toggle.addEventListener('click', function () {
      var isOpen = menu.classList.contains('active');
      if (isOpen) {
        menu.classList.remove('active');
        toggle.classList.remove('active');
        body.style.overflow = '';
        toggle.setAttribute('aria-expanded', 'false');
      } else {
        menu.classList.add('active');
        toggle.classList.add('active');
        body.style.overflow = 'hidden';
        toggle.setAttribute('aria-expanded', 'true');
      }
    });

    // Expandable sub-menus in mobile nav
    var sectionTitles = menu.querySelectorAll('.db-mobile-nav-title');
    sectionTitles.forEach(function (title) {
      title.addEventListener('click', function () {
        var links = this.nextElementSibling;
        var isOpen = links && links.classList.contains('open');
        if (isOpen) {
          links.classList.remove('open');
          this.classList.remove('open');
        } else {
          links.classList.add('open');
          this.classList.add('open');
        }
      });
    });

    // Close menu when clicking a leaf link
    var menuLinks = menu.querySelectorAll('a:not(.db-mobile-nav-title)');
    menuLinks.forEach(function (link) {
      link.addEventListener('click', function () {
        menu.classList.remove('active');
        toggle.classList.remove('active');
        body.style.overflow = '';
        toggle.setAttribute('aria-expanded', 'false');
      });
    });

    // Escape key
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && menu.classList.contains('active')) {
        menu.classList.remove('active');
        toggle.classList.remove('active');
        body.style.overflow = '';
        toggle.setAttribute('aria-expanded', 'false');
        toggle.focus();
      }
    });
  }

  // ── Header Scroll Effect ────────────────────────────────────────────────
  function initHeaderScroll() {
    var header = document.querySelector('.db-header');
    if (!header) return;
    var ticking = false;
    function update() {
      var scrollY = window.pageYOffset || document.documentElement.scrollTop;
      if (scrollY > 10) { header.classList.add('scrolled'); }
      else { header.classList.remove('scrolled'); }
      ticking = false;
    }
    window.addEventListener('scroll', function () {
      if (!ticking) { requestAnimationFrame(update); ticking = true; }
    }, { passive: true });
    update();
  }

  // ── Scroll Animations ───────────────────────────────────────────────────
  function initScrollAnimations() {
    var animElements = document.querySelectorAll('.animate');
    if (!animElements.length) return;

    var prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (prefersReducedMotion) {
      animElements.forEach(function (el) {
        el.classList.add('visible');
        el.style.opacity = '1';
        el.style.transform = 'none';
      });
      return;
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible');
          observer.unobserve(entry.target);
        }
      });
    }, { root: null, rootMargin: '0px 0px -40px 0px', threshold: 0.1 });

    animElements.forEach(function (el) { observer.observe(el); });
  }

  // ── Smooth Scroll ──────────────────────────────────────────────────────
  function initSmoothScroll() {
    document.addEventListener('click', function (e) {
      var link = e.target.closest('a[href^="#"]');
      if (!link) return;
      var targetId = link.getAttribute('href');
      if (targetId === '#') return;
      var target = document.querySelector(targetId);
      if (!target) return;
      e.preventDefault();
      var header = document.querySelector('.db-header');
      var offset = header ? header.offsetHeight + 24 : 80;
      var targetPosition = target.getBoundingClientRect().top + window.pageYOffset - offset;
      window.scrollTo({ top: targetPosition, behavior: 'smooth' });
      if (history.pushState) { history.pushState(null, null, targetId); }
    });
  }

  // ── FAQ Accordion ──────────────────────────────────────────────────────
  function initFAQ() {
    var faqItems = document.querySelectorAll('.db-faq-question');
    if (!faqItems.length) return;
    faqItems.forEach(function (question) {
      question.addEventListener('click', function () {
        var item = this.parentElement;
        var isActive = item.classList.contains('active');
        var allItems = document.querySelectorAll('.db-faq-item');
        allItems.forEach(function (f) { f.classList.remove('active'); });
        if (!isActive) { item.classList.add('active'); }
      });
    });
  }

  // ── Tab Switching ──────────────────────────────────────────────────────
  function initTabs() {
    var tabContainers = document.querySelectorAll('[data-tabs]');
    tabContainers.forEach(function (container) {
      var tabs = container.querySelectorAll('.db-tab');
      var panels = container.querySelectorAll('.db-tab-panel');
      if (!tabs.length || !panels.length) return;

      tabs.forEach(function (tab) {
        tab.addEventListener('click', function () {
          var target = this.getAttribute('data-tab');
          tabs.forEach(function (t) { t.classList.remove('active'); });
          this.classList.add('active');
          panels.forEach(function (p) { p.classList.remove('active'); });
          var targetPanel = container.querySelector('[data-panel="' + target + '"]');
          if (targetPanel) { targetPanel.classList.add('active'); }
        });
      });
    });
  }

  // ── Announcement Bar Dismiss ───────────────────────────────────────────
  function initAnnouncement() {
    var closeBtn = document.querySelector('.db-announcement-close');
    if (!closeBtn) return;
    closeBtn.addEventListener('click', function () {
      var bar = this.closest('.db-announcement');
      if (bar) {
        bar.style.display = 'none';
        // Adjust trust bar margin if present
        var trustBar = document.querySelector('.db-trust-bar');
        if (trustBar) { trustBar.style.marginTop = '0'; }
      }
    });
  }

  // ── Active Nav Link Detection ──────────────────────────────────────────
  function initActiveNavLinks() {
    var currentPath = window.location.pathname.replace(/\/$/, '').split('/').pop() || 'index.html';
    var navLinks = document.querySelectorAll('.db-nav-link:not(.db-btn), .db-mobile-menu .db-nav-link:not(.db-btn)');
    navLinks.forEach(function (link) {
      var href = link.getAttribute('href');
      if (!href) return;
      if (href === currentPath || href === './' + currentPath) {
        link.classList.add('active');
      } else if (currentPath === '' && (href === 'index.html' || href === './index.html' || href === './')) {
        link.classList.add('active');
      }
    });
  }

})();
