// Isosceles_MakeSeamlessLoop.jsx
// Code generated by ChatGPT-5.3
// Date: March 12, 2026
// Description: This script will create a seamless loop (with user-defined crossfade length) for the selected comps in the project window. 
// IMPORTANT NOTE: You must precompose the main comp before executing this script.

(function () {

    var proj = app.project;

    if (!proj || proj.selection.length === 0) {
        alert("Select one or more comps in the Project panel.");
        return;
    }

    // Ask user for crossfade length
    var input = prompt("Enter crossfade length in frames:", "120");

    if (input === null) {
        return; // user cancelled
    }

    var fadeFrames = parseInt(input, 10);

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

    app.beginUndoGroup("Create Seamless Loop");

    for (var i = 0; i < proj.selection.length; i++) {

        var comp = proj.selection[i];

        if (!(comp instanceof CompItem)) {
            continue;
        }

        if (comp.numLayers < 1) {
            continue;
        }

        var fadeDur = fadeFrames / comp.frameRate;

        var baseLayer = comp.layer(1);

        var originalDuration = comp.duration;
        var newDuration = originalDuration - fadeDur;

        // Duplicate layer (top)
        var loopLayer = baseLayer.duplicate();
        loopLayer.moveBefore(baseLayer);

        // Bottom layer: remove first frames
        baseLayer.startTime -= fadeDur;
        baseLayer.inPoint = 0;
        baseLayer.outPoint = newDuration;

        // Top layer: first frames placed over end
        loopLayer.startTime = newDuration - fadeDur;
        loopLayer.inPoint = newDuration - fadeDur;
        loopLayer.outPoint = newDuration;

        // Crossfade (only top layer animated)
        var opacity = loopLayer.property("Transform").property("Opacity");

        opacity.setValueAtTime(newDuration - fadeDur, 0);
        opacity.setValueAtTime(newDuration, 100);

        // Adjust comp duration
        comp.duration = newDuration;
    }

    app.endUndoGroup();

})();