(function($) {
    'use strict';
    
    var fieldIndex = $('.askagento-field').length;
    var sources = null;
    
    // Init
    $(function() {
        initSortable();
        bindEvents();
    });
    
    function initSortable() {
        $('#askagento-fields-list').sortable({
            handle: '.askagento-handle',
            placeholder: 'askagento-field ui-sortable-placeholder',
            update: reindex
        });
    }
    
    function bindEvents() {
        // Add field
        $('#askagento-add-field').on('click', openModal);
        
        // Modal
        $('.askagento-modal-close, #askagento-cancel').on('click', closeModal);
        $('#askagento-modal').on('click', function(e) {
            if ($(e.target).is('.askagento-modal')) closeModal();
        });
        
        // Search
        $('#askagento-search').on('input', function() {
            filterSources($(this).val());
        });
        
        // Select source
        $(document).on('click', '.askagento-source-item:not(.disabled)', function() {
            $(this).toggleClass('selected');
            $(this).find('input').prop('checked', $(this).hasClass('selected'));
            updateAddBtn();
        });
        
        // Add selected
        $('#askagento-add-selected').on('click', addSelected);
        
        // Remove field
        $(document).on('click', '.askagento-remove', function() {
            if (confirm(askagentoAdmin.i18n.confirmRemove)) {
                $(this).closest('.askagento-field').remove();
                updateEmpty();
                reindex();
            }
        });
        
        // Configure
        $(document).on('click', '.askagento-configure', function() {
            $(this).closest('.askagento-field').find('.askagento-config').slideToggle(150);
        });
        
        // Config changes
        $(document).on('change', '.askagento-cfg-label', function() {
            var $f = $(this).closest('.askagento-field');
            var v = $(this).val();
            $f.find('.askagento-label').text(v);
            $f.find('input[name*="[label]"]').val(v);
        });
        
        $(document).on('change', '.askagento-cfg-type', function() {
            var $f = $(this).closest('.askagento-field');
            var v = $(this).val();
            $f.find('.askagento-type').text($(this).find('option:selected').text());
            $f.find('input[name*="[type]"]').val(v);
        });
        
        $(document).on('change', '.askagento-cfg-count', function() {
            var $f = $(this).closest('.askagento-field');
            $f.find('input[name*="[show_count]"]').val(this.checked ? '1' : '0');
        });
        
        // Post type change
        $('#askagento_post_types').on('change', function() {
            sources = null;
        });
    }
    
    function openModal() {
        $('#askagento-modal').show();
        $('#askagento-search').val('').focus();
        if (!sources) {
            loadSources();
        } else {
            renderSources();
        }
    }
    
    function closeModal() {
        $('#askagento-modal').hide();
        $('.askagento-source-item').removeClass('selected');
        $('.askagento-source-item input').prop('checked', false);
        updateAddBtn();
    }
    
    function loadSources() {
        $('#askagento-sources').html('<p class="askagento-loading">' + askagentoAdmin.i18n.loading + '</p>');
        
        $.post(askagentoAdmin.ajaxUrl, {
            action: 'askagento_get_data_sources',
            nonce: askagentoAdmin.nonce,
            post_types: $('#askagento_post_types').val() || ['product']
        }, function(r) {
            if (r.success) {
                sources = r.data;
                renderSources();
            }
        });
    }
    
    function renderSources() {
        var html = '';
        var existing = getExisting();
        
        // Taxonomies
        if (sources.taxonomies && Object.keys(sources.taxonomies).length) {
            html += '<h4 class="askagento-group-title">Taxonomies</h4>';
            $.each(sources.taxonomies, function(k, s) {
                html += renderItem(s, existing);
            });
        }
        
        // Meta
        if (sources.meta && Object.keys(sources.meta).length) {
            html += '<h4 class="askagento-group-title">Meta Fields</h4>';
            $.each(sources.meta, function(k, s) {
                html += renderItem(s, existing);
            });
        }
        
        $('#askagento-sources').html(html || '<p class="askagento-loading">' + askagentoAdmin.i18n.noData + '</p>');
    }
    
    function renderItem(s, existing) {
        var disabled = existing.indexOf(s.source) !== -1;
        var cls = disabled ? ' disabled' : '';
        var dis = disabled ? ' disabled' : '';
        
        var samples = '';
        if (s.sample_values && s.sample_values.length) {
            samples = s.sample_values.slice(0, 3).join(', ');
        } else if (s.min_value !== null) {
            samples = s.min_value + ' — ' + s.max_value;
        }
        
        return '<div class="askagento-source-item' + cls + '" data-source="' + s.source + '" data-label="' + esc(s.label) + '" data-type="' + s.suggested_type + '">' +
            '<input type="checkbox"' + dis + '>' +
            '<div class="askagento-source-info">' +
                '<div class="askagento-source-name">' + esc(s.name) + ' <small>(' + esc(s.label) + ')</small></div>' +
                '<div class="askagento-source-meta">' + s.type + (samples ? ' • ' + samples : '') + '</div>' +
            '</div>' +
            '<div class="askagento-source-count">' + s.products_count + '</div>' +
        '</div>';
    }
    
    function getExisting() {
        var arr = [];
        $('.askagento-field').each(function() {
            arr.push($(this).find('input[name*="[source]"]').val());
        });
        return arr;
    }
    
    function filterSources(q) {
        q = q.toLowerCase();
        $('.askagento-source-item').each(function() {
            var match = $(this).data('source').toLowerCase().indexOf(q) !== -1 ||
                        $(this).data('label').toLowerCase().indexOf(q) !== -1;
            $(this).toggle(match);
        });
    }
    
    function updateAddBtn() {
        var n = $('.askagento-source-item.selected').length;
        $('#askagento-add-selected').prop('disabled', n === 0).text(n ? askagentoAdmin.i18n.addField + ' (' + n + ')' : askagentoAdmin.i18n.addField);
    }
    
    function addSelected() {
        var types = {checkbox: 'Checkbox', radio: 'Radio', dropdown: 'Dropdown', range: 'Range'};
        
        $('.askagento-source-item.selected').each(function() {
            var source = $(this).data('source');
            var label = $(this).data('label');
            var type = $(this).data('type');
            
            var html = $('#tmpl-askagento-field').html()
                .replace(/\{\{index\}\}/g, fieldIndex)
                .replace(/\{\{source\}\}/g, esc(source))
                .replace(/\{\{label\}\}/g, esc(label))
                .replace(/\{\{type\}\}/g, type)
                .replace(/\{\{type_label\}\}/g, types[type] || type);
            
            $('.askagento-no-fields').remove();
            $('#askagento-fields-list').append(html);
            
            $('#askagento-fields-list .askagento-field').last().find('.askagento-cfg-type').val(type);
            fieldIndex++;
        });
        
        closeModal();
    }
    
    function updateEmpty() {
        if (!$('.askagento-field').length) {
            $('#askagento-fields-list').html('<p class="askagento-no-fields">No fields. Click "Add Field" to start.</p>');
        }
    }
    
    function reindex() {
        $('.askagento-field').each(function(i) {
            $(this).attr('data-index', i);
            $(this).find('input[name^="askagento_fields"]').each(function() {
                $(this).attr('name', $(this).attr('name').replace(/askagento_fields\[\d+\]/, 'askagento_fields[' + i + ']'));
            });
        });
    }
    
    function esc(s) {
        return $('<div>').text(s).html();
    }
    
})(jQuery);
