// Filename: frontend/js/components/filterPopover.js

import { createPopper } from '../vendor/popper.esm.min.js';

export default class FilterPopover {
    constructor(triggerElement, options, title) {
        if (!triggerElement || typeof createPopper !== 'function') {
            console.error('FilterPopover: Trigger element or Popper.js not found.');
            return;
        }
        this.triggerElement = triggerElement;
        this.options = options;
        this.title = title;
        this.selectedValues = new Set();

        this._createPopoverHTML();
        this.popperInstance = createPopper(this.triggerElement, this.popoverElement, {
            placement: 'bottom-start',
            modifiers: [{ name: 'offset', options: { offset: [0, 8] } }],
        });

        this._bindEvents();
    }

    _createPopoverHTML() {
        this.popoverElement = document.createElement('div');
        this.popoverElement.className = 'hidden z-50 min-w-[12rem] rounded-md border bg-popover bg-white dark:bg-zinc-800 p-2 text-popover-foreground shadow-md';
        this.popoverElement.innerHTML = `
            <div class="px-2 py-1.5 text-sm font-semibold">${this.title}</div>
            <div class="space-y-1 p-1">
                ${this.options.map(option => `
                    <label class="flex items-center space-x-2 px-2 py-1.5 rounded-md hover:bg-accent cursor-pointer">
                        <input type="checkbox" value="${option.value}" class="h-4 w-4 rounded border-zinc-300 text-blue-600 focus:ring-blue-500">
                        <span class="text-sm">${option.label}</span>
                    </label>
                `).join('')}
            </div>
            <div class="border-t border-border mt-2 pt-2 px-2 flex justify-end space-x-2">
                 <button data-action="clear" class="btn btn-ghost h-7 px-2 text-xs">清空</button>
                 <button data-action="apply" class="btn btn-primary h-7 px-2 text-xs">应用</button>
            </div>
        `;
        document.body.appendChild(this.popoverElement);
    }

    _bindEvents() {
        this.triggerElement.addEventListener('click', () => this.toggle());

        document.addEventListener('click', (event) => {
            if (!this.popoverElement.contains(event.target) && !this.triggerElement.contains(event.target)) {
                this.hide();
            }
        });

        this.popoverElement.addEventListener('click', (event) => {
            const target = event.target.closest('button');
            if (!target) return;
            const action = target.dataset.action;
            if (action === 'clear') this._handleClear();
            if (action === 'apply') this._handleApply();
        });
    }

    _handleClear() {
        this.popoverElement.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
        this.selectedValues.clear();
        this._handleApply();
    }

    _handleApply() {
        this.selectedValues.clear();
        this.popoverElement.querySelectorAll('input:checked').forEach(cb => {
            this.selectedValues.add(cb.value);
        });

        const filterChangeEvent = new CustomEvent('filter-change', {
            detail: {
                filterKey: this.triggerElement.id,
                selected: this.selectedValues
            }
        });
        this.triggerElement.dispatchEvent(filterChangeEvent);

        this.hide();
    }

    toggle() {
        this.popoverElement.classList.toggle('hidden');
        this.popperInstance.update();
    }

    hide() {
        this.popoverElement.classList.add('hidden');
    }
}
