/**
 * Settings page helpers.
 *
 * Currently one job: show which custom fields a real order carries, so the shop
 * can find the meta key its invoicing plugin uses for company identifiers
 * instead of guessing.
 */
(function () {
    'use strict';

    var button = document.getElementById('ssrc-probe-run');
    var input = document.getElementById('ssrc-probe-order');
    var output = document.getElementById('ssrc-probe-result');

    if (!button || !input || !output || !window.ssrcAdmin) {
        return;
    }

    button.addEventListener('click', function () {
        var orderId = input.value.replace(/[^0-9]/g, '');

        if (!orderId) {
            output.textContent = '';
            return;
        }

        output.textContent = '…';

        var xhr = new XMLHttpRequest();
        xhr.open('POST', window.ssrcAdmin.ajaxUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onloadend = function () {
            var payload = null;

            try {
                payload = JSON.parse(xhr.responseText);
            } catch (e) {
                payload = null;
            }

            if (!payload || !payload.success || !payload.data || !payload.data.rows) {
                output.textContent = payload && payload.data && payload.data.message
                    ? payload.data.message
                    : window.ssrcAdmin.genericError;
                return;
            }

            render(payload.data.rows);
        };

        xhr.send(
            'action=' + encodeURIComponent(window.ssrcAdmin.probeAction) +
            '&nonce=' + encodeURIComponent(window.ssrcAdmin.probeNonce) +
            '&order=' + encodeURIComponent(orderId)
        );
    });

    function render(rows) {
        var table = document.createElement('table');
        table.className = 'widefat striped';

        var body = document.createElement('tbody');

        rows.forEach(function (row) {
            var tr = document.createElement('tr');

            var keyCell = document.createElement('td');
            var code = document.createElement('code');
            code.textContent = row.key;
            keyCell.appendChild(code);

            if (row.label) {
                var note = document.createElement('span');
                note.className = 'description';
                note.textContent = ' ' + row.label;
                keyCell.appendChild(note);
            }

            var valueCell = document.createElement('td');
            valueCell.textContent = row.value;

            tr.appendChild(keyCell);
            tr.appendChild(valueCell);
            body.appendChild(tr);
        });

        table.appendChild(body);

        output.textContent = '';
        output.appendChild(table);
    }
}());

/**
 * Decision screen: pick the decision, then the wording.
 *
 * The decision is a field, not something inferred from the chosen message. Once
 * it is picked the message list narrows to the sentences that belong to it, so
 * "unsealed goods" simply is not reachable while approving.
 *
 * Nothing is preselected and the send button starts disabled: a decision that
 * ends in money leaving the till should take a deliberate click. With scripts
 * off the button stays live and the server refuses a submission with no
 * decision, rather than guessing one.
 *
 * A select element cannot wrap, so a full sentence is unreadable inside it.
 * Writing the preset into the textarea means the operator reads the whole thing,
 * can edit it before sending, and what is on screen is what the customer gets.
 */
(function () {
    'use strict';

    var preset = document.getElementById('ssrc-preset');
    var message = document.getElementById('ssrc-message');
    var send = document.getElementById('ssrc-send');
    var radios = document.querySelectorAll('.ssrc-decision');

    if (!preset || !message || !radios.length || !window.ssrcDecision || !window.ssrcDecision.presets) {
        return;
    }

    var placeholder = preset.options.length ? preset.options[0].text : '';
    var all = [];

    Array.prototype.forEach.call(preset.getElementsByTagName('option'), function (option) {
        if (!option.value) {
            return;
        }

        all.push({
            value: option.value,
            outcome: option.getAttribute('data-outcome') || '',
            label: option.text,
            title: option.title || ''
        });
    });

    send.disabled = true;

    function isPresetText(value) {
        var presets = window.ssrcDecision.presets;

        for (var key in presets) {
            if (Object.prototype.hasOwnProperty.call(presets, key) && presets[key] === value) {
                return true;
            }
        }

        return false;
    }

    function narrowTo(outcome) {
        preset.innerHTML = '';

        var first = document.createElement('option');
        first.value = '';
        first.text = placeholder;
        preset.appendChild(first);

        all.forEach(function (item) {
            if (item.outcome !== outcome) {
                return;
            }

            var option = document.createElement('option');
            option.value = item.value;
            option.text = item.label;
            option.title = item.title;
            option.setAttribute('data-outcome', item.outcome);
            preset.appendChild(option);
        });

        // Only wording the operator did not type gets cleared. Anything written
        // by hand survives a change of mind about the decision.
        if (isPresetText(message.value)) {
            message.value = '';
        }
    }

    Array.prototype.forEach.call(radios, function (radio) {
        radio.addEventListener('change', function () {
            if (!radio.checked) {
                return;
            }

            narrowTo(radio.value);
            send.disabled = false;
        });
    });

    preset.addEventListener('change', function () {
        var key = preset.value;

        message.value = key && window.ssrcDecision.presets[key]
            ? window.ssrcDecision.presets[key]
            : '';

        message.focus();
    });
}());
