// Partial: _journey-engine.js.j2 — Journey filtering, grouping, and navigation

// Store original card order for ungrouping
let originalJourneyCards = null;
let collapsedJourneyGroups = new Set();

function filterJourneys() {
    const searchInput = document.getElementById('journey-search');
    const query = searchInput.value.toLowerCase().trim();

    // Filter both ungrouped cards and cards within groups
    const allCards = document.querySelectorAll('.journey-card');
    let visibleCount = 0;

    allCards.forEach(card => {
        if (!query) {
            card.classList.remove('hidden');
            visibleCount++;
            return;
        }

        const id = card.dataset.id || '';
        const title = card.dataset.title || '';
        const actor = card.dataset.actor || '';
        const goal = card.dataset.goal || '';
        const descriptor = card.dataset.descriptor || '';
        const file = card.dataset.file || '';
        const refs = card.dataset.refs || '';

        const matches = id.includes(query) ||
                        title.includes(query) ||
                        actor.includes(query) ||
                        goal.includes(query) ||
                        descriptor.includes(query) ||
                        file.includes(query) ||
                        refs.includes(query);

        card.classList.toggle('hidden', !matches);
        if (matches) visibleCount++;
    });

    // Update group counts if grouped
    updateGroupCounts();

    // Update visible count
    const countEl = document.getElementById('journey-visible-count');
    if (countEl) {
        countEl.textContent = visibleCount;
    }

    saveStateToCookie();
}

function updateGroupCounts() {
    const groups = document.querySelectorAll('.journey-group');
    groups.forEach(group => {
        const visibleCards = group.querySelectorAll('.journey-card:not(.hidden)');
        const countEl = group.querySelector('.journey-group-count');
        if (countEl) {
            countEl.textContent = visibleCards.length;
        }
        // Hide group if no visible cards
        group.style.display = visibleCards.length === 0 ? 'none' : '';
    });
}

function regroupJourneys() {
    const groupBy = document.getElementById('journey-group-by').value;
    const journeyList = document.getElementById('journey-list');

    // Store original cards on first grouping
    if (!originalJourneyCards) {
        originalJourneyCards = Array.from(journeyList.querySelectorAll('.journey-card'));
    }

    // Clear current content
    journeyList.innerHTML = '';

    if (groupBy === 'none') {
        // Restore ungrouped view
        originalJourneyCards.forEach(card => {
            card.classList.remove('compact');
            journeyList.appendChild(card);
        });
    } else {
        // Group cards by selected attribute
        const groups = new Map();

        originalJourneyCards.forEach(card => {
            let key = card.dataset[groupBy] || '(none)';
            // Capitalize first letter
            if (key !== '(none)') {
                key = key.charAt(0).toUpperCase() + key.slice(1);
            }

            if (!groups.has(key)) {
                groups.set(key, []);
            }
            groups.get(key).push(card);
        });

        // Sort groups alphabetically, but put (none) last
        const sortedKeys = Array.from(groups.keys()).sort((a, b) => {
            if (a === '(none)') return 1;
            if (b === '(none)') return -1;
            return a.localeCompare(b);
        });

        // Create group elements
        sortedKeys.forEach(key => {
            const cards = groups.get(key);
            const groupEl = document.createElement('div');
            groupEl.className = 'journey-group';
            groupEl.dataset.groupKey = key.toLowerCase();

            // Check if this group was previously collapsed
            if (collapsedJourneyGroups.has(key.toLowerCase())) {
                groupEl.classList.add('collapsed');
            }

            const header = document.createElement('div');
            header.className = 'journey-group-header';
            header.onclick = () => toggleJourneyGroup(groupEl);
            header.innerHTML = `
                <span class="expand-icon">▼</span>
                <h4>${key}</h4>
                <span class="journey-group-count">${cards.length}</span>
            `;

            const cardsContainer = document.createElement('div');
            cardsContainer.className = 'journey-group-cards';

            cards.forEach(card => {
                card.classList.add('compact');
                cardsContainer.appendChild(card);
            });

            groupEl.appendChild(header);
            groupEl.appendChild(cardsContainer);
            journeyList.appendChild(groupEl);
        });
    }

    // Re-apply search filter
    filterJourneys();
    saveStateToCookie();
}

function toggleJourneyGroup(groupEl) {
    groupEl.classList.toggle('collapsed');
    const key = groupEl.dataset.groupKey;

    if (groupEl.classList.contains('collapsed')) {
        collapsedJourneyGroups.add(key);
    } else {
        collapsedJourneyGroups.delete(key);
    }

    saveStateToCookie();
}

function expandAllJourneyGroups() {
    document.querySelectorAll('.journey-group').forEach(group => {
        group.classList.remove('collapsed');
    });
    collapsedJourneyGroups.clear();
    saveStateToCookie();
}

function collapseAllJourneyGroups() {
    document.querySelectorAll('.journey-group').forEach(group => {
        group.classList.add('collapsed');
        collapsedJourneyGroups.add(group.dataset.groupKey);
    });
    saveStateToCookie();
}

// ─────────────────────────────────────────────────────────────────────────────
// Journey → Requirement Navigation
// ─────────────────────────────────────────────────────────────────────────────

function switchToReqTab(reqId) {
    switchTab('requirements');
    setTimeout(function() {
        var row = document.querySelector('tr.req-row[data-id="' + reqId + '"]');
        if (!row) return;
        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
        row.style.transition = 'none';
        row.style.backgroundColor = '#ffc107';
        setTimeout(function() {
            row.style.transition = 'background-color 1.5s ease';
            row.style.backgroundColor = '';
        }, 200);
    }, 100);
}
