// Archive grouping/sorting helpers — ZDDC parsing comes from window.zddc directly.
(function() {
    'use strict';

    function isTransmittalFolder(name) {
        var parsed = zddc.parseFolder(name);
        return !!(parsed && parsed.valid);
    }

    function groupFilesByTrackingNumber(files) {
        const groups = {};
        files.forEach(file => {
            if (!file.trackingNumber) return;
            if (!groups[file.trackingNumber]) {
                groups[file.trackingNumber] = { trackingNumber: file.trackingNumber, title: file.title, revisions: {} };
            }
            if (file.title.length > groups[file.trackingNumber].title.length) {
                groups[file.trackingNumber].title = file.title;
            }
            const revKey = `${file.revision}_${file.status}`;
            if (!groups[file.trackingNumber].revisions[revKey]) {
                groups[file.trackingNumber].revisions[revKey] = {
                    revision: file.revision, status: file.status, title: file.title,
                    hasModifier: file.revision.includes('+'), files: []
                };
            }
            if (file.title.length > groups[file.trackingNumber].revisions[revKey].title.length) {
                groups[file.trackingNumber].revisions[revKey].title = file.title;
            }
            groups[file.trackingNumber].revisions[revKey].files.push(file);
        });
        return groups;
    }

    function sortGroupedFiles(groups) {
        const field = window.app.sortField || 'trackingNumber';
        const direction = window.app.sortDirection === 'desc' ? -1 : 1;
        const sorted = Object.values(groups).sort((a, b) => {
            let comparison = 0;
            if (field === 'trackingNumber') comparison = a.trackingNumber.localeCompare(b.trackingNumber);
            else if (field === 'title') comparison = a.title.localeCompare(b.title);
            else if (field === 'revisions') {
                const aRevs = Object.keys(a.revisions), bRevs = Object.keys(b.revisions);
                comparison = zddc.compareRevisions(
                    aRevs.length > 0 ? aRevs[aRevs.length - 1] : '',
                    bRevs.length > 0 ? bRevs[bRevs.length - 1] : ''
                );
            }
            return comparison * direction;
        });
        sorted.forEach(group => {
            const revisions = Object.values(group.revisions);
            revisions.sort((a, b) => zddc.compareRevisions(b.revision, a.revision));
            group.sortedRevisions = revisions;
        });
        return sorted;
    }

    window.app.modules.parser = {
        isTransmittalFolder,
        groupFilesByTrackingNumber,
        sortGroupedFiles,
    };

})();
