/**
 * Persist changelist filters state (collapsed/expanded).
 */
'use strict';
{
    // Init filters.
    // 1. 初始化筛选器状态
    // 从sessionStorage中读取已保存的筛选器状态（键为"django.admin.filtersState"）
    // 若读取到数据，解析为JSON对象；若未读取到，后续会初始化为空对象
    let filters = JSON.parse(sessionStorage.getItem('django.admin.filtersState'));
    // 若sessionStorage中无筛选器状态数据，初始化filters为空对象
    if (!filters) {
        filters = {};
    }
    // 遍历已保存的筛选器状态，恢复每个筛选器的展开/折叠状态
    Object.entries(filters).forEach(([key, value]) => {
        // 根据筛选器标题（key）找到对应的筛选器元素（data-filter-title属性匹配）
        // CSS.escape用于转义特殊字符，避免选择器语法错误
        const detailElement = document.querySelector(`[data-filter-title='${CSS.escape(key)}']`);

        // Check if the filter is present, it could be from other view.
        if (detailElement) {
            value ? detailElement.setAttribute('open', '') : detailElement.removeAttribute('open');
        }
    });

    // Save filter state when clicks.
    // 2. 监听筛选器点击事件，实时保存状态
    // 获取页面中所有筛选器元素（通常是<details>标签，支持展开/折叠）
    const details = document.querySelectorAll('details');
    details.forEach(detail => {
        detail.addEventListener('toggle', event => {
            filters[`${event.target.dataset.filterTitle}`] = detail.open;
            sessionStorage.setItem('django.admin.filtersState', JSON.stringify(filters));
        });
    });
}
