/* Pull-to-refresh — drag down at the top of a list to reload.
   Dispatches window 'app:refresh' (ListMixin components listen and reload). */
(function () {
    var THRESH = 70, MAX = 120, DAMP = 0.5;
    var startY = 0, dist = 0, pulling = false, refreshing = false, ind;

    function ensure() {
        if (ind) return;
        ind = document.createElement('div');
        ind.className = 'ptr';
        ind.innerHTML = '<i class="fa-light fa-arrow-down"></i>';
        document.body.appendChild(ind);
    }
    function atTop() { return (window.scrollY || document.documentElement.scrollTop || 0) <= 0; }
    function set(y, op) { ensure(); ind.style.transform = 'translateX(-50%) translateY(' + y + 'px)'; ind.style.opacity = op; }
    function reset() { dist = 0; if (ind) { ind.style.transform = 'translateX(-50%) translateY(-46px)'; ind.style.opacity = 0; ind.classList.remove('ready'); } }

    document.addEventListener('touchstart', function (e) {
        if (refreshing || e.touches.length !== 1) return;
        if (atTop()) { startY = e.touches[0].clientY; pulling = true; dist = 0; }
    }, { passive: true });

    document.addEventListener('touchmove', function (e) {
        if (!pulling || refreshing) return;
        var dy = e.touches[0].clientY - startY;
        if (dy <= 0 || !atTop()) { pulling = false; reset(); return; }
        dist = Math.min(MAX, dy * DAMP);
        set(dist - 10, Math.min(1, dist / THRESH));
        var ready = dist >= THRESH;
        ind.classList.toggle('ready', ready);
        ind.querySelector('i').className = ready ? 'fa-light fa-arrow-up' : 'fa-light fa-arrow-down';
    }, { passive: true });

    document.addEventListener('touchend', function () {
        if (!pulling) return;
        pulling = false;
        if (dist >= THRESH) trigger(); else reset();
    });

    function trigger() {
        refreshing = true;
        ensure();
        ind.querySelector('i').className = 'fa-light fa-spinner fa-spin';
        set(56, 1);
        window.dispatchEvent(new CustomEvent('app:refresh'));
        setTimeout(function () {
            refreshing = false; reset();
            setTimeout(function () { if (ind) ind.querySelector('i').className = 'fa-light fa-arrow-down'; }, 250);
        }, 900);
    }
})();
