// ISO_PrecompLayersInPairs.jsx
// Artist: https://www.jasonfletcher.info/
// Code generated by ChatGPT-5.5
// Date: July 24, 2026
// Description: This After Effects script will precompose the layers within the active comp into sequential pairs (1-2, 3-4, 5-6, and so forth).

(function () {

    app.beginUndoGroup("Precompose Layers In Pairs");

    try {

        var activeItem = app.project.activeItem;
        var comp;
        var totalLayers;
        var pairCount = 0;
        var skippedOddLayer = false;
        var folder;
        var i;
        var layerIndices;
        var precompName;
        var newComp;

        if (!(activeItem instanceof CompItem)) {
            alert("Please make a composition active in the Timeline before running this script.");
            return;
        }

        comp = activeItem;
        totalLayers = comp.numLayers;

        if (totalLayers < 2) {
            alert("The active composition must contain at least two layers.");
            return;
        }

        // Always create a new folder named "Precomped"
        folder = app.project.items.addFolder("Precomped");

        // Process from the bottom upward so layer indices remain valid.
        for (i = totalLayers - 1; i >= 1; i -= 2) {

            layerIndices = [i, i + 1];

            pairCount++;
            precompName = "Precomp_" + ("000" + pairCount).substr(-3);

            comp.layers.precompose(
                layerIndices,
                precompName,
                true // Move all attributes into the new composition
            );

            newComp = comp.layer(i).source;

            if (newComp !== null && newComp instanceof CompItem) {
                newComp.parentFolder = folder;
            }
        }

        if ((totalLayers % 2) !== 0) {
            skippedOddLayer = true;
        }

        alert(
            "Finished precomping layers.\n\n" +
            "Composition: " + comp.name + "\n" +
            "Pairs precomped: " + pairCount + "\n" +
            "Project folder created: Precomped\n" +
            "Odd layer left unchanged: " + (skippedOddLayer ? "Yes" : "No")
        );

    } catch (err) {

        alert(
            "An error occurred:\n\n" +
            err.toString()
        );

    } finally {

        app.endUndoGroup();

    }

})();