// Partial: _filter-engine.js.j2 — View mode filters, toggles, tree expand/collapse, tabs, legend

// ─────────────────────────────────────────────────────────────────────────────
// View Mode
// ─────────────────────────────────────────────────────────────────────────────

function setViewMode(mode) {
    state.viewMode = mode;

    // Update button states
    document.querySelectorAll('[data-view]').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.view === mode);
    });

    // Update label
    document.getElementById('view-mode-label').textContent =
        mode === 'flat' ? 'Flat View' : 'Hierarchical View';

    applyFilters();
}

// ─────────────────────────────────────────────────────────────────────────────
// Filter Toggles
// ─────────────────────────────────────────────────────────────────────────────

function toggleIndirectCoverage() {
    state.indirectCoverage = document.getElementById('toggle-indirect').checked;

    // Update coverage icons to reflect the active mode
    document.querySelectorAll('#table-body .req-row').forEach(row => {
        const cov = state.indirectCoverage ? row.dataset.coverageIndirect : row.dataset.coverage;
        const icon = row.querySelector('.coverage-icon');
        if (icon) {
            icon.className = 'coverage-icon ' + cov;
            if (cov === 'full') icon.textContent = '\u25CF';       // ●
            else if (cov === 'partial') icon.textContent = '\u25D0'; // ◐
            else icon.textContent = '\u25CB';                        // ○
        }
    });

    applyFilters();
    saveStateToCookie();
}

function toggleFilter(filter) {
    state.activeFilters[filter] = !state.activeFilters[filter];

    const btn = document.getElementById('btn-' + filter);
    if (btn) btn.classList.toggle('active', state.activeFilters[filter]);

    // Also update badges for files/associated
    const badge = document.getElementById('badge-' + filter);
    if (badge) badge.classList.toggle('active', state.activeFilters[filter]);

    applyFilters();
    saveStateToCookie();
}

function toggleLevelFilter(level) {
    const key = 'level' + level.charAt(0).toUpperCase() + level.slice(1).toLowerCase();
    state.activeFilters[key] = !state.activeFilters[key];

    // Update badge visual
    const badge = document.getElementById('badge-' + level.toLowerCase());
    if (badge) badge.classList.toggle('active', state.activeFilters[key]);

    // Clear dropdown when badge filters are used (badges hide, dropdown shows - they conflict)
    const anyBadgeActive = state.activeFilters.levelPrd || state.activeFilters.levelOps || state.activeFilters.levelDev;
    if (anyBadgeActive) {
        document.getElementById('filter-level').value = '';
    }

    applyFilters();
    saveStateToCookie();
}

function clearFilters() {
    // Reset all filters
    state.activeFilters = {
        uncommitted: false, changed: false, code: false, tests: false, results: false, associated: false, core: false,
        levelPrd: false, levelOps: false, levelDev: false
    };

    // Remove active class from buttons and badges
    document.querySelectorAll('.btn-group .btn').forEach(btn => {
        if (!btn.dataset.view) btn.classList.remove('active');
    });
    document.querySelectorAll('.stat-badge').forEach(badge => badge.classList.remove('active'));

    document.getElementById('filter-id').value = '';
    document.getElementById('filter-title').value = '';
    document.getElementById('filter-level').value = '';
    document.getElementById('filter-status').value = '';
    document.getElementById('filter-cov').value = '';
    document.getElementById('filter-topic').value = '';

    document.getElementById('toggle-leaf').checked = false;
    document.getElementById('toggle-deprecated').checked = false;
    document.getElementById('toggle-roadmap').checked = false;
    document.getElementById('toggle-code').checked = false;
    document.getElementById('toggle-indirect').checked = false;
    state.indirectCoverage = false;
    toggleIndirectCoverage(); // Reset coverage icons to strict mode

    applyFilters();
    saveStateToCookie();
}

// ─────────────────────────────────────────────────────────────────────────────
// Apply Filters
// ─────────────────────────────────────────────────────────────────────────────

function applyFilters() {
    const rows = document.querySelectorAll('#table-body .req-row');
    const filterIdValue = document.getElementById('filter-id').value.toLowerCase();
    const filterTitleValue = document.getElementById('filter-title').value.toLowerCase();
    const filterLevelValue = document.getElementById('filter-level').value;
    const filterStatusValue = document.getElementById('filter-status').value;
    const filterCovValue = document.getElementById('filter-cov').value;
    const filterTopicValue = document.getElementById('filter-topic').value;

    const leafOnly = document.getElementById('toggle-leaf').checked;
    const includeDeprecated = document.getElementById('toggle-deprecated').checked;
    const includeRoadmap = document.getElementById('toggle-roadmap').checked;
    const showCode = document.getElementById('toggle-code').checked;

    // Check if any level badge filters are active
    const levelBadgeFiltersActive = state.activeFilters.levelPrd ||
                                     state.activeFilters.levelOps ||
                                     state.activeFilters.levelDev;

    let visibleCount = 0;

    rows.forEach(row => {
        const id = row.dataset.id.toLowerCase();
        const level = row.dataset.level;
        const status = row.dataset.status;
        const coverage = state.indirectCoverage ? row.dataset.coverageIndirect : row.dataset.coverage;
        const topic = row.dataset.topic;
        const title = row.querySelector('.col-title')?.textContent.toLowerCase() || '';
        const isLeaf = row.dataset.isLeaf === 'true';
        const isChanged = row.dataset.isChanged === 'true';
        const isUncommitted = row.dataset.isUncommitted === 'true';
        const isRoadmap = row.dataset.isRoadmap === 'true';
        const isCode = row.dataset.isCode === 'true';
        const isTest = row.dataset.isTest === 'true';
        const isTestResult = row.dataset.isTestResult === 'true';
        const isAssociated = row.dataset.isAssociated === 'true';
        const depth = parseInt(row.dataset.depth);
        const parentId = row.dataset.parent;
        const isImplNode = isCode || isTest || isTestResult;  // Implementation/evidence nodes

        let visible = true;

        // Code badge filter - HIDE logic: code visible by default, hide when badge is active
        if (isCode && state.activeFilters.code) {
            visible = false;
        }

        // Tests badge filter - HIDE logic: tests visible by default, hide when badge is active
        if (isTest && state.activeFilters.tests) {
            visible = false;
        }

        // Results badge filter - SHOW logic: results hidden by default, show when badge is active
        if (isTestResult && !state.activeFilters.results) {
            visible = false;
        }

        // Text filters
        if (filterIdValue && !id.includes(filterIdValue)) visible = false;
        if (filterTitleValue && !title.includes(filterTitleValue)) visible = false;

        // Dropdown filters (level dropdown is separate from badge filters)
        if (filterLevelValue && !levelBadgeFiltersActive && level !== filterLevelValue) visible = false;
        if (filterStatusValue && status !== filterStatusValue) visible = false;
        if (filterCovValue && coverage !== filterCovValue) visible = false;
        if (filterTopicValue && topic !== filterTopicValue) visible = false;

        // Level badge filters (HIDE logic - hide if that level's filter is active)
        if (!isImplNode) {
            if (state.activeFilters.levelPrd && level === 'PRD') visible = false;
            if (state.activeFilters.levelOps && level === 'OPS') visible = false;
            if (state.activeFilters.levelDev && level === 'DEV') visible = false;
            // Associated filter - same HIDE logic as level filters
            if (state.activeFilters.associated && isAssociated) visible = false;
            // Core filter - HIDE logic: hide non-associated (core) requirements
            if (state.activeFilters.core && !isAssociated) visible = false;
        }

        // Toggle filters
        if (leafOnly && !isLeaf && !isImplNode) visible = false;
        if (!includeDeprecated && status === 'DEPRECATED') visible = false;
        if (!includeRoadmap && isRoadmap) visible = false;

        // Git filters
        if (state.activeFilters.uncommitted && !isUncommitted) visible = false;
        if (state.activeFilters.changed && !isChanged) visible = false;

        // Hierarchical mode: hide if parent is collapsed
        if (state.viewMode === 'hierarchical' && parentId && depth > 0) {
            if (isParentCollapsed(parentId)) {
                visible = false;
            }
        }

        // Flat mode: reset indentation visually
        if (state.viewMode === 'flat') {
            // In flat mode, all rows are at depth 0 visually
            // We keep the data but hide tree structure
            row.querySelectorAll('.tree-indent').forEach(indent => {
                indent.style.display = 'none';
            });
            row.querySelector('.tree-toggle')?.classList.add('leaf');
        } else {
            row.querySelectorAll('.tree-indent').forEach(indent => {
                indent.style.display = '';
            });
            const toggle = row.querySelector('.tree-toggle');
            if (toggle && row.dataset.hasChildren === 'true') {
                toggle.classList.remove('leaf');
            }
        }

        row.classList.toggle('hidden', !visible);
        if (visible && !isImplNode) visibleCount++;  // Only count requirements, not code/test
    });

    updateCounter(visibleCount);
    saveStateToCookie();
}

function isParentCollapsed(parentId) {
    if (!parentId) return false;
    if (state.collapsedNodes.has(parentId)) return true;

    // Check ancestors
    const parentRow = document.querySelector(`[data-id="${parentId}"]`);
    if (parentRow && parentRow.dataset.parent) {
        return isParentCollapsed(parentRow.dataset.parent);
    }
    return false;
}

function updateCounter(count) {
    document.getElementById('counter').textContent =
        `Showing ${count} of ${state.totalCount} requirements`;
}

// ─────────────────────────────────────────────────────────────────────────────
// Tree Expand/Collapse
// ─────────────────────────────────────────────────────────────────────────────

function toggleNode(nodeId) {
    const toggle = document.querySelector(`[data-node-id="${nodeId}"]`);
    if (!toggle) return;

    if (state.collapsedNodes.has(nodeId)) {
        state.collapsedNodes.delete(nodeId);
        toggle.classList.remove('collapsed');
        toggle.classList.add('expanded');
    } else {
        state.collapsedNodes.add(nodeId);
        toggle.classList.remove('expanded');
        toggle.classList.add('collapsed');
    }

    applyFilters();
}

function expandAll() {
    state.collapsedNodes.clear();
    document.querySelectorAll('.tree-toggle').forEach(toggle => {
        if (!toggle.classList.contains('leaf')) {
            toggle.classList.remove('collapsed');
            toggle.classList.add('expanded');
        }
    });
    applyFilters();
}

function collapseAll() {
    document.querySelectorAll('.tree-toggle').forEach(toggle => {
        if (!toggle.classList.contains('leaf')) {
            const nodeId = toggle.dataset.nodeId;
            state.collapsedNodes.add(nodeId);
            toggle.classList.remove('expanded');
            toggle.classList.add('collapsed');
        }
    });
    applyFilters();
}

// ─────────────────────────────────────────────────────────────────────────────
// Tabs
// ─────────────────────────────────────────────────────────────────────────────

function switchTab(tabName, save = true) {
    state.activeTab = tabName;

    // Update tab buttons
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.toggle('active', tab.dataset.tab === tabName);
    });

    // Switch tab content visibility
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    const activeContent = document.getElementById('content-' + tabName);
    if (activeContent) {
        activeContent.classList.add('active');
    }

    if (save) {
        saveStateToCookie();
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Legend Modal
// ─────────────────────────────────────────────────────────────────────────────

function toggleLegend() {
    const modal = document.getElementById('legend-modal');
    modal.classList.toggle('visible');
}

function closeLegendOnOverlay(event) {
    if (event.target === event.currentTarget) {
        toggleLegend();
    }
}
