/**
 * TamRank WebP — Settings page controls.
 *
 * Live quality-slider value + "Convert existing images" bulk runner that walks
 * the media library in batches via the tamrank_generate_webp_batch AJAX action.
 */
(function ($) {
    'use strict';

    /**
     * Fill one placeholder without letting the value expand.
     *
     * Copy of the canonical helper in assets/js/tamrank-onboarding.js; read the
     * docblock there for why String.replace() with a STRING replacement mangles
     * any value carrying $&, $`, $' or $$, and why this is a copy instead of a
     * shared global. `token` may be a string or a RegExp; a FUNCTION replacement
     * is exempt from that expansion in both cases. Keep the body identical.
     */
    function fillPlaceholder(tpl, token, value) {
        var literal = String(value);
        return String(tpl).replace(token, function () { return literal; });
    }

    var cfg  = window.tamrankWebP || {};
    var i18n = cfg.i18n || {};

    // Live quality-slider value readout.
    $('#webp_quality').on('input', function () {
        $(this).closest('.tr-slider-wrap').find('.tr-slider-value').text(this.value);
    });

    var $btn    = $('#tamrank-webp-bulk');
    var $status = $('#tamrank-webp-bulk-status');
    if (!$btn.length) {
        return;
    }

    function runBatch(offset, total) {
        $.post(cfg.ajaxUrl, {
            action: 'tamrank_generate_webp_batch',
            nonce:  cfg.nonce,
            offset: offset,
            limit:  20
        }).done(function (resp) {
            if (!resp || !resp.success || !resp.data) {
                fail();
                return;
            }
            var done = total + (resp.data.processed ? resp.data.processed.length : 0);
            if (resp.data.done) {
                $status.text(fillPlaceholder(i18n.done || 'Done — %d images processed.', '%d', done));
                $btn.prop('disabled', false);
            } else {
                $status.text((i18n.converting || 'Converting images...') + ' (' + done + ')');
                runBatch(resp.data.next_offset, done);
            }
        }).fail(fail);
    }

    function fail() {
        $status.text(i18n.error || 'Conversion failed. Please try again.');
        $btn.prop('disabled', false);
    }

    // The branded dialog from tam-toast.js, which resolves a Promise where
    // window.confirm returned straight away. tam-rank-toast is a declared
    // dependency of this script, so the function is normally there; the
    // fallback only catches a half-loaded admin, where losing the confirmation
    // step altogether would be worse than a plain browser box. No confirm
    // string at all still means no dialog, exactly as before.
    function askConfirm() {
        if (!i18n.confirm) {
            return Promise.resolve(true);
        }
        var title = i18n.confirmTitle || 'Convert existing images?';
        if (window.TamRank && typeof window.TamRank.confirm === 'function') {
            return window.TamRank.confirm({
                title:        title,
                message:      i18n.confirm,
                confirmLabel: i18n.confirmLabel || 'Convert',
                cancelLabel:  i18n.cancel,
                variant:      'default'
            });
        }
        return Promise.resolve(window.confirm(title + '\n\n' + i18n.confirm));
    }

    $btn.on('click', function (e) {
        e.preventDefault();
        askConfirm().then(function (ok) {
            if (!ok) {
                return;
            }
            $btn.prop('disabled', true);
            $status.text(i18n.converting || 'Converting images...');
            runBatch(0, 0);
        });
    });
})(jQuery);
