/* ==========================================================================
   BLOOM IRIS AGENCY — PUBLIC JS
   Self-contained, dependency-free. Hero carousel, marquee, nav, reveal,
   lightbox, filters.
   ========================================================================== */
(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {
    initHeader();
    initMobileNav();
    initHeroCarousel();
    initReveal();
    initCounters();
    initLightbox();
    initFilters();
    initNewsletter();
  });

  /* ----------------------------------------------------------------------
   * STICKY HEADER
   * ------------------------------------------------------------------- */
  function initHeader() {
    var header = document.querySelector('.site-header');
    if (!header) return;
    var onScroll = function () {
      header.classList.toggle('scrolled', window.scrollY > 40);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
  }

  /* ----------------------------------------------------------------------
   * MOBILE NAV DRAWER
   * ------------------------------------------------------------------- */
  function initMobileNav() {
    var toggle = document.querySelector('.nav-toggle');
    var drawer = document.querySelector('.nav-drawer');
    var close  = document.querySelector('.nav-drawer-close');
    if (!toggle || !drawer) return;

    var open  = function () { drawer.classList.add('open'); document.body.style.overflow = 'hidden'; };
    var shut  = function () { drawer.classList.remove('open'); document.body.style.overflow = ''; };

    toggle.addEventListener('click', open);
    if (close) close.addEventListener('click', shut);
    drawer.querySelectorAll('a').forEach(function (a) { a.addEventListener('click', shut); });
  }

  /* ----------------------------------------------------------------------
   * HERO CAROUSEL — mixed media (image / video / youtube)
   * A lightweight custom slider so video slides can control their own
   * timing and YouTube iframes are managed cleanly.
   * ------------------------------------------------------------------- */
  function initHeroCarousel() {
    var root = document.querySelector('[data-hero]');
    if (!root) return;

    var slides = Array.prototype.slice.call(root.querySelectorAll('.hero-slide'));
    if (slides.length === 0) return;

    var dots   = Array.prototype.slice.call(document.querySelectorAll('.hero-pagination .dot'));
    var prevBt = document.querySelector('[data-hero-prev]');
    var nextBt = document.querySelector('[data-hero-next]');
    var bar    = document.querySelector('.hero-progress span');

    var index   = 0;
    var timer   = null;
    var DEFAULT = 7000;     // images / youtube
    var raf     = null;

    function slideDuration(slide) {
      var v = slide.querySelector('video');
      if (v && v.duration && isFinite(v.duration)) {
        return Math.max(5000, v.duration * 1000);
      }
      return DEFAULT;
    }

    function show(next) {
      slides[index].classList.remove('is-active');
      if (dots[index]) dots[index].classList.remove('active');

      // pause any video on the outgoing slide
      var oldVid = slides[index].querySelector('video');
      if (oldVid) { try { oldVid.pause(); } catch (e) {} }

      index = (next + slides.length) % slides.length;

      slides[index].classList.add('is-active');
      if (dots[index]) dots[index].classList.add('active');

      // (re)start any video on the incoming slide
      var newVid = slides[index].querySelector('video');
      if (newVid) { newVid.currentTime = 0; var p = newVid.play(); if (p && p.catch) p.catch(function(){}); }

      restart();
    }

    function next() { show(index + 1); }
    function prev() { show(index - 1); }

    function restart() {
      clearTimeout(timer);
      animateBar(slideDuration(slides[index]));
      timer = setTimeout(next, slideDuration(slides[index]));
    }

    function animateBar(duration) {
      if (!bar) return;
      cancelAnimationFrame(raf);
      var start = performance.now();
      bar.style.width = '0%';
      (function step(now) {
        var pct = Math.min(1, (now - start) / duration);
        bar.style.width = (pct * 100) + '%';
        if (pct < 1) raf = requestAnimationFrame(step);
      })(start);
    }

    // wire controls
    if (nextBt) nextBt.addEventListener('click', next);
    if (prevBt) prevBt.addEventListener('click', prev);
    dots.forEach(function (d, i) { d.addEventListener('click', function () { show(i); }); });

    // pause on tab blur, resume on focus
    document.addEventListener('visibilitychange', function () {
      if (document.hidden) { clearTimeout(timer); }
      else { restart(); }
    });

    // keyboard arrows
    document.addEventListener('keydown', function (e) {
      if (e.key === 'ArrowRight') next();
      if (e.key === 'ArrowLeft') prev();
    });

    // touch swipe
    var startX = 0;
    root.addEventListener('touchstart', function (e) { startX = e.touches[0].clientX; }, { passive: true });
    root.addEventListener('touchend', function (e) {
      var dx = e.changedTouches[0].clientX - startX;
      if (Math.abs(dx) > 60) { dx < 0 ? next() : prev(); }
    }, { passive: true });

    // boot
    slides[0].classList.add('is-active');
    if (dots[0]) dots[0].classList.add('active');
    var firstVid = slides[0].querySelector('video');
    if (firstVid) { var fp = firstVid.play(); if (fp && fp.catch) fp.catch(function(){}); }
    restart();
  }

  /* ----------------------------------------------------------------------
   * SCROLL REVEAL (AOS-lite)
   * ------------------------------------------------------------------- */
  function initReveal() {
    var items = document.querySelectorAll('[data-reveal]');
    if (!items.length) return;

    if (!('IntersectionObserver' in window)) {
      items.forEach(function (el) { el.classList.add('in'); });
      return;
    }
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -60px 0px' });
    items.forEach(function (el) { io.observe(el); });
  }

  /* ----------------------------------------------------------------------
   * STAT COUNTERS
   * ------------------------------------------------------------------- */
  function initCounters() {
    var nums = document.querySelectorAll('[data-count]');
    if (!nums.length) return;

    var run = function (el) {
      var target = parseInt(el.getAttribute('data-count'), 10) || 0;
      var dur = 1600, start = performance.now();
      (function tick(now) {
        var p = Math.min(1, (now - start) / dur);
        var eased = 1 - Math.pow(1 - p, 3);
        el.firstChild.textContent = Math.floor(eased * target);
        if (p < 1) requestAnimationFrame(tick);
        else el.firstChild.textContent = target;
      })(start);
    };

    if (!('IntersectionObserver' in window)) { nums.forEach(run); return; }
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) { run(entry.target); io.unobserve(entry.target); }
      });
    }, { threshold: 0.5 });
    nums.forEach(function (el) { io.observe(el); });
  }

  /* ----------------------------------------------------------------------
   * LIGHTBOX (gallery viewer)
   * ------------------------------------------------------------------- */
  function initLightbox() {
    var triggers = document.querySelectorAll('[data-lightbox]');
    if (!triggers.length) return;

    var box = document.querySelector('.lightbox');
    if (!box) {
      box = document.createElement('div');
      box.className = 'lightbox';
      box.innerHTML = '<button class="lightbox-close" aria-label="Close">' +
        '<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
        'stroke-width="2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg></button>' +
        '<img alt="">';
      document.body.appendChild(box);
    }
    var img = box.querySelector('img');
    var closeBtn = box.querySelector('.lightbox-close');

    triggers.forEach(function (t) {
      t.addEventListener('click', function (e) {
        e.preventDefault();
        var src = t.getAttribute('data-lightbox') || t.getAttribute('href');
        img.src = src;
        box.classList.add('open');
        document.body.style.overflow = 'hidden';
      });
    });
    var shut = function () { box.classList.remove('open'); document.body.style.overflow = ''; };
    closeBtn.addEventListener('click', shut);
    box.addEventListener('click', function (e) { if (e.target === box) shut(); });
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape') shut(); });
  }

  /* ----------------------------------------------------------------------
   * CLIENT-SIDE FILTER (portfolio / talent grids)
   * ------------------------------------------------------------------- */
  function initFilters() {
    var bars = document.querySelectorAll('[data-filter-bar]');
    bars.forEach(function (bar) {
      var targetSel = bar.getAttribute('data-filter-bar');
      var grid = document.querySelector(targetSel);
      if (!grid) return;
      var items = Array.prototype.slice.call(grid.children);

      bar.querySelectorAll('.filter-chip').forEach(function (chip) {
        chip.addEventListener('click', function () {
          bar.querySelectorAll('.filter-chip').forEach(function (c) { c.classList.remove('active'); });
          chip.classList.add('active');
          var cat = chip.getAttribute('data-filter');
          items.forEach(function (item) {
            var show = (cat === 'all' || item.getAttribute('data-category') === cat);
            item.style.display = show ? '' : 'none';
          });
        });
      });
    });
  }

  /* ----------------------------------------------------------------------
   * NEWSLETTER — async submit
   * ------------------------------------------------------------------- */
  function initNewsletter() {
    var form = document.querySelector('[data-newsletter]');
    if (!form) return;
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var input = form.querySelector('input[type="email"]');
      var btn = form.querySelector('button');
      if (!input || !input.value) return;
      btn.disabled = true;

      fetch(form.getAttribute('action'), {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: new FormData(form)
      })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        form.innerHTML = '<p style="color:#fff;font-size:.92rem;">' +
          (res.message || 'Thank you for subscribing!') + '</p>';
      })
      .catch(function () {
        btn.disabled = false;
        alert('Something went wrong. Please try again.');
      });
    });
  }
})();