(function ($) {
    'use strict';
    window.WTC = window.WTC || {};
    WTC.Admin = {
        init: function () {
            this.initializeSortable();
            this.bindEvents();
        },
        initializeSortable: function () {
            $('.wtc-sortable').sortable({
                placeholder: 'wtc-sortable-placeholder',
                update: function (event, ui) {
                    WTC.Admin.updatePriorities();
                    WTC.Admin.updateLayouts();
                }
            });
        },
        bindEvents: function () {
            $('.wtc-layout-select').on('change', this.updateLayouts);
        },
        updatePriorities: function () {
            var priorities = {};
            var priority = 10;
            $('#billing-fields-sortable .wtc-sortable-item').each(function () {
                var fieldId = $(this).data('field-id');
                priorities[fieldId] = priority;
                priority += 10;
            });
            priority = 10;
            $('#shipping-fields-sortable .wtc-sortable-item').each(function () {
                var fieldId = $(this).data('field-id');
                priorities[fieldId] = priority;
                priority += 10;
            });
            $('#wtc-field-priorities').val(JSON.stringify(priorities));
        },
        updateLayouts: function () {
            var layouts = {};
            $('.wtc-sortable-item').each(function () {
                var fieldId = $(this).data('field-id');
                var layout = $(this).find('.wtc-layout-select').val();
                if (fieldId && layout) {
                    layouts[fieldId] = layout;
                }
            });
            $('#wtc-field-layouts').val(JSON.stringify(layouts));
        },
    };
    $(document).ready(function () {
        WTC.Admin.init();
    });
})(jQuery); 