jQuery(function ($) {

    // Keep the "Total: N photos" counters in sync as Columns/Rows change.
    // (The old empty placeholder-cell grids that used to sit below these
    // were removed once the real photo-based Live Preview shipped.)
    function updateFbTotal() {
        var cols = Math.max(1, parseInt($('#yatoon_sf_fb_columns').val(), 10) || 4);
        var rows = Math.max(1, parseInt($('#yatoon_sf_fb_rows').val(), 10) || 3);
        $('.yatoon-sf-fb-total').text(cols * rows);
    }
    function updateIgTotal() {
        var cols = Math.max(1, parseInt($('#yatoon_sf_ig_columns').val(), 10) || 4);
        var rows = Math.max(1, parseInt($('#yatoon_sf_ig_rows').val(), 10) || 3);
        $('.yatoon-sf-ig-total').text(cols * rows);
    }
    $('#yatoon_sf_fb_columns, #yatoon_sf_fb_rows').on('input change', updateFbTotal);
    $('#yatoon_sf_ig_columns, #yatoon_sf_ig_rows').on('input change', updateIgTotal);
    updateFbTotal();
    updateIgTotal();

    // Live Preview (Step 3) - re-renders the actual shortcode output with
    // whatever is currently in the form, without requiring Save first.
    var $livePreview = $('#yatoon-sf-live-preview-content');
    var $livePreviewLoading = $('#yatoon-sf-live-preview-loading');
    var livePreviewTimer = null;
    var livePreviewXhr = null;

    function refreshLivePreview() {
        if (!$livePreview.length) return;

        clearTimeout(livePreviewTimer);
        livePreviewTimer = setTimeout(function () {
            if (livePreviewXhr) livePreviewXhr.abort();

            $livePreview.addClass('is-loading');
            $livePreviewLoading.show();

            var data = {
                action:     'yatoon_sf_admin_preview',
                nonce:      YatoonSF.nonce,
                layout:     $('#yatoon_sf_layout').val(),
                display:    $('#yatoon_sf_display_mode').val(),
                lightbox:   $('input[name="yatoon_sf_lightbox"]').is(':checked') ? 1 : 0,
                open_link:  $('input[name="yatoon_sf_open_link"]').is(':checked') ? 1 : 0,
                gap:        $('#yatoon_sf_gap').val(),
                columns:    $('#yatoon_sf_columns').val(),
                rows:       $('#yatoon_sf_rows').val(),
                custom_css: $('#yatoon_sf_custom_css').length ? $('#yatoon_sf_custom_css').val() : ''
            };

            livePreviewXhr = $.post(YatoonSF.ajax_url, data)
                .done(function (resp) {
                    if (resp.success) {
                        $livePreview.html(resp.data.html);
                    }
                })
                .always(function () {
                    $livePreview.removeClass('is-loading');
                    $livePreviewLoading.hide();
                });
        }, 400); // debounce so typing in Custom CSS / dragging Gap doesn't spam requests
    }

    $(document).on('change', '#yatoon_sf_layout, #yatoon_sf_display_mode, input[name="yatoon_sf_lightbox"], input[name="yatoon_sf_open_link"]', refreshLivePreview);
    $(document).on('input', '#yatoon_sf_gap, #yatoon_sf_custom_css, #yatoon_sf_columns, #yatoon_sf_rows', refreshLivePreview);

    // Verify token
    $('#yatoon-sf-verify-btn').on('click', function () {
        var token = $.trim($('#yatoon-sf-token-input').val());
        if (!token) { alert('Please paste a token first.'); return; }

        var $btn = $(this);
        var $result = $('#yatoon-sf-verify-result');
        $btn.addClass('loading').text(YatoonSF.verifying);
        $result.hide();

        $.post(YatoonSF.ajax_url, {
            action: 'yatoon_sf_verify_token',
            nonce:  YatoonSF.nonce,
            token:  token
        })
        .done(function (resp) {
            if (resp.success) {
                var d = resp.data;
                var msg = 'Connected to Facebook: ' + d.page_name;
                $result.removeClass('error').addClass('success').text(msg).show();
                setTimeout(function () { location.reload(); }, 1500);
            } else {
                $result.removeClass('success').addClass('error').text('Error: ' + resp.data).show();
            }
        })
        .fail(function () {
            $result.removeClass('success').addClass('error').text('Error: ' + YatoonSF.error).show();
        })
        .always(function () {
            $btn.removeClass('loading').text('Verify & Save Facebook Token');
        });
    });

    // Verify Instagram token
    $('#yatoon-sf-ig-verify-btn').on('click', function () {
        var token = $.trim($('#yatoon-sf-ig-token-input').val());
        if (!token) { alert('Please paste an Instagram token first.'); return; }

        var $btn = $(this);
        var $result = $('#yatoon-sf-ig-verify-result');
        $btn.addClass('loading').text(YatoonSF.verifying);
        $result.hide();

        $.post(YatoonSF.ajax_url, {
            action: 'yatoon_sf_verify_ig_token',
            nonce:  YatoonSF.nonce,
            token:  token
        })
        .done(function (resp) {
            if (resp.success) {
                $result.removeClass('error').addClass('success').text('Connected to Instagram: @' + resp.data.username).show();
                setTimeout(function () { location.reload(); }, 1500);
            } else {
                $result.removeClass('success').addClass('error').text('Error: ' + resp.data).show();
            }
        })
        .fail(function () {
            $result.removeClass('success').addClass('error').text('Error: ' + YatoonSF.error).show();
        })
        .always(function () {
            $btn.removeClass('loading').text('Verify & Save IG Token');
        });
    });

    // Manual sync
    function showStatus(msg, duration) {
        var $s = $('#yatoon-sf-sync-status');
        $s.text(msg).show();
        if (duration) setTimeout(function () { $s.fadeOut(); }, duration);
    }

    $('.yatoon-sf-btn-all').on('click', function () {
        var $btn     = $(this);
        var platform = $btn.data('platform');
        var orig     = $btn.text();
        $btn.addClass('loading').text(YatoonSF.syncing);
        showStatus('Syncing ' + platform + '...');

        $.post(YatoonSF.ajax_url, { action: 'yatoon_sf_manual_sync', nonce: YatoonSF.nonce, platform: platform })
        .done(function (resp) {
            if (resp.success) {
                var parts = [];
                $.each(resp.data, function (p, r) {
                    if (r.status === 'ok') parts.push(p + ': +' + (r.saved || 0) + ' new photos');
                    else if (r.status === 'error' && r.reason) parts.push(p + ': error - ' + r.reason);
                    else if (r.reason) parts.push(p + ': ' + r.reason);
                });
                showStatus('Done! ' + parts.join(' | ') + ' - Refresh to see changes.', 6000);
            } else { showStatus('Error: ' + YatoonSF.error, 5000); }
        })
        .fail(function () { showStatus('Error: ' + YatoonSF.error, 5000); })
        .always(function () { $btn.removeClass('loading').text(orig); });
    });

    // Copy button
    $(document).on('click', '.yatoon-sf-copy-btn', function () {
        var text = $(this).data('copy'), $btn = $(this);
        if (navigator.clipboard) navigator.clipboard.writeText(text);
        else { $('<input>').val(text).appendTo('body').select(); document.execCommand('copy'); }
        $btn.text('Copied!');
        setTimeout(function () { $btn.text('Copy'); }, 2000);
    });
});
