(function(){
  const hero = document.querySelector('[data-hero]');
  if (!hero) return;

  const layerA = hero.querySelector('[data-hero-layer="a"]');
  const layerB = hero.querySelector('[data-hero-layer="b"]');
  const indicators = hero.querySelector('[data-hero-indicators]');

  // Prefer structured slides (image + text + ctas); fallback to images list
  let slides = [];
  const slidesAttr = hero.getAttribute('data-hero-slides');
  if (slidesAttr) {
    try { slides = JSON.parse(slidesAttr); } catch (e) { slides = []; }
  }
  // Compute base prefix from this script's src (works when hosted in a subdirectory)
  function getBasePrefix(){
    try {
      // find this script tag by filename
      const scripts = document.querySelectorAll('script[src]');
      for (const s of scripts){
        const src = s.getAttribute('src') || '';
        const idx = src.indexOf('/assets/js/hero-slider.js');
        if (idx > -1){
          const path = src.substring(0, idx); // may be '' or '/altoukhi'
          return path;
        }
      }
    } catch(e) {}
    return '';
  }
  const basePrefix = getBasePrefix();

  function withPrefix(url){
    if (!url) return url;
    if (url.startsWith('//') || /^https?:\/\//i.test(url)) return url;
    if (url.startsWith('/') && basePrefix && !url.startsWith(basePrefix + '/')) return basePrefix + url;
    return url;
  }

  const images = (slides.length ? slides.map(s => s.image) : (hero.getAttribute('data-hero-images') || '').split(',').map(s => s.trim()).filter(Boolean)).map(withPrefix);
  const intervalMs = parseInt(hero.getAttribute('data-hero-interval') || '15000', 10);

  if (images.length === 0) return;

  let current = 0;
  let isAActive = true;
  let timer = null;

  function setBg(el, url){
    el.style.backgroundImage = `url('${withPrefix(url)}')`;
  }

  function updateIndicators(idx){
    if (!indicators) return;
    indicators.querySelectorAll('button').forEach((btn, i) => {
      const activeIndicator = btn.querySelector('.absolute.rounded-full.bg-white');
      const glowEffect = btn.querySelector('.absolute.rounded-full.bg-white\\/20');
      
      if (i === idx) {
        // Active state
        btn.classList.remove('bg-white/30');
        btn.classList.add('bg-white/60');
        activeIndicator?.classList.remove('scale-0');
        activeIndicator?.classList.add('scale-100');
        glowEffect?.classList.remove('scale-0');
        glowEffect?.classList.add('scale-150');
      } else {
        // Inactive state
        btn.classList.remove('bg-white/60');
        btn.classList.add('bg-white/30');
        activeIndicator?.classList.remove('scale-100');
        activeIndicator?.classList.add('scale-0');
        glowEffect?.classList.remove('scale-150');
        glowEffect?.classList.add('scale-0');
      }
    });
  }

  const titleEl = hero.querySelector('[data-hero-title]');
  const descEl = hero.querySelector('[data-hero-desc]');
  const cta1El = hero.querySelector('[data-hero-cta1]');
  const cta2El = hero.querySelector('[data-hero-cta2]');

  function applySlideText(idx){
    if (!slides.length) return;
    const s = slides[idx];
    // smooth hide
    [titleEl, descEl].forEach(el => el && el.classList.add('is-hiding'));
    const ctasWrap = hero.querySelector('[data-hero-ctas]');
    ctasWrap && ctasWrap.classList.add('is-hiding');

    setTimeout(() => {
      if (titleEl) titleEl.textContent = s.title || '';
      if (descEl) descEl.textContent = s.desc || '';
      if (cta1El && s.cta1){
        // Update button text while preserving icons
        const textSpan = cta1El.querySelector('[data-hero-cta1-text]');
        if (textSpan) textSpan.textContent = s.cta1.label || '';
        if (s.cta1.href) cta1El.setAttribute('href', withPrefix(s.cta1.href));
        cta1El.classList.toggle('bg-white', !!s.cta1.primary);
        cta1El.classList.toggle('text-primary-600', !!s.cta1.primary);
      }
      if (cta2El && s.cta2){
        // Update button text while preserving icons
        const textSpan = cta2El.querySelector('[data-hero-cta2-text]');
        if (textSpan) textSpan.textContent = s.cta2.label || '';
        if (s.cta2.href) cta2El.setAttribute('href', withPrefix(s.cta2.href));
      }
      [titleEl, descEl].forEach(el => el && el.classList.remove('is-hiding'));
      ctasWrap && ctasWrap.classList.remove('is-hiding');
      
      // Re-initialize Lucide icons after content update
      if (window.lucide) {
        window.lucide.createIcons();
      }
    }, 250);
  }

  function goTo(idx){
    idx = (idx + images.length) % images.length;
    const nextUrl = images[idx];

    const showEl = isAActive ? layerB : layerA;
    setBg(showEl, nextUrl);

    // cross-fade
    showEl.style.opacity = '1';
    (isAActive ? layerA : layerB).style.opacity = '0';

    isAActive = !isAActive;
    current = idx;
    updateIndicators(current);
    applySlideText(current);
    preload((current + 1) % images.length);
  }

  function next(){ goTo(current + 1); }
  function prev(){ goTo(current - 1); }

  function start(){
    if (timer) clearInterval(timer);
    timer = setInterval(next, intervalMs);
  }
  function stop(){ if (timer) { clearInterval(timer); timer = null; } }

  function preload(idx){
    const img = new Image();
    img.src = images[idx];
  }

  // init
  setBg(layerA, images[0]);
  layerA.style.opacity = '1';
  if (images.length > 1){
    setBg(layerB, images[1]);
    layerB.style.opacity = '0';
  }
  updateIndicators(0);
  applySlideText(0);
  preload(1 % images.length);
  start();

  // hover pause
  hero.addEventListener('mouseenter', stop);
  hero.addEventListener('mouseleave', start);

  // indicators click
  if (indicators){
    indicators.addEventListener('click', (e) => {
      const btn = e.target.closest('button[data-idx]');
      if (!btn) return;
      stop();
      goTo(parseInt(btn.getAttribute('data-idx'), 10));
      start();
    });
  }

  // optional: arrow keys navigation
  window.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowRight') { stop(); next(); start(); }
    if (e.key === 'ArrowLeft') { stop(); prev(); start(); }
  });
})();
