/*global SelectBox, gettext, ngettext, interpolate, quickElement, SelectFilter*/
/*
SelectFilter2 - Turns a multiple-select box into a filter interface.

Requires core.js and SelectBox.js.
*/
'use strict';
{
    window.SelectFilter = {
        /**
         * 初始化双栏选择器
         * 生成“可选”“已选”双栏布局，绑定交互事件，初始化选项数据
         * @param {string} field_id - 原始多选框ID
         * @param {string} field_name - 字段名称（用于显示文本，如“文章”“标签”）
         * @param {boolean} is_stacked - 是否为堆叠布局（true=垂直堆叠，false=水平并列）
         */
        init: function(field_id, field_name, is_stacked) {
            // 跳过表单集模板中的字段（ID含__prefix__，未实际渲染）
            if (field_id.match(/__prefix__/)) {
                // Don't initialize on empty forms.
                return;
            }
            // 1. 处理原始多选框（转为“可选”栏）
            const from_box = document.getElementById(field_id);
            from_box.id += '_from'; // change its ID
            from_box.className = 'filtered';
            from_box.setAttribute('aria-labelledby', field_id + '_from_title');
            // 处理原始父容器中的文本（移除info文本，移动help文本到顶部）
            for (const p of from_box.parentNode.getElementsByTagName('p')) {
                if (p.classList.contains("info")) {
                    // Remove <p class="info">, because it just gets in the way.
                    from_box.parentNode.removeChild(p);
                } else if (p.classList.contains("help")) {
                    // Move help text up to the top so it isn't below the select
                    // boxes or wrapped off on the side to the right of the add
                    // button:
                    // 移动help文本到父容器最顶部（避免被遮挡）
                    from_box.parentNode.insertBefore(p, from_box.parentNode.firstChild);
                }
            }

            // <div class="selector"> or <div class="selector stacked">
            // 2. 生成核心容器结构
            // 2.1 主选择器容器（含双栏和操作按钮）
            const selector_div = quickElement('div', from_box.parentNode);
            // Make sure the selector div is at the beginning so that the
            // add link would be displayed to the right of the widget.
            from_box.parentNode.prepend(selector_div);
            selector_div.className = is_stacked ? 'selector stacked' : 'selector';

            // <div class="selector-available">
            // 2.2 “可选”栏容器（左侧/上方，未选择的选项）
            const selector_available = quickElement('div', selector_div);
            selector_available.className = 'selector-available';
            // “可选”栏标题区（含字段名称和帮助文本）
            const selector_available_title = quickElement('div', selector_available);
            selector_available_title.id = field_id + '_from_title';
            selector_available_title.className = 'selector-available-title';
            quickElement('label', selector_available_title, interpolate(gettext('Available %s') + ' ', [field_name]), 'for', field_id + '_from');
            quickElement(
                'p',
                selector_available_title,
                interpolate(gettext('Choose %s by selecting them and then select the "Choose" arrow button.'), [field_name]),
                'class', 'helptext'
            );
            // “可选”栏过滤输入框
            const filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter');
            filter_p.className = 'selector-filter';

            const search_filter_label = quickElement('label', filter_p, '', 'for', field_id + '_input');
            // 过滤图标（带悬浮提示）
            quickElement(
                'span', search_filter_label, '',
                'class', 'help-tooltip search-label-icon',
                'aria-label', interpolate(gettext("Type into this box to filter down the list of available %s."), [field_name])
            );

            filter_p.appendChild(document.createTextNode(' '));

            const filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter"));
            filter_input.id = field_id + '_input';

            selector_available.appendChild(from_box);
            const choose_all = quickElement(
                'button',
                selector_available,
                interpolate(gettext('Choose all %s'), [field_name]),
                'id', field_id + '_add_all',
                'class', 'selector-chooseall',
                'type', 'button'
            );

            // <ul class="selector-chooser">
            // 2.3 操作按钮容器（中间，转移选项的按钮）
            const selector_chooser = quickElement('ul', selector_div);
            selector_chooser.className = 'selector-chooser';
            // “选择选中项”按钮（可选→已选）
            const add_button = quickElement(
                'button',
                quickElement('li', selector_chooser),
                interpolate(gettext('Choose selected %s'), [field_name]),
                'id', field_id + '_add',
                'class', 'selector-add',
                'type', 'button'
            );
            const remove_button = quickElement(
                'button',
                quickElement('li', selector_chooser),
                interpolate(gettext('Remove selected %s'), [field_name]),
                'id', field_id + '_remove',
                'class', 'selector-remove',
                'type', 'button'
            );

            // <div class="selector-chosen">
            // 2.4 “已选”栏容器（右侧/下方，已选择的选项）
            const selector_chosen = quickElement('div', selector_div, '', 'id', field_id + '_selector_chosen');
            selector_chosen.className = 'selector-chosen';

            const selector_chosen_title = quickElement('div', selector_chosen);
            selector_chosen_title.className = 'selector-chosen-title';
            selector_chosen_title.id = field_id + '_to_title';
            quickElement('label', selector_chosen_title, interpolate(gettext('Chosen %s') + ' ', [field_name]), 'for', field_id + '_to');
            quickElement(
                'p',
                selector_chosen_title,
                interpolate(gettext('Remove %s by selecting them and then select the "Remove" arrow button.'), [field_name]),
                'class', 'helptext'
            );
            
            const filter_selected_p = quickElement('p', selector_chosen, '', 'id', field_id + '_filter_selected');
            filter_selected_p.className = 'selector-filter';

            const search_filter_selected_label = quickElement('label', filter_selected_p, '', 'for', field_id + '_selected_input');

            quickElement(
                'span', search_filter_selected_label, '',
                'class', 'help-tooltip search-label-icon',
                'aria-label', interpolate(gettext("Type into this box to filter down the list of selected %s."), [field_name])
            );

            filter_selected_p.appendChild(document.createTextNode(' '));

            const filter_selected_input = quickElement('input', filter_selected_p, '', 'type', 'text', 'placeholder', gettext("Filter"));
            filter_selected_input.id = field_id + '_selected_input';
            // 生成“已选”栏的多选框（最终提交给后端的字段）
            quickElement(
                'select',
                selector_chosen,
                '',
                'id', field_id + '_to',
                'multiple', '',
                'size', from_box.size,
                'name', from_box.name,
                'aria-labelledby', field_id + '_to_title',
                'class', 'filtered'
            );
            // “已选”栏隐藏选项提示区（过滤时显示隐藏的已选项数量）
            const warning_footer = quickElement('div', selector_chosen, '', 'class', 'list-footer-display');
            quickElement('span', warning_footer, '', 'id', field_id + '_list-footer-display-text');
            quickElement('span', warning_footer, ' ' + gettext('(click to clear)'), 'class', 'list-footer-display__clear');
            const clear_all = quickElement(
                'button',
                selector_chosen,
                interpolate(gettext('Remove all %s'), [field_name]),
                'id', field_id + '_remove_all',
                'class', 'selector-clearall',
                'type', 'button'
            );
            // 3. 调整原始多选框的名称（避免提交冲突）
            from_box.name = from_box.name + '_old';

            // Set up the JavaScript event handlers for the select box filter interface
            // 4. 绑定核心交互事件
            /**
             * 选项转移通用函数
             * @param {Event} e - 事件对象
             * @param {HTMLElement} elem - 触发事件的按钮
             * @param {Function} move_func - 转移函数（SelectBox.move/move_all）
             * @param {string} from - 源栏ID
             * @param {string} to - 目标栏ID
             */
            const move_selection = function(e, elem, move_func, from, to) {
                if (!elem.hasAttribute('disabled')) {
                    move_func(from, to);
                    SelectFilter.refresh_icons(field_id);
                    SelectFilter.refresh_filtered_selects(field_id);
                    SelectFilter.refresh_filtered_warning(field_id);
                }
                e.preventDefault();
            };
            // 绑定“全选”按钮（可选→已选）
            choose_all.addEventListener('click', function(e) {
                move_selection(e, this, SelectBox.move_all, field_id + '_from', field_id + '_to');
            });
            // 绑定“选择选中项”按钮（可选→已选）
            add_button.addEventListener('click', function(e) {
                move_selection(e, this, SelectBox.move, field_id + '_from', field_id + '_to');
            });
            // 绑定“移除选中项”按钮（已选→可选）
            remove_button.addEventListener('click', function(e) {
                move_selection(e, this, SelectBox.move, field_id + '_to', field_id + '_from');
            });
            // 绑定“全部移除”按钮（已选→可选）
            clear_all.addEventListener('click', function(e) {
                move_selection(e, this, SelectBox.move_all, field_id + '_to', field_id + '_from');
            });
            // 绑定“已选”栏过滤提示区点击事件（清空过滤）
            warning_footer.addEventListener('click', function(e) {
                filter_selected_input.value = '';
                SelectBox.filter(field_id + '_to', '');
                SelectFilter.refresh_filtered_warning(field_id);
                SelectFilter.refresh_icons(field_id);
            });
            // 绑定过滤输入框按键事件（可选栏）
            filter_input.addEventListener('keypress', function(e) {
                SelectFilter.filter_key_press(e, field_id, '_from', '_to');
            });
            filter_input.addEventListener('keyup', function(e) {
                SelectFilter.filter_key_up(e, field_id, '_from');
            });
            filter_input.addEventListener('keydown', function(e) {
                SelectFilter.filter_key_down(e, field_id, '_from', '_to');
            });
            // 绑定过滤输入框按键事件（已选栏）
            filter_selected_input.addEventListener('keypress', function(e) {
                SelectFilter.filter_key_press(e, field_id, '_to', '_from');
            });
            filter_selected_input.addEventListener('keyup', function(e) {
                SelectFilter.filter_key_up(e, field_id, '_to', '_selected_input');
            });
            filter_selected_input.addEventListener('keydown', function(e) {
                SelectFilter.filter_key_down(e, field_id, '_to', '_from');
            });
            selector_div.addEventListener('change', function(e) {
                if (e.target.tagName === 'SELECT') {
                    SelectFilter.refresh_icons(field_id);
                }
            });
            // 双击选项直接转移（可选→已选 或 已选→可选）
            selector_div.addEventListener('dblclick', function(e) {
                if (e.target.tagName === 'OPTION') {
                    if (e.target.closest('select').id === field_id + '_to') {
                        SelectBox.move(field_id + '_to', field_id + '_from');
                    } else {
                        SelectBox.move(field_id + '_from', field_id + '_to');
                    }
                    SelectFilter.refresh_icons(field_id);
                }
            });
            // 表单提交前处理：清空已选栏过滤，全选已选项（确保所有已选项提交）
            from_box.closest('form').addEventListener('submit', function() {
                SelectBox.filter(field_id + '_to', '');
                SelectBox.select_all(field_id + '_to');
            });
            // 5. 初始化SelectBox缓存（可选栏和已选栏
            SelectBox.init(field_id + '_from');
            SelectBox.init(field_id + '_to');
            // Move selected from_box options to to_box
            SelectBox.move(field_id + '_from', field_id + '_to');

            // Initial icon refresh
            // 6. 初始刷新按钮状态
            SelectFilter.refresh_icons(field_id);
        },
        /**
         * 判断选择框是否有选中项
         * @param {HTMLElement} field - 选择框元素
         * @return {boolean} true=有选中项，false=无选中项
         */
        any_selected: function(field) {
            // Temporarily add the required attribute and check validity.
            field.required = true;
            const any_selected = field.checkValidity();
            field.required = false;
            return any_selected;
        },
        /**
         * 刷新“已选”栏的隐藏选项提示
         * 显示过滤后隐藏的已选项数量，无隐藏项则隐藏提示
         * @param {string} field_id - 字段ID前缀
         */
        refresh_filtered_warning: function(field_id) {
            const count = SelectBox.get_hidden_node_count(field_id + '_to');
            const selector = document.getElementById(field_id + '_selector_chosen');
            const warning = document.getElementById(field_id + '_list-footer-display-text');
            // 移除“有隐藏项”样式
            selector.className = selector.className.replace('selector-chosen--with-filtered', '');
            warning.textContent = interpolate(ngettext(
                '%s selected option not visible',
                '%s selected options not visible',
                count
            ), [count]);
            if(count > 0) {
                selector.className += ' selector-chosen--with-filtered';
            }
        },
        /**
         * 刷新双栏的过滤状态
         * 同步两个栏的过滤输入值到SelectBox
         * @param {string} field_id - 字段ID前缀
         */
        refresh_filtered_selects: function(field_id) {
            // 同步可选栏过滤值
            SelectBox.filter(field_id + '_from', document.getElementById(field_id + "_input").value);
            // 同步已选栏过滤值
            SelectBox.filter(field_id + '_to', document.getElementById(field_id + "_selected_input").value);
        },
        /**
         * 刷新操作按钮的禁用状态
         * 根据选择框是否有选项/选中项，启用或禁用按钮
         * @param {string} field_id - 字段ID前缀
         */
        refresh_icons: function(field_id) {
            const from = document.getElementById(field_id + '_from');
            const to = document.getElementById(field_id + '_to');
            // Disabled if no items are selected.
            document.getElementById(field_id + '_add').disabled = !SelectFilter.any_selected(from);
            document.getElementById(field_id + '_remove').disabled = !SelectFilter.any_selected(to);
            // Disabled if the corresponding box is empty.
            document.getElementById(field_id + '_add_all').disabled = !from.querySelector('option');
            document.getElementById(field_id + '_remove_all').disabled = !to.querySelector('option');
        },
        /**
         * 过滤输入框按键按下事件（Enter键处理）
         * 按下Enter时，转移当前选中项
         * @param {Event} event - 事件对象
         * @param {string} field_id - 字段ID前缀
         * @param {string} source - 源栏后缀（_from/_to）
         * @param {string} target - 目标栏后缀（_to/_from）
         */
        filter_key_press: function(event, field_id, source, target) {
            const source_box = document.getElementById(field_id + source);
            // don't submit form if user pressed Enter
            if ((event.which && event.which === 13) || (event.keyCode && event.keyCode === 13)) {
                source_box.selectedIndex = 0;
                SelectBox.move(field_id + source, field_id + target);
                source_box.selectedIndex = 0;
                event.preventDefault();
            }
        },
        /**
         * 过滤输入框按键抬起事件（实时过滤）
         * 输入内容变化时，实时过滤选项
         * @param {Event} event - 事件对象
         * @param {string} field_id - 字段ID前缀
         * @param {string} source - 源栏后缀（_from/_to）
         * @param {string} [filter_input] - 过滤输入框后缀（默认_input）
         */
        filter_key_up: function(event, field_id, source, filter_input) {
            const input = filter_input || '_input';
            const source_box = document.getElementById(field_id + source);
            const temp = source_box.selectedIndex;
            SelectBox.filter(field_id + source, document.getElementById(field_id + input).value);
            source_box.selectedIndex = temp;
            SelectFilter.refresh_filtered_warning(field_id);
            SelectFilter.refresh_icons(field_id);
        },
        /**
         * 过滤输入框按键按下事件（方向键处理）
         * 支持方向键转移选项、上下键切换选中项
         * @param {Event} event - 事件对象
         * @param {string} field_id - 字段ID前缀
         * @param {string} source - 源栏后缀（_from/_to）
         * @param {string} target - 目标栏后缀（_to/_from）
         */
        filter_key_down: function(event, field_id, source, target) {
            const source_box = document.getElementById(field_id + source);
            // right key (39) or left key (37)
            const direction = source === '_from' ? 39 : 37;
            // right arrow -- move across
            if ((event.which && event.which === direction) || (event.keyCode && event.keyCode === direction)) {
                const old_index = source_box.selectedIndex;
                SelectBox.move(field_id + source, field_id + target);
                SelectFilter.refresh_filtered_selects(field_id);
                SelectFilter.refresh_filtered_warning(field_id);
                source_box.selectedIndex = (old_index === source_box.length) ? source_box.length - 1 : old_index;
                return;
            }
            // down arrow -- wrap around
            if ((event.which && event.which === 40) || (event.keyCode && event.keyCode === 40)) {
                source_box.selectedIndex = (source_box.length === source_box.selectedIndex + 1) ? 0 : source_box.selectedIndex + 1;
            }
            // up arrow -- wrap around
            if ((event.which && event.which === 38) || (event.keyCode && event.keyCode === 38)) {
                source_box.selectedIndex = (source_box.selectedIndex === 0) ? source_box.length - 1 : source_box.selectedIndex - 1;
            }
        }
    };
    // 页面加载完成后，初始化所有SelectFilter组件
    window.addEventListener('load', function(e) {
        document.querySelectorAll('select.selectfilter, select.selectfilterstacked').forEach(function(el) {
            const data = el.dataset;
            SelectFilter.init(el.id, data.fieldName, parseInt(data.isStacked, 10));
        });
    });
}
