export async function initSequencePage() {

    const listContainer = document.getElementById('sequence-list') || document.getElementById('ablauf-list');
    const filterChips = document.querySelectorAll('.filter-chip');

    if (!listContainer) {
        console.warn('Sequence container not found.');
        return;
    }

    try {
        const response = await fetch('data/sequence/sequence.json');
        if (!response.ok) throw new Error('Sequence data could not be loaded.');

        const sequenceSteps = await response.json();

        renderSequenceList(listContainer, sequenceSteps);
        setupFilterLogic(filterChips);

    } catch (error) {
        console.error('Error loading sequence:', error);
        listContainer.innerHTML = '<p>Sequence could not be loaded.</p>';
    }
}

function renderSequenceList(container, steps) {
    container.innerHTML = '';

    steps.forEach(step => {
        const item = document.createElement('div');
        item.className = 'ablauf-item';
        item.dataset.categories = step.categories.join(',');

        item.innerHTML = `
            <button class="sequence-header">
                <span class="sequence-title">${step.title}</span>
                <i data-lucide="chevron-down" class="ablauf-arrow"></i>
            </button>
            <div class="sequence-content">
                <p class="loading">Loading...</p>
            </div>
        `;

        const header = item.querySelector('.sequence-header');
        const contentDiv = item.querySelector('.sequence-content');
        let isLoaded = false;

        header.addEventListener('click', async () => {
            item.classList.toggle('active');

            if (item.classList.contains('active') && !isLoaded) {
                try {
                    const contentResponse = await fetch(`data/sequence/${step.file}`);
                    if (!contentResponse.ok) throw new Error('Content not found.');

                    const htmlContent = await contentResponse.text();
                    contentDiv.innerHTML = htmlContent;
                    isLoaded = true;
                } catch (err) {
                    console.error(err);
                    contentDiv.innerHTML = '<p>Content could not be loaded.</p>';
                }
            }
        });

        container.appendChild(item);
    });

}

function setupFilterLogic(filterChips) {
    if (!filterChips || filterChips.length === 0) return;

    let activeFilters = new Set(['alle']);

    function applyFilters() {
        document.querySelectorAll('.ablauf-item').forEach(item => {
            const categories = item.dataset.categories ? item.dataset.categories.split(',') : [];

            const isVisible = activeFilters.has('alle') ||
                categories.some(cat => activeFilters.has(cat));

            item.style.display = isVisible ? '' : 'none';
        });
    }

    filterChips.forEach(chip => {
        chip.addEventListener('click', () => {
            const filter = chip.dataset.filter;

            if (filter === 'alle') {
                activeFilters = new Set(['alle']);
                filterChips.forEach(c => c.classList.remove('active'));
                chip.classList.add('active');
            } else {
                if (activeFilters.has('alle')) {
                    activeFilters.delete('alle');
                    document.querySelector('.filter-chip[data-filter="alle"]')?.classList.remove('active');
                }

                if (activeFilters.has(filter)) {
                    activeFilters.delete(filter);
                    chip.classList.remove('active');
                } else {
                    activeFilters.add(filter);
                    chip.classList.add('active');
                }

                if (activeFilters.size === 0) {
                    activeFilters.add('alle');
                    document.querySelector('.filter-chip[data-filter="alle"]')?.classList.add('active');
                }
            }

            applyFilters();
        });
    });

    applyFilters();
}