// ISO_WorkAreaEndShortenByNFrames.jsx
// Artist: https://www.jasonfletcher.info/
// Code generated by ChatGPT-5
// Date: August 18, 2025
// Description: This After Effects script shortens the work area end point by a user-defined number of frames for selected comps in the Project window.

{
    function shortenWorkAreaByFrames() {
        var proj = app.project;
        if (!proj) return;

        var selectedItems = proj.selection;
        if (selectedItems.length === 0) {
            alert("Please select at least one comp in the Project panel.");
            return;
        }

        // Ask user for number of frames
        var frameInput = prompt("Enter number of frames to shorten the Work Area by:", "1");

        if (frameInput === null) {
            return;
        }

        var frames = parseInt(frameInput, 10);

        if (isNaN(frames) || frames <= 0) {
            alert("Please enter a valid positive number of frames.");
            return;
        }

        var processedComps = 0;

        app.beginUndoGroup("Shorten Work Area By Frames");

        for (var i = 0; i < selectedItems.length; i++) {
            var comp = selectedItems[i];

            if (comp instanceof CompItem) {
                var frameDuration = comp.frameDuration;
                var totalReduction = frameDuration * frames;

                var newWorkAreaEnd = comp.workAreaStart + comp.workAreaDuration - totalReduction;

                // Ensure we don't go shorter than workAreaStart
                if (newWorkAreaEnd > comp.workAreaStart) {
                    comp.workAreaDuration = newWorkAreaEnd - comp.workAreaStart;
                } else {
                    comp.workAreaDuration = frameDuration; // minimum 1 frame
                }

                processedComps++;
            }
        }

        app.endUndoGroup();

        alert(
            "Comps processed: " + processedComps + "\n" +
            "Frames shortened per comp: " + frames
        );
    }

    shortenWorkAreaByFrames();
}