/**
 * Contentosapp Studio Admin — Settings > Language interactions.
 */
/* global CostudioData */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var i18n = data.i18n || {};
    function t(key, fallback) {
        return (typeof i18n[key] === 'string' && i18n[key].length) ? i18n[key] : fallback;
    }

    if (!$('.cts-lang-select').length) {
        return;
    }

    function fosUpdateLangPreview($select) {
        var $opt = $select.find('option:selected');
        var name = $opt.data('name') || $opt.text();
        var code = String($select.val() || '');
        var previewId = $select.data('preview');
        var $preview = $('#' + previewId);
        if (!$preview.length) { return; }

        $preview.find('.cts-lang-preview__name').text(name);
        $preview.find('.cts-lang-preview__code').text(code);

        var flagBase = (CostudioData && CostudioData.flag_url_base) || '';
        var flagMap = (CostudioData && CostudioData.flag_map) || {};
        var flagFile = flagMap[code] || '';
        if (flagBase && flagFile) {
            $preview.find('.cts-lang-flag')
                .attr('src', flagBase + flagFile)
                .attr('alt', name);
        }
    }

    $(document).on('change', '.cts-lang-select', function () {
        fosUpdateLangPreview($(this));
    });

    $(document).on('submit', '#fos-settings-lang-form', function (e) {
        e.preventDefault();
        var $form = $(this);
        var $btn = $form.find('button[type="submit"]');
        var $msg = $('#fos-settings-lang-msg');
        var ajax = (CostudioData && CostudioData.ajax_url) || '';
        var nonce = (CostudioData && CostudioData.nonce) || '';
        var orig = $btn.text();

        $btn.text('…').prop('disabled', true);
        $msg.text('').removeClass('is-success is-error');

        var formData = $form.serializeArray();
        formData.push({ name: 'action', value: 'costudio_save_settings' });
        formData.push({ name: 'nonce', value: nonce });

        $.post(ajax, formData)
            .done(function (res) {
                if (res.success) {
                    $msg.text(res.data || t('saved', 'Saved!')).addClass('is-success');
                } else {
                    $msg.text(res.data || t('error', 'Error')).addClass('is-error');
                }
                $btn.text(orig).prop('disabled', false);
                setTimeout(function () { $msg.text('').removeClass('is-success is-error'); }, 3000);
            })
            .fail(function () {
                $msg.text(t('network_error', 'Network error.')).addClass('is-error');
                $btn.text(orig).prop('disabled', false);
            });
    });
}(jQuery));
