(() => {
  function qs(root, sel){ return root.querySelector(sel); }
  function qsa(root, sel){ return Array.from(root.querySelectorAll(sel)); }

  function buildModal(){
    let modal = document.getElementById('nikanStoryModal');
    if (modal) return modal;

    modal = document.createElement('div');
    modal.id = 'nikanStoryModal';
    modal.className = 'nikan-story-modal';
    modal.innerHTML = `
      <div class="nikan-story-backdrop" data-close="1"></div>
      <div class="nikan-story-modal-inner" role="dialog" aria-modal="true">
        <button type="button" class="nikan-story-close" aria-label="بستن">×</button>
        <div class="nikan-story-progress"></div>
        <div class="nikan-story-stage">
          <div class="nikan-story-media"></div>
          <div class="nikan-story-cta-wrap">
            <a class="nikan-story-cta" href="#" target="_self" rel="nofollow noopener">مشاهده</a>
          </div>
        </div>
        <button type="button" class="nikan-story-nav nikan-story-prev" aria-label="قبلی"></button>
        <button type="button" class="nikan-story-nav nikan-story-next" aria-label="بعدی"></button>
      </div>`;
    document.body.appendChild(modal);
    return modal;
  }

  function initStoryWidget(widget){
    if (!widget || widget.dataset.nikanStoryInit === '1') return;
    widget.dataset.nikanStoryInit = '1';

    const jsonEl = qs(widget, '.nikan-story-json');
    if (!jsonEl) return;

    let data;
    try{ data = JSON.parse(jsonEl.textContent || '{}'); } catch(e){ return; }
    const stories = Array.isArray(data.stories) ? data.stories : [];
    if (!stories.length) return;

    const modal = buildModal();
    const elBackdrop = qs(modal, '.nikan-story-backdrop');
    const elClose = qs(modal, '.nikan-story-close');
    const elMedia = qs(modal, '.nikan-story-media');
    const elProgress = qs(modal, '.nikan-story-progress');
    const elCtaWrap = qs(modal, '.nikan-story-cta-wrap');
    const elCta = qs(modal, '.nikan-story-cta');
    const btnPrev = qs(modal, '.nikan-story-prev');
    const btnNext = qs(modal, '.nikan-story-next');

    let activeIndex = 0;
    let timer = null;
    let activeVideo = null;

    function clearTimer(){
      if (timer){ clearTimeout(timer); timer = null; }
    }
    function stopVideo(){
      if (activeVideo){
        try{ activeVideo.pause(); }catch(e){}
        activeVideo = null;
      }
    }
    function closeModal(){
      clearTimer();
      stopVideo();
      modal.classList.remove('is-open');
      document.body.classList.remove('nikan-story-lock');
      elMedia.innerHTML = '';
      if (elProgress) elProgress.innerHTML = '';
    }

    function buildProgress(idx){
      if (!elProgress) return;
      elProgress.innerHTML = '';
      stories.forEach((_, i) => {
        const seg = document.createElement('div');
        seg.className = 'nikan-story-seg';
        seg.innerHTML = '<span class="nikan-story-seg-fill"></span>';
        if (i < idx) seg.classList.add('is-done');
        if (i === idx) seg.classList.add('is-active');
        elProgress.appendChild(seg);
      });
    }

    function setActiveFill(pct){
      const fill = elProgress ? elProgress.querySelector('.nikan-story-seg.is-active .nikan-story-seg-fill') : null;
      if (fill) fill.style.width = `${pct}%`;
    }

    function next(){
      if (activeIndex + 1 < stories.length) openStory(activeIndex + 1);
      else closeModal();
    }
    function prev(){
      if (activeIndex - 1 >= 0) openStory(activeIndex - 1);
    }

    function openStory(index){
      clearTimer();
      stopVideo();

      activeIndex = index;
      const st = stories[activeIndex];

      buildProgress(activeIndex);
      setActiveFill(0);

      // CTA
      const hasCta = st.ctaUrl && st.ctaText;
      if (hasCta){
        elCtaWrap.style.display = '';
        elCta.textContent = st.ctaText;
        elCta.href = st.ctaUrl;
        elCta.target = st.ctaNewTab ? '_blank' : '_self';
        elCta.rel = st.ctaNewTab ? 'nofollow noopener' : 'nofollow';
      } else {
        elCtaWrap.style.display = 'none';
      }

      elMedia.innerHTML = '';

      modal.classList.add('is-open');
      document.body.classList.add('nikan-story-lock');

      if (st.type === 'video'){
        const v = document.createElement('video');
        v.src = st.src || '';
        v.autoplay = true;
        v.playsInline = true;
        v.setAttribute('playsinline', 'true');
        v.setAttribute('webkit-playsinline', 'true');
        v.setAttribute('x5-playsinline', 'true');
        v.preload = 'auto';
        v.controls = false;

        activeVideo = v;
        elMedia.appendChild(v);

        const raf = () => {
          if (!activeVideo || !modal.classList.contains('is-open')) return;
          if (activeVideo.duration && isFinite(activeVideo.duration)){
            const pct = Math.min(100, (activeVideo.currentTime / activeVideo.duration) * 100);
            setActiveFill(pct);
          }
          requestAnimationFrame(raf);
        };

        v.addEventListener('loadedmetadata', () => requestAnimationFrame(raf));
        v.addEventListener('ended', next);
      } else {
        const img = document.createElement('img');
        img.src = st.src || '';
        img.alt = st.title || '';
        elMedia.appendChild(img);

        const duration = Math.max(1, parseInt(st.duration || 5, 10));
        const startedAt = Date.now();

        const tick = () => {
          if (!modal.classList.contains('is-open')) return;
          const elapsed = (Date.now() - startedAt) / 1000;
          const pct = Math.min(100, (elapsed / duration) * 100);
          setActiveFill(pct);
          if (pct < 100) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);

        timer = setTimeout(next, duration * 1000);
      }
    }

    qsa(widget, '.nikan-story-item').forEach(btn => {
      btn.addEventListener('click', () => {
        const idx = parseInt(btn.getAttribute('data-index') || '0', 10);
        openStory(isNaN(idx) ? 0 : idx);
      });
    });

    elBackdrop && elBackdrop.addEventListener('click', closeModal);
    elClose && elClose.addEventListener('click', closeModal);
    btnNext && btnNext.addEventListener('click', next);
    btnPrev && btnPrev.addEventListener('click', prev);

    document.addEventListener('keydown', (e) => {
      if (!modal.classList.contains('is-open')) return;
      if (e.key === 'Escape') closeModal();
      if (e.key === 'ArrowRight') prev(); // RTL
      if (e.key === 'ArrowLeft') next();  // RTL
    });
  }

  function initAll(){
    document.querySelectorAll('[data-nikan-story=\"1\"]').forEach(initStoryWidget);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initAll);
  else initAll();
})();
