import { icon } from './icons.js';
import { hapticImpact } from './telegram.js';

/**
 * Open a full-screen story overlay.
 * @param {Array<{title:string, text:string, iconName?:string, cta?:{label:string, href:string}}>} slides
 * @param {{durationMs?:number}} opts
 */
export function openStoryViewer(slides, opts = {}) {
    if (!Array.isArray(slides) || !slides.length) return;
    const durationMs = opts.durationMs || 5000;

    const overlay = document.createElement('div');
    overlay.className = 'story-overlay';
    overlay.innerHTML = `
        <div class="story-progress">
            ${slides.map(() => `<span class="story-seg"><i></i></span>`).join('')}
        </div>
        <button type="button" class="story-close" aria-label="close">${icon('close')}</button>
        <div class="story-slide-host"></div>
        <div class="story-tapzone story-tapzone-prev" aria-label="prev"></div>
        <div class="story-tapzone story-tapzone-next" aria-label="next"></div>
        <div class="story-nav">
            <button type="button" class="btn btn-ghost btn-block story-prev-btn">قبلی</button>
            <button type="button" class="btn btn-primary btn-block story-next-btn">بعدی</button>
        </div>
    `;
    document.body.appendChild(overlay);
    document.body.style.overflow = 'hidden';

    const segs = Array.from(overlay.querySelectorAll('.story-seg > i'));
    const host = overlay.querySelector('.story-slide-host');
    const nextBtn = overlay.querySelector('.story-next-btn');
    const prevBtn = overlay.querySelector('.story-prev-btn');
    const closeBtn = overlay.querySelector('.story-close');

    let idx = 0;
    let startedAt = 0;
    let raf = 0;
    let paused = false;

    function render() {
        const s = slides[idx];
        host.innerHTML = `
            <div class="story-slide">
                ${s.iconName ? `<span class="story-slide-ico">${icon(s.iconName)}</span>` : ''}
                <h2>${escapeHtml(s.title || '')}</h2>
                <p>${escapeHtml(s.text || '')}</p>
                ${s.cta ? `<a class="btn btn-primary story-cta" href="${escapeHtml(s.cta.href)}">${escapeHtml(s.cta.label)}</a>` : ''}
            </div>
        `;
        prevBtn.style.visibility = idx === 0 ? 'hidden' : 'visible';
        nextBtn.textContent = idx === slides.length - 1 ? 'تمام' : 'بعدی';
        segs.forEach((el, i) => {
            el.style.transition = 'none';
            el.style.width = i < idx ? '100%' : '0%';
        });
        startedAt = performance.now();
        tick();
    }

    function tick() {
        cancelAnimationFrame(raf);
        function step(now) {
            if (paused) { raf = requestAnimationFrame(step); return; }
            const elapsed = now - startedAt;
            const pct = Math.min(100, (elapsed / durationMs) * 100);
            segs[idx].style.transition = 'none';
            segs[idx].style.width = pct + '%';
            if (pct >= 100) { goNext(); return; }
            raf = requestAnimationFrame(step);
        }
        raf = requestAnimationFrame(step);
    }

    function goNext() {
        hapticImpact('light');
        if (idx >= slides.length - 1) { close(); return; }
        idx += 1;
        render();
    }
    function goPrev() {
        hapticImpact('light');
        if (idx <= 0) return;
        idx -= 1;
        render();
    }
    function close() {
        cancelAnimationFrame(raf);
        document.body.style.overflow = '';
        overlay.classList.add('is-closing');
        setTimeout(() => overlay.remove(), 180);
    }

    overlay.querySelector('.story-tapzone-next').addEventListener('click', goNext);
    overlay.querySelector('.story-tapzone-prev').addEventListener('click', goPrev);
    nextBtn.addEventListener('click', goNext);
    prevBtn.addEventListener('click', goPrev);
    closeBtn.addEventListener('click', close);

    overlay.addEventListener('pointerdown', () => { paused = true; });
    overlay.addEventListener('pointerup', () => { paused = false; });
    overlay.addEventListener('pointercancel', () => { paused = false; });

    render();
}

function escapeHtml(value) {
    if (value === null || value === undefined) return '';
    return String(value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}
