(function (window, $) {
    if (!$) return;

    var settings = window.nnaxAdminSettings || {};
    var optionName = (settings.optionName || '').toString();
    var i18n = settings.i18n || {};

    function isHex(v) {
        return !!(v && /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v));
    }

    function escAttr(v) {
        return String(v)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function getNextIndex($tbody) {
        var max = -1;
        $tbody.find('tr.nnaxadmin-meta-row').each(function () {
            var $input = $(this).find('input[name*="[custom_meta_fields]"][name$="[label]"]').first();
            if (!$input.length) return;
            var match = $input.attr('name').match(/\[custom_meta_fields\]\[(\d+)\]\[label\]$/);
            if (!match) return;
            var idx = parseInt(match[1], 10);
            if (!isNaN(idx) && idx > max) max = idx;
        });
        return max + 1;
    }

    function reindexRows($tbody) {
        $tbody.find('tr.nnaxadmin-meta-row').each(function (idx) {
            $(this).find('input[name], select[name], textarea[name]').each(function () {
                this.name = this.name.replace(/\[custom_meta_fields\]\[\d+\]\[/, '[custom_meta_fields][' + idx + '][');
            });
        });
    }

    function addRow($tbody, data) {
        if (!optionName) return;

        var idx = getNextIndex($tbody);
        var label = data && data.label ? data.label : '';
        var type = data && data.type ? data.type : 'text';
        var key = data && data.key ? data.key : '';

        var $row = $('<tr class="nnaxadmin-meta-row"></tr>');
        $row.html(
            '<td><button type="button" class="button-link nnaxadmin-drag-handle" draggable="true" title="' + escAttr(i18n.changeOrder || '') + '" aria-label="' + escAttr(i18n.changeOrder || '') + '">⋮⋮</button></td>' +
            '<td><input type="text" class="regular-text" name="' + optionName + '[custom_meta_fields][' + idx + '][label]" value="' + escAttr(label) + '" placeholder="' + escAttr(i18n.labelPlaceholder || '') + '"></td>' +
            '<td><select name="' + optionName + '[custom_meta_fields][' + idx + '][type]">' +
                '<option value="text">' + escAttr(i18n.text || 'Text') + '</option>' +
                '<option value="textarea">' + escAttr(i18n.textarea || 'Textarea') + '</option>' +
                '<option value="date">' + escAttr(i18n.date || 'Date') + '</option>' +
                '<option value="number">' + escAttr(i18n.number || 'Number') + '</option>' +
                '<option value="email">' + escAttr(i18n.email || 'Email') + '</option>' +
                '<option value="url">' + escAttr(i18n.url || 'URL') + '</option>' +
            '</select></td>' +
            '<td><input type="text" class="regular-text code" name="' + optionName + '[custom_meta_fields][' + idx + '][key]" value="' + escAttr(key) + '" placeholder="_nnaxfuf_my_field"></td>' +
            '<td><button type="button" class="button-link-delete nnaxadmin-remove-meta-row">' + escAttr(i18n.remove || 'Remove') + '</button></td>'
        );

        $tbody.append($row);
        $row.find('select').val(type);
        reindexRows($tbody);
    }

    $(function () {
        var $fields = $('.nnaxadmin-color-field');
        if ($fields.length) {
            $fields.each(function () {
                var value = String($(this).val() || '').trim();
                if (value && !isHex(value)) {
                    var def = String($(this).data('default-color') || '').trim();
                    if (isHex(def)) {
                        $(this).val(def);
                    }
                }
            });

            $fields.wpColorPicker();

            $('#nnaxadmin-reset-colors').on('click', function (e) {
                e.preventDefault();

                $fields.each(function () {
                    var $field = $(this);
                    var def = String($field.data('default-color') || '').trim();
                    if (!isHex(def)) return;

                    if ($field.hasClass('wp-color-picker')) {
                        $field.wpColorPicker('color', def);
                    } else {
                        $field.val(def).trigger('change');
                    }
                });
            });
        }

        var $wrap = $('.wrap.nnaxadmin-wrap');
        if ($wrap.length) {
            var $header = $wrap.find('.nnax-header').first();
            if ($header.length) {
                $wrap.find('.notice, .update-nag, .error, .updated').each(function () {
                    var $notice = $(this);
                    if ($notice.closest('.nnax-header').length) {
                        $notice.insertBefore($header);
                    }
                });
            }
        }

        var $tbody = $('#nnaxadmin-custom-meta-table tbody');
        if (!$tbody.length) return;

        $(document).on('click', function (ev) {
            if ($(ev.target).is('#nnaxadmin-add-meta-row')) {
                ev.preventDefault();
                addRow($tbody);
            }

            if ($(ev.target).closest('.nnaxadmin-remove-meta-row').length) {
                ev.preventDefault();
                var $tr = $(ev.target).closest('tr');
                if ($tr.length) {
                    $tr.remove();
                    reindexRows($tbody);
                }
            }
        });

        var draggingRow = null;

        $tbody.on('dragstart', function (ev) {
            var $handle = $(ev.target).closest('.nnaxadmin-drag-handle');
            if (!$handle.length) return;
            var $tr = $handle.closest('tr');
            if (!$tr.length) return;
            draggingRow = $tr.get(0);
            $tr.addClass('nnaxadmin-dragging-row');
            ev.originalEvent.dataTransfer.effectAllowed = 'move';
            try {
                ev.originalEvent.dataTransfer.setData('text/plain', 'drag');
            } catch (error) {}
        });

        $tbody.on('dragover', function (ev) {
            if (!draggingRow) return;
            ev.preventDefault();
            var target = $(ev.target).closest('tr.nnaxadmin-meta-row').get(0);
            if (!target || target === draggingRow) return;

            var rect = target.getBoundingClientRect();
            var before = (ev.originalEvent.clientY - rect.top) < (rect.height / 2);
            if (before) {
                target.parentNode.insertBefore(draggingRow, target);
            } else {
                target.parentNode.insertBefore(draggingRow, target.nextSibling);
            }
        });

        $tbody.on('dragend', function () {
            if (!draggingRow) return;
            $(draggingRow).removeClass('nnaxadmin-dragging-row');
            draggingRow = null;
            reindexRows($tbody);
        });

        var $form = $tbody.closest('form');
        if ($form.length) {
            $form.on('submit', function () {
                reindexRows($tbody);
            });
        }
    });
})(window, window.jQuery);
