/* global jQuery, WPSN_SERP_GAP */
(function ($) {
    'use strict';

    function fmtUtc(ts) {
        try {
            var d = new Date(ts * 1000);
            // YYYY-MM-DD HH:mm:ss UTC
            return d.toISOString().replace('T', ' ').replace('Z', ' UTC');
        } catch (e) {
            return String(ts);
        }
    }

    var state = {
        backoffUntil: parseInt((WPSN_SERP_GAP && WPSN_SERP_GAP.serperBackoffUntil) || '0', 10) || 0
    };

    function setTestResult(text) {
        var $r = $('#wpsn-serper-test-result');
        if (!$r.length) {
            return;
        }
        $r.text(text || '');
    }

    function updateBackoffUI() {
        var $status = $('#wpsn-serper-backoff-status');
        var $clearBtn = $('#wpsn-serper-backoff-clear');
        if (!$status.length) {
            return;
        }

        var now = Math.floor(Date.now() / 1000);
        if (state.backoffUntil > now) {
            var wait = state.backoffUntil - now;
            $status.text('Active — retry in ' + wait + 's (until ' + fmtUtc(state.backoffUntil) + ').');
            if ($clearBtn.length) {
                $clearBtn.show().prop('disabled', false);
            }
        } else {
            $status.text('Not active.');
            if ($clearBtn.length) {
                $clearBtn.hide().prop('disabled', true);
            }
        }
    }

    function readInput(names) {
        var i;
        for (i = 0; i < names.length; i++) {
            var name = names[i];
            var $el = $('input[name="' + name + '"]');
            if ($el.length) {
                return $el.first().val() || '';
            }
        }
        return '';
    }

    function ajaxPost(action, data) {
        var payload = $.extend(
            {
                action: action,
                nonce: (WPSN_SERP_GAP && WPSN_SERP_GAP.nonce) || ''
            },
            data || {}
        );
        return $.post((WPSN_SERP_GAP && WPSN_SERP_GAP.ajaxUrl) || ajaxurl, payload);
    }

    function copyToClipboard(text) {
        if (!text) {
            return Promise.reject(new Error('empty'));
        }
        if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
            return navigator.clipboard.writeText(text);
        }
        return new Promise(function (resolve, reject) {
            try {
                var $tmp = $('<textarea readonly></textarea>');
                $tmp.css({ position: 'absolute', left: '-9999px', top: '0' });
                $tmp.val(text);
                $('body').append($tmp);
                $tmp[0].select();
                var ok = document.execCommand('copy');
                $tmp.remove();
                if (ok) {
                    resolve();
                } else {
                    reject(new Error('copy_failed'));
                }
            } catch (e) {
                reject(e);
            }
        });
    }

    $(function () {
        updateBackoffUI();
        setInterval(updateBackoffUI, 1000);

        $('#wpsn-serper-test-btn').on('click', function (e) {
            e.preventDefault();

            var $btn = $(this);
            $btn.prop('disabled', true);
            setTestResult((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.testing) || 'Testing…');

            var gl = readInput(['gl', 'wpsn[serp_gap][serper][gl]']);
            var hl = readInput(['hl', 'wpsn[serp_gap][serper][hl]']);

            ajaxPost('wpsn_serper_test_connection', { gl: gl, hl: hl })
                .done(function (resp) {
                    if (!resp || !resp.success || !resp.data) {
                        setTestResult((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.error) || 'Error.');
                        return;
                    }

                    var d = resp.data;
                    var status = parseInt(d.http_status || '0', 10) || 0;

                    if (d.ok) {
                        var msgOk = d.message || ('OK (HTTP ' + status + ')');
                        setTestResult('✔ ' + msgOk);
                    } else {
                        var msg = d.message || 'Error.';
                        if (status === 429) {
                            var ra = parseInt(d.retry_after || d.backoff_retry_after || '0', 10) || 0;
                            if (ra > 0) {
                                msg = 'HTTP 429 — retry in ' + ra + 's. ' + msg;
                            } else {
                                msg = 'HTTP 429 — rate limited. ' + msg;
                            }
                            setTestResult('⚠ ' + msg);
                        } else if (status === 401 || status === 403) {
                            setTestResult('✖ HTTP ' + status + ' — ' + msg);
                        } else {
                            setTestResult('✖ HTTP ' + (status || '0') + ' — ' + msg);
                        }
                    }

                    if (typeof d.backoff_until !== 'undefined') {
                        state.backoffUntil = parseInt(d.backoff_until || '0', 10) || 0;
                        updateBackoffUI();
                    }
                })
                .fail(function () {
                    // If admin-ajax.php is blocked/busy (common 503), fall back to direct admin-post link.
                    setTestResult((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.error) || 'Error.');
                    var href = $btn.attr('href') || '';
                    if (href) {
                        window.location = href;
                    }
                })
                .always(function () {
                    $btn.prop('disabled', false);
                });
        });

        $('#wpsn-serper-backoff-clear').on('click', function (e) {
            e.preventDefault();

            var confirmText = (WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.clearBackoffConfirm) || 'Clear backoff?';
            if (!window.confirm(confirmText)) {
                return;
            }

            var $btn = $(this);
            $btn.prop('disabled', true);

            ajaxPost('wpsn_serper_clear_backoff', {})
                .done(function (resp) {
                    if (!resp || !resp.success || !resp.data) {
                        setTestResult((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.error) || 'Error.');
                        return;
                    }
                    var d = resp.data;
                    state.backoffUntil = parseInt(d.backoff_until || '0', 10) || 0;
                    updateBackoffUI();
                    setTestResult('✔ ' + ((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.cleared) || 'Backoff cleared.'));
                })
                .fail(function () {
                    setTestResult((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.error) || 'Error.');
                    var href = $btn.attr('href') || '';
                    if (href) {
                        window.location = href;
                    }
                })
                .always(function () {
                    $btn.prop('disabled', false);
                });
        });

        // Copy helpers (SERP Gap run details).
        $(document).on('click', '[data-wpsn-copy-target]', function (e) {
            e.preventDefault();

            var $btn = $(this);
            var target = $btn.attr('data-wpsn-copy-target') || '';
            if (!target) {
                return;
            }

            var $el = $(target);
            if (!$el.length) {
                return;
            }

            var text = '';
            if ($el.is('textarea') || $el.is('input')) {
                text = $el.val() || '';
            } else {
                text = $el.text() || '';
            }

            var original = $btn.text();
            $btn.prop('disabled', true);
            $btn.text((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.copying) || 'Copying…');

            copyToClipboard(String(text))
                .then(function () {
                    $btn.text((WPSN_SERP_GAP && WPSN_SERP_GAP.strings && WPSN_SERP_GAP.strings.copied) || 'Copied!');
                    setTimeout(function () {
                        $btn.prop('disabled', false);
                        $btn.text(original);
                    }, 1200);
                })
                .catch(function () {
                    $btn.prop('disabled', false);
                    $btn.text(original);
                });
        });
    });
})(jQuery);
