#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(round);
use File::Path qw(make_path);
use Tk;
use Tk::JPEG;
use Tk::PNG;
use Tk qw(Ev);
use Image::Imlib2;
use feature 'say';
# --------------------------------------------------
# DIRECTORIES
# --------------------------------------------------

my $dir = "GUIDE";
make_path($dir) unless -d $dir;

my $img_dir = "images";
my @images;
my $image_index = 0;

# Try to load initial list from images/ if it exists
if (-d $img_dir) {
    opendir(my $dh, $img_dir);
    if ($dh) {
        @images = sort grep { /\.(?:jpe?g|png)$/i } readdir($dh);
        closedir $dh;
    }
}

# --------------------------------------------------
# SETTINGS
# --------------------------------------------------

my $canvas_w = 1955;
my $canvas_h = 1100;

my $play_w = 1072;
my $play_h = 603;

my $fps = 25;
my $delay = int(1000 / $fps);

# Aspect ratio (width / height). 16/9 ≈ 1.777...
# Can be changed from the GUI; default is 16:9.
my $ratio = 16 / 9;

# --------------------------------------------------
# DEFAULT VALUES
# --------------------------------------------------

my %vars = (
    viewer_w => 1072,
    viewer_h => 603,
    ratio    => 16 / 9,   # width / height
    filename => 'pan_test',
    frames   => 100,

    # Track timing + style (start/end/length are linked)
    track_style  => 'cosine',
    track_start  => 0,
    track_end    => 100,
    track_length => 100,
    track_ease_front => 20,   # % of window for ease-in
    track_ease_rear  => 20,   # % of window for ease-out

    # Zoom timing + style
    zoom_style   => 'linear',
    zoom_start   => 0,
    zoom_end     => 100,
    zoom_length  => 100,
    zoom_ease_front  => 0,
    zoom_ease_rear   => 0,

    start_x  => -400,
    start_y  => 0,
    start_w  => 160,
    start_h  => 90,

    end_x    => 400,
    end_y    => 0,
    end_w    => 160,
    end_h    => 90,

    # Curve control
    use_curve => 0,

    # Playback visualization
    blackout => 0,   # 0 = thin outline, 1 = solid black outside rectangle
);

# --------------------------------------------------
# WINDOWS
# --------------------------------------------------

my $mw = MainWindow->new;
$mw->title("Camera Movement Experiment");
$mw->optionAdd('*font', ['Helvetica', 14]);
$mw->optionAdd('*Dialog*font', ['Helvetica', 14]);
$mw->optionAdd('*FileSelect*font', ['Helvetica', 14]);
$mw->optionAdd('*Listbox*font', ['Helvetica', 14]);
$mw->optionAdd('*Entry*font', ['Helvetica', 14]);

my $editor = $mw->Toplevel;
$editor->title("Photograph Editor");

# --------------------------------------------------
# VARIABLES
# --------------------------------------------------

my @frames;

# Cached preview data
# @preview_crops  = Imlib2 images of the exact cropped regions (source resolution)
# @preview_photos = Tk Photos scaled to current viewer size
my @preview_crops;
my @preview_photos;
my $preview_vw = 0;
my $preview_vh = 0;

my $current = 0;
my $playing = 0;
my $after_id;

my $photo;
my $play_photo;

my $photo_id;
my $play_photo_id;

# Cached scaled photo for the viewer (avoids re-scaling every frame)
my $scaled_photo;
my $scaled_scale = 0;

my $image_name_label;
my $frame_label;

my $rect_start;
my $rect_end;

my $image_width = 0;
my $image_height = 0;

my $drag;

# Curve point (absolute image coordinates the centre should pass through)
my $curve_cx;
my $curve_cy;
my $curve_dot;

# --------------------------------------------------
# MAIN WINDOW CONTROLS
# --------------------------------------------------

my $controls = $mw->Frame;
$controls->grid(
    -row => 0,
    -column => 0,
    -sticky => 'ew',
    -padx => 5,
    -pady => 5
);

my @fields_top = (
    [filename => 'Filename'],
    [frames   => 'Frames'],
    [ratio    => 'Ratio W/H'],
    [viewer_w => 'Viewer W'],
    [viewer_h => 'Viewer H'],

    [start_x  => 'Start X'],
    [start_y  => 'Start Y'],
    [start_w  => 'Start W'],
    [start_h  => 'Start H'],

    [end_x    => 'End X'],
    [end_y    => 'End Y'],
    [end_w    => 'End W'],
    [end_h    => 'End H'],
);

my @fields_bottom = (
    [track_style      => 'Track Style'],
    [track_start      => 'Track Start'],
    [track_end        => 'Track End'],
    [track_length     => 'Track Len'],
    [track_ease_front => 'Track Ease Front %'],
    [track_ease_rear  => 'Track Ease Rear %'],

    [zoom_style       => 'Zoom Style'],
    [zoom_start       => 'Zoom Start'],
    [zoom_end         => 'Zoom End'],
    [zoom_length      => 'Zoom Len'],
    [zoom_ease_front  => 'Zoom Ease Front %'],
    [zoom_ease_rear   => 'Zoom Ease Rear %'],
);

my %entries;

sub build_field_row {
    my ($parent, $fields, $row) = @_;
    my $col = 0;
    for my $field (@$fields) {
        my ($key, $label) = @$field;
        $parent->Label(
            -text => $label,
            -font => ['Helvetica', 14],
        )->grid(-row => $row, -column => $col, -padx => 2, -pady => 1);

        my $e = $parent->Entry(
            -textvariable => \$vars{$key},
            -width => 9,
            -font => ['Helvetica', 14],
        );
        $e->grid(-row => $row + 1, -column => $col, -padx => 2, -pady => 1);
        $entries{$key} = $e;
        $col++;
    }
}

build_field_row($controls, \@fields_top,    0);
build_field_row($controls, \@fields_bottom, 2);

# Replace style text fields with dropdowns
my @style_options = qw(linear cosine smoothstep cubic);
for my $key (qw(track_style zoom_style)) {
    next unless $entries{$key};
    my $old = $entries{$key};
    my $info = $old->gridInfo;
    # gridInfo can return a list or a hashref depending on context/Tk version
    my %grid_opts = ref($info) eq 'HASH' ? %$info : @$info;
    $old->gridForget;
    $old->destroy;

    my $om = $controls->Optionmenu(
        -options => \@style_options,
        -textvariable => \$vars{$key},
        -font => ['Helvetica', 12],
        -width => 10,
    );
    $om->grid(%grid_opts);
    $entries{$key} = $om;
}

# --------------------------------------------------
# LINK start / end / length  (only need to set two)
# --------------------------------------------------

sub sync_timing {
    my ($prefix, $changed) = @_;   # prefix = 'track' or 'zoom'
    return if $sync_timing::busy;
    local $sync_timing::busy = 1;

    my $s = $vars{"${prefix}_start"};
    my $e = $vars{"${prefix}_end"};
    my $l = $vars{"${prefix}_length"};

    # Treat non-numeric as 0 for safety
    $s = 0 unless defined $s && $s =~ /^-?\d+$/;
    $e = 0 unless defined $e && $e =~ /^-?\d+$/;
    $l = 0 unless defined $l && $l =~ /^-?\d+$/;

    if ($changed eq 'start' || $changed eq 'end') {
        $vars{"${prefix}_length"} = $e - $s;
    }
    elsif ($changed eq 'length') {
        $vars{"${prefix}_end"} = $s + $l;
    }
    elsif ($changed eq 'start_len') {   # if we ever need it
        $vars{"${prefix}_end"} = $s + $l;
    }
}

# Bind the timing fields
for my $prefix (qw(track zoom)) {
    for my $which (qw(start end length)) {
        my $key = "${prefix}_$which";
        next unless $entries{$key};
        $entries{$key}->bind('<Return>' => sub { sync_timing($prefix, $which) });
        $entries{$key}->bind('<FocusOut>' => sub { sync_timing($prefix, $which) });
    }
}


# --------------------------------------------------
# LINK VIEWER W / H TO RATIO (16:9 for now)
# Changing one field updates the other to match $ratio_w:$ratio_h
# Structured so ratio can later become GUI-controlled without rewrite
# --------------------------------------------------

sub sync_viewer_size {
    my ($source) = @_;   # 'w' or 'h'

    return if $sync_viewer_size::busy;
    local $sync_viewer_size::busy = 1;

    my $r = $vars{ratio};
    return unless defined $r && $r > 0;

    if ($source eq 'w') {
        my $w = $vars{viewer_w};
        return unless defined $w && $w =~ /^\d+$/ && $w > 0;
        $vars{viewer_h} = round($w / $r);
    }
    elsif ($source eq 'h') {
        my $h = $vars{viewer_h};
        return unless defined $h && $h =~ /^\d+$/ && $h > 0;
        $vars{viewer_w} = round($h * $r);
    }
}

# Bind Return / FocusOut so typing updates the other field
if ($entries{viewer_w}) {
    $entries{viewer_w}->bind('<Return>' => sub { sync_viewer_size('w') });
    $entries{viewer_w}->bind('<FocusOut>' => sub { sync_viewer_size('w') });
}
if ($entries{viewer_h}) {
    $entries{viewer_h}->bind('<Return>' => sub { sync_viewer_size('h') });
    $entries{viewer_h}->bind('<FocusOut>' => sub { sync_viewer_size('h') });
}
if ($entries{ratio}) {
    $entries{ratio}->bind('<Return>' => sub { sync_viewer_size('w') });
    $entries{ratio}->bind('<FocusOut>' => sub { sync_viewer_size('w') });
}

my $buttons = $mw->Frame;
$buttons->grid(
    -row => 1,
    -column => 0,
    -sticky => 'ew',
    -padx => 5,
    -pady => 5
);

# --------------------------------------------------
# PLAYBACK CANVAS
# --------------------------------------------------

my $play_canvas = $mw->Canvas(
    -width => $play_w,
    -height => $play_h,
    -background => 'black',
    -highlightthickness => 0
);

$play_canvas->grid(
    -row => 2,
    -column => 0,
    -padx => 5,
    -pady => 5
);

# --------------------------------------------------
# EDITOR CANVAS AND SCROLLBARS
# --------------------------------------------------

my $editor_frame = $editor->Frame;
$editor_frame->pack(-fill => 'both', -expand => 1);

my $editor_canvas = $editor_frame->Canvas(
    -width => 1200,
    -height => 800,
    -background => 'black',
    -highlightthickness => 0,
    -scrollregion => [0, 0, $canvas_w, $canvas_h]
);

my $scroll_x = $editor_frame->Scrollbar(
    -orient => 'horizontal',
    -command => ['xview', $editor_canvas]
);

my $scroll_y = $editor_frame->Scrollbar(
    -orient => 'vertical',
    -command => ['yview', $editor_canvas]
);

$editor_canvas->configure(
    -xscrollcommand => ['set', $scroll_x],
    -yscrollcommand => ['set', $scroll_y]
);

$editor_canvas->grid(
    -row => 0,
    -column => 0,
    -sticky => 'nsew'
);

$scroll_y->grid(
    -row => 0,
    -column => 1,
    -sticky => 'ns'
);

$scroll_x->grid(
    -row => 1,
    -column => 0,
    -sticky => 'ew'
);

$editor_frame->gridRowconfigure(0, -weight => 1);
$editor_frame->gridColumnconfigure(0, -weight => 1);

# --------------------------------------------------
# RECTANGLE COORDINATES
# --------------------------------------------------

sub rectangle_coords {
    my ($name) = @_;

    my $cx = $image_width / 2 + $vars{"${name}_x"};
    my $cy = $image_height / 2 + $vars{"${name}_y"};

    my $w = $vars{"${name}_w"};
    my $h = $vars{"${name}_h"};

    return (
        $cx - $w / 2,
        $cy - $h / 2,
        $cx + $w / 2,
        $cy + $h / 2
    );
}

# --------------------------------------------------
# DRAW RECTANGLES
# --------------------------------------------------

sub draw_rectangles {
	#########
#say " image= $images[$image_index] $photo";
    ######## 
    return unless $photo;
    
my @start = rectangle_coords('start');
my @end   = rectangle_coords('end');
############
#@start = (
#    $start[0] - 50,
#    $start[1] - 50,
#    $start[2] + 50,
#    $start[3] + 50
#);

#@end = (
#    $end[0] - 50,
#    $end[1] - 50,
#    $end[2] + 50,
#    $end[3] + 50
#);
#############
    if ($rect_start) {
        $editor_canvas->coords($rect_start, @start);
    }
    else {
        $rect_start = $editor_canvas->createRectangle(
            @start,
            -outline => 'green',
            -width => 3
        );
    }

    if ($rect_end) {
        $editor_canvas->coords($rect_end, @end);
    }
    else {
        $rect_end = $editor_canvas->createRectangle(
            @end,
            -outline => 'red',
            -width => 3
        );
    }

    # Draw / update curve point marker
    if ($curve_dot) {
        $editor_canvas->delete($curve_dot);
        $curve_dot = undef;
    }
    if ($vars{use_curve} && defined $curve_cx && defined $curve_cy) {
        my $r = 12;
        $curve_dot = $editor_canvas->createOval(
            $curve_cx - $r, $curve_cy - $r,
            $curve_cx + $r, $curve_cy + $r,
            -fill => 'yellow',
            -outline => 'black',
            -width => 2
        );
        $editor_canvas->raise($curve_dot);
    }
}

# --------------------------------------------------
# KEEP HEIGHT ACCORDING TO CURRENT RATIO (width / height)
# --------------------------------------------------

sub set_rectangle_size {
    my ($name, $width) = @_;

    $width = 16 if $width < 16;

    # Keep width in multiples of 16
    $width = round($width / 16) * 16;

    my $r = $vars{ratio} || (16/9);
    my $height = $width / $r;

    $vars{"${name}_w"} = $width;
    $vars{"${name}_h"} = $height;
}

# --------------------------------------------------
# MOUSE HIT TEST
# --------------------------------------------------

sub hit_rectangle {

    my ($x, $y) = @_;

    my $tolerance = 25;

    my @hits;   # collect all rectangles that contain the point or a near corner

    for my $name (qw(start end)) {

        my ($x1, $y1, $x2, $y2) = rectangle_coords($name);

        # Ensure x1 < x2, y1 < y2
        ($x1, $x2) = ($x2, $x1) if $x1 > $x2;
        ($y1, $y2) = ($y2, $y1) if $y1 > $y2;

        my $area = ($x2 - $x1) * ($y2 - $y1);

        # Check corners first (resize)
        my @corners = (
            [$x1, $y1, $x2, $y2, -1, -1],
            [$x2, $y1, $x1, $y2,  1, -1],
            [$x1, $y2, $x2, $y1, -1,  1],
            [$x2, $y2, $x1, $y1,  1,  1],
        );

        my $nearest;
        my $nearest_dist = $tolerance;

        for my $corner (@corners) {
            my ($cx, $cy) = @$corner[0,1];
            my $dist = sqrt( ($x - $cx)**2 + ($y - $cy)**2 );
            if ($dist <= $nearest_dist) {
                $nearest_dist = $dist;
                $nearest = $corner;
            }
        }

        if ($nearest) {
            push @hits, {
                name => $name,
                mode => 'resize',
                area => $area,
                data => $nearest,
            };
            next;
        }

        # Inside for move
        if ($x >= $x1 && $x <= $x2 && $y >= $y1 && $y <= $y2) {
            push @hits, {
                name => $name,
                mode => 'move',
                area => $area,
            };
        }
    }

    return unless @hits;

    # Prefer resize hits; among them (or among move hits) prefer the smallest area
    my @resize_hits = grep { $_->{mode} eq 'resize' } @hits;
    my @candidates = @resize_hits ? @resize_hits : @hits;

    my $best = $candidates[0];
    for my $h (@candidates) {
        $best = $h if $h->{area} < $best->{area};
    }

    if ($best->{mode} eq 'resize') {
        my $c = $best->{data};
        return (
            $best->{name},
            'resize',
            $c->[2], $c->[3], $c->[4], $c->[5]
        );
    }
    else {
        return ($best->{name}, 'move');
    }
}

# --------------------------------------------------
# MOUSE PRESS
# --------------------------------------------------

sub mouse_press {

    my ($canvas, $x, $y) = @_;

    $x = $canvas->canvasx($x);
    $y = $canvas->canvasy($y);

    my @hit = hit_rectangle($x, $y);

    if (@hit) {
        my ($name, $mode, $fx, $fy, $sx, $sy) = @hit;

        $drag = {
            name => $name,
            mode => $mode,

            mouse_x => $x,
            mouse_y => $y,

            original_x => $vars{"${name}_x"},
            original_y => $vars{"${name}_y"},

            fixed_x => $fx,
            fixed_y => $fy,

            sign_x => $sx,
            sign_y => $sy,
        };
        return;
    }

    # Missed both rectangles — set curve point if the checkbox is on
    if ($vars{use_curve}) {
        set_curve_point($x, $y);
    }
}

# Force-set the curve point (used by Shift-click so it works inside rectangles)
sub set_curve_point {
    my ($x, $y) = @_;
    return unless $vars{use_curve};
    $curve_cx = int($x);
    $curve_cy = int($y);
    draw_rectangles();
    if ($frame_label) {
        $frame_label->configure(-text => "Curve point set at $curve_cx, $curve_cy");
    }
}

sub mouse_press_shift {
    my ($canvas, $x, $y) = @_;
    $x = $canvas->canvasx($x);
    $y = $canvas->canvasy($y);
    set_curve_point($x, $y);
}

# --------------------------------------------------
# MOUSE DRAG
# --------------------------------------------------

sub mouse_drag {

    my ($canvas, $x, $y) = @_;

    return unless $drag;

    $x = $canvas->canvasx($x);
    $y = $canvas->canvasy($y);

    my $name = $drag->{name};

    my $dx = $x - $drag->{mouse_x};
    my $dy = $y - $drag->{mouse_y};

    if ($drag->{mode} eq 'move') {

        $vars{"${name}_x"} =
            round($drag->{original_x} + $dx);

        $vars{"${name}_y"} =
            round($drag->{original_y} + $dy);
    }
    else {

        my $width_x =
            $drag->{sign_x} * ($x - $drag->{fixed_x});

        my $width_y =
            $drag->{sign_y} * ($y - $drag->{fixed_y}) * 16 / 9;

        my $width = $width_x > $width_y
                  ? $width_x
                  : $width_y;

        set_rectangle_size($name, $width);

        my $w = $vars{"${name}_w"};
        my $h = $vars{"${name}_h"};

        my $cx = $drag->{fixed_x} +
                 $drag->{sign_x} * $w / 2;

        my $cy = $drag->{fixed_y} +
                 $drag->{sign_y} * $h / 2;

        $vars{"${name}_x"} =
            round($cx - $image_width / 2);

        $vars{"${name}_y"} =
            round($cy - $image_height / 2);
    }

    draw_rectangles();
}

# --------------------------------------------------
# MOUSE RELEASE
# --------------------------------------------------

sub mouse_release {
    undef $drag;
}

$editor_canvas->CanvasBind(
    '<Button-1>' => [\&mouse_press, Ev('x'), Ev('y')]
);

$editor_canvas->CanvasBind(
    '<Shift-Button-1>' => [\&mouse_press_shift, Ev('x'), Ev('y')]
);

$editor_canvas->CanvasBind(
    '<B1-Motion>' => [\&mouse_drag, Ev('x'), Ev('y')]
);

$editor_canvas->CanvasBind(
    '<ButtonRelease-1>' => \&mouse_release
);

# --------------------------------------------------
# LOAD PHOTOGRAPH
# --------------------------------------------------

sub load_image {

    my ($index_or_path) = @_;

    my $filename;
    if (defined $index_or_path && $index_or_path =~ /^\d+$/) {
        # Index into current @images list
        $image_index = $index_or_path;
        $image_index = 0 if $image_index < 0;
        $image_index = $#images if $image_index > $#images && @images;
        return unless @images;
        $filename = "$img_dir/$images[$image_index]";
    }
    elsif (defined $index_or_path && -f $index_or_path) {
        # Full path
        $filename = $index_or_path;
        # Update directory and rebuild image list for prev/next
        ($img_dir) = $filename =~ m{^(.*)/[^/]+$};
        $img_dir ||= '.';
        opendir(my $dh, $img_dir);
        if ($dh) {
            @images = sort grep { /\.(?:jpe?g|png)$/i } readdir($dh);
            closedir $dh;
        }
        # Find index of this file
        my ($base) = $filename =~ m{([^/]+)$};
        $image_index = 0;
        for my $i (0 .. $#images) {
            if ($images[$i] eq $base) {
                $image_index = $i;
                last;
            }
        }
    }
    else {
        return unless @images;
        $filename = "$img_dir/$images[$image_index]";
    }

    return unless defined $filename && -f $filename;

    my $new_photo = $mw->Photo(
        -file => $filename
    );

    $photo = $new_photo;

    # Force re-scale on next display when the source image changes
    $scaled_photo = undef;
    $scaled_scale = 0;

    $image_width  = $photo->width;
    $image_height = $photo->height;

    $canvas_w = $image_width;
    $canvas_h = $image_height;

    $editor_canvas->delete('all');

    $photo_id = $editor_canvas->createImage(
        0,
        0,
        -image => $photo,
        -anchor => 'nw'
    );

    $editor_canvas->configure(
        -scrollregion => [0, 0, $image_width, $image_height]
    );

    $rect_start = undef;
    $rect_end = undef;

    # Reset curve point on new image
    $curve_cx = undef;
    $curve_cy = undef;
    $curve_dot = undef;

    # Reset start/end rectangles to sensible defaults for this image
    # Centre them, modest size that fits, correct ratio
    my $default_w = int($image_width * 0.25);
    $default_w = 160 if $default_w < 160;
    $default_w = $image_width - 32 if $default_w > $image_width - 32;
    set_rectangle_size('start', $default_w);
    set_rectangle_size('end',   $default_w);
    $vars{start_x} = 0;
    $vars{start_y} = 0;
    $vars{end_x}   = 0;
    $vars{end_y}   = 0;

    # Clear any previous calculated frames and previews
    @frames = ();
    @preview_crops  = ();
    @preview_photos = ();
    $preview_vw = 0;
    $preview_vh = 0;
    $current = 0;

    draw_rectangles();

    my ($base) = $filename =~ m{([^/]+)$};
    $image_name_label->configure(
        -text => $base || $filename
    ) if $image_name_label;

    display_frame($current) if @frames;
}

# Open image via file dialog
sub open_image {
    my $file = $mw->getOpenFile(
        -title => 'Open Image',
        -initialdir => $img_dir,
        -filetypes => [
            ['Images', ['.jpg', '.jpeg', '.png']],
            ['All files', '*'],
        ],
    );
    return unless defined $file && $file ne '' && -f $file;
    load_image($file);
}

# --------------------------------------------------
# IMAGE SELECTION
# --------------------------------------------------

sub previous_image {
    return unless @images;
    my $index = $image_index - 1;
    $index = $#images if $index < 0;
    load_image($index);
}

sub next_image {
    return unless @images;
    my $index = $image_index + 1;
    $index = 0 if $index > $#images;
    load_image($index);
}
#--------------------
#       FAIRINGS
# Pure progress functions (0 → 1). Easy to add new equations.
# front_f / rear_f = number of frames for ease sections (0 = none)
#--------------------

# Linear (constant speed — no S)
sub fairing_linear {
    my ($i, $n) = @_;
    return 0 if $n <= 1;
    return $i / ($n - 1);
}

# Cosine ease-in / ease-out (classic S when both front and rear > 0)
sub fairing_cosine {
    my ($i, $n, $front_f, $rear_f) = @_;
    return 0 if $n <= 1;

    $front_f = int($front_f || 0);
    $rear_f  = int($rear_f  || 0);

    my $intervals = $n - 1;

    my @weights;
    for my $j (0 .. $intervals) {
        my $weight = 1;
        if ($j < $front_f && $front_f > 0) {
            $weight = 1 - cos( ($j + 1) / $front_f * 3.14159265358979 / 2 );
        }
        elsif ($j >= $intervals - $rear_f && $rear_f > 0) {
            my $remaining = $intervals - $j;
            $weight = 1 - cos( ($remaining + 1) / $rear_f * 3.14159265358979 / 2 );
        }
        push @weights, $weight;
    }

    my $total = 0;
    $total += $_ for @weights;
    return 0 if $total == 0;

    my $travelled = 0;
    for my $j (0 .. $i - 1) {
        $travelled += $weights[$j];
    }
    my $progress = $travelled / $total;
    return 1 if $i >= $n - 1;
    return $progress;
}

# Smoothstep (also S-shaped when used full-window)
sub fairing_smoothstep {
    my ($i, $n) = @_;
    return 0 if $n <= 1;
    my $t = $i / ($n - 1);
    return $t * $t * (3 - 2 * $t);
}

# Ease-in only (cosine ramp up, then constant) — avoids late slowdown
#sub fairing_ease_in {
#    my ($i, $n, $front_f) = @_;
#    return fairing_cosine($i, $n, $front_f, 0);
#}
#
#sub fairing_ease_out {
#    my ($i, $n, $rear_f) = @_;
#    return fairing_cosine($i, $n, 0, $rear_f);
#}

# Cubic ease-in-out (softer than cosine, still S if both sides)
sub fairing_cubic {
    my ($i, $n) = @_;
    return 0 if $n <= 1;
    my $t = $i / ($n - 1);
    return $t < 0.5
        ? 4 * $t * $t * $t
        : 1 - (-2 * $t + 2)**3 / 2;
}

# Helper: apply a progress value to a start/end pair
sub interpolate {
    my ($start, $end, $progress) = @_;
    return $start + ($end - $start) * $progress;
}

# --------------------------------------------------
# CALCULATE MOVEMENT
# --------------------------------------------------


# Map a global frame index into a 0-1 progress inside a start/end window,
# then apply the chosen fairing style.
# ease_front / ease_rear are percentages (0-100) of the window length.
sub progress_in_window {
    my ($i, $start, $end, $style, $ease_front_pct, $ease_rear_pct) = @_;

    return 0 if $i < $start;
    return 1 if $i >= $end;

    my $len = $end - $start;
    return 0 if $len <= 0;

    my $local = $i - $start;          # 0 .. len-1
    my $n     = $len;                 # number of steps

    my $front_f = int($n * ($ease_front_pct || 0) / 100);
    my $rear_f  = int($n * ($ease_rear_pct  || 0) / 100);

    # Clamp so front + rear don't exceed the window
    if ($front_f + $rear_f > $n - 1) {
        my $scale = ($n - 1) / ($front_f + $rear_f || 1);
        $front_f = int($front_f * $scale);
        $rear_f  = int($rear_f  * $scale);
    }

    $style = lc($style || 'linear');

    if ($style eq 'cosine') {
        return fairing_cosine($local, $n, $front_f, $rear_f);
    }
    elsif ($style eq 'smoothstep' || $style eq 'smooth') {
        return fairing_smoothstep($local, $n);
    }
#    elsif ($style eq 'ease_in') {
#        return fairing_ease_in($local, $n, $front_f || int($n * 0.3));
#    }
#    elsif ($style eq 'ease_out') {
#        return fairing_ease_out($local, $n, $rear_f || int($n * 0.3));
#    }
    elsif ($style eq 'cubic') {
        return fairing_cubic($local, $n);
    }
    else {
        # default / linear (constant velocity, no S)
        return fairing_linear($local, $n);
    }
}

sub calculate {

    pause();

    for my $key (qw(
        frames
        start_x start_y start_w
        end_x end_y end_w
    )) {
        unless (
            defined $vars{$key} &&
            $vars{$key} =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/
        ) {
            warn "Invalid value for $key\n";
            return;
        }
    }

    unless (
        defined $vars{filename} &&
        $vars{filename} =~ /\S/
    ) {
        warn "Please enter a filename\n";
        return;
    }

    my $n = int($vars{frames});

    if ($n < 1) {
        warn "Frames must be at least 1\n";
        return;
    }

    # Enforce current ratio on the rectangles
    set_rectangle_size('start', $vars{start_w});
    set_rectangle_size('end',   $vars{end_w});

    my $sx = $vars{start_x};
    my $sy = $vars{start_y};
    my $ex = $vars{end_x};
    my $ey = $vars{end_y};

    my $sw = $vars{start_w};
    my $sh = $vars{start_h};
    my $ew = $vars{end_w};
    my $eh = $vars{end_h};

    # Read timing + style + ease from the GUI fields
    my $track_style = lc($vars{track_style} || 'cosine');
    my $zoom_style  = lc($vars{zoom_style}  || 'linear');

    my $ts = $vars{track_start}  || 0;
    my $te = $vars{track_end}    || $n;
    my $zs = $vars{zoom_start}   || 0;
    my $ze = $vars{zoom_end}     || $n;

    my $t_front = $vars{track_ease_front} || 0;
    my $t_rear  = $vars{track_ease_rear}  || 0;
    my $z_front = $vars{zoom_ease_front}  || 0;
    my $z_rear  = $vars{zoom_ease_rear}   || 0;

    @frames = ();
    for my $i (0 .. $n - 1) {
        # Map global frame $i into the active window for each channel
        my $track_p = progress_in_window($i, $ts, $te, $track_style, $t_front, $t_rear);
        my $zoom_p  = progress_in_window($i, $zs, $ze, $zoom_style,  $z_front, $z_rear);

        my ($fx, $fy);
        if ($vars{use_curve} && defined $curve_cx && defined $curve_cy) {
            # Quadratic Bézier that passes through the clicked point at t=0.5
            # Start/end centres in absolute image coordinates
            my $p0x = $image_width  / 2 + $sx;
            my $p0y = $image_height / 2 + $sy;
            my $p2x = $image_width  / 2 + $ex;
            my $p2y = $image_height / 2 + $ey;
            # Control point that makes the curve go through ($curve_cx, $curve_cy) at t=0.5
            my $p1x = 2 * $curve_cx - 0.5 * ($p0x + $p2x);
            my $p1y = 2 * $curve_cy - 0.5 * ($p0y + $p2y);

            my $t = $track_p;
            my $u = 1 - $t;
            my $abs_x = $u*$u*$p0x + 2*$u*$t*$p1x + $t*$t*$p2x;
            my $abs_y = $u*$u*$p0y + 2*$u*$t*$p1y + $t*$t*$p2y;

            $fx = $abs_x - $image_width  / 2;
            $fy = $abs_y - $image_height / 2;
        }
        else {
            $fx = interpolate($sx, $ex, $track_p);
            $fy = interpolate($sy, $ey, $track_p);
        }

        push @frames, {
            x => round($fx),
            y => round($fy),
            w => round(interpolate($sw, $ew, $zoom_p)),
            h => round(interpolate($sh, $eh, $zoom_p)),
        };
    }

    # Guarantee exact end values
    if (@frames) {
        $frames[-1]{x} = round($ex);
        $frames[-1]{y} = round($ey);
        $frames[-1]{w} = round($ew);
        $frames[-1]{h} = round($eh);
    }

    # Pre-generate cropped previews (source resolution) and scale to current viewer
    generate_preview_crops();

    draw_rectangles();

    $current = 0;
    display_frame(0);
    save_frame_map();
}

# --------------------------------------------------
# PREVIEW CACHE  (crop once, rescale on viewer size change)
# --------------------------------------------------

sub generate_preview_crops {
    @preview_crops  = ();
    @preview_photos = ();
    $preview_vw = 0;
    $preview_vh = 0;

    return unless @frames && $photo;

    my $img_path = "$img_dir/$images[$image_index]";
    return unless -f $img_path;

    my $im = Image::Imlib2->load($img_path);

    for my $f (@frames) {
        my $cx = $image_width  / 2 + $f->{x};
        my $cy = $image_height / 2 + $f->{y};
        my $left   = int($cx - $f->{w} / 2);
        my $top    = int($cy - $f->{h} / 2);
        my $right  = $left + int($f->{w});
        my $bottom = $top  + int($f->{h});

        $left   = 0 if $left < 0;
        $top    = 0 if $top < 0;
        $right  = $image_width  if $right  > $image_width;
        $bottom = $image_height if $bottom > $image_height;

        my $cw = $right - $left;
        my $ch = $bottom - $top;
        next if $cw < 1 || $ch < 1;

        my $cropped = $im->crop($left, $top, $cw, $ch);
        push @preview_crops, $cropped;
    }

    # Initial scale to current viewer size
    rescale_previews_to_viewer();
}

sub rescale_previews_to_viewer {
    my $vw = $vars{viewer_w};
    my $vh = $vars{viewer_h};
    return unless @preview_crops && $vw > 0 && $vh > 0;

    @preview_photos = ();
    my $tmp = "/tmp/move_preview_$$.jpg";
    for my $crop (@preview_crops) {
        my $scaled_im = $crop->create_scaled_image($vw, $vh);
        # Lower quality JPEG for faster write/read (preview only)
        $scaled_im->set_quality(50) if $scaled_im->can('set_quality');
        $scaled_im->save($tmp);
        my $photo = $mw->Photo(-file => $tmp);
        push @preview_photos, $photo;
    }
    unlink $tmp if -f $tmp;
    $preview_vw = $vw;
    $preview_vh = $vh;
}

# --------------------------------------------------
# DISPLAY FRAME
# --------------------------------------------------

sub display_frame {

    my ($index) = @_;

    return unless @frames;
    return unless $photo;

    $index = 0 if $index < 0;
    $index = $#frames if $index > $#frames;

    $current = $index;

    # Ensure we have previews at the current viewer size
    my $vw = $vars{viewer_w};
    my $vh = $vars{viewer_h};
    if (!@preview_photos || $preview_vw != $vw || $preview_vh != $vh) {
        if (@preview_crops) {
            if ($frame_label) {
                $frame_label->configure(-text => "rescaling (not regenerating) to fit changed viewer size");
            }
            rescale_previews_to_viewer();
        }
        else {
            generate_preview_crops();
        }
    }

    return unless $preview_photos[$current];

    $play_canvas->delete('all');
    $play_canvas->createImage(
        0, 0,
        -image => $preview_photos[$current],
        -anchor => 'nw'
    );

    # Thin border only when not in blackout mode
    unless ($vars{blackout}) {
        $play_canvas->createRectangle(
            1, 1, $vw - 1, $vh - 1,
            -outline => 'cyan',
            -width => 2
        );
    }

    $frame_label->configure(
        -text => "Frame: " . ($current + 1) .
                 " / " . scalar(@frames)
    ) if $frame_label;
}

# --------------------------------------------------
# PLAYBACK
# --------------------------------------------------

sub play {

    return unless @frames;
    return if $playing;

    # Prefer external playback if ffmpeg is available
    if (external_play()) {
        return;
    }

    # Fallback to internal Tk playback
    if ($current >= $#frames) {
        $current = 0;
        display_frame(0);
    }

    $playing = 1;
    play_tick();
}

sub external_playback_available {
    for my $bin (qw(ffplay ffmpeg)) {
        my $path = `which $bin 2>/dev/null`;
        chomp $path;
        return $path if $path && -x $path;
    }
    return;
}

sub external_play {
    return unless @preview_crops;

    my $ffplay = `which ffplay 2>/dev/null`;
    chomp $ffplay;
    my $ffmpeg = `which ffmpeg 2>/dev/null`;
    chomp $ffmpeg;

    unless ($ffmpeg && -x $ffmpeg) {
        warn "ffmpeg not found – falling back to Tk playback\n";
        return 0;
    }

    my $tmpdir = "move_play_$$";
    mkdir $tmpdir unless -d $tmpdir;

    # Export numbered JPEGs from the cached crops
    # Force even dimensions (required by libx264 / yuv420p)
    my $vw = $vars{viewer_w};
    my $vh = $vars{viewer_h};
    $vw -= $vw % 2;
    $vh -= $vh % 2;
    $vw = 2 if $vw < 2;
    $vh = 2 if $vh < 2;

    my $i = 0;
    for my $crop (@preview_crops) {
        my $scaled = $crop->create_scaled_image($vw, $vh);
        $scaled->set_quality(70) if $scaled->can('set_quality');
        my $file = sprintf("%s/frame_%04d.jpg", $tmpdir, $i++);
        $scaled->save($file);
    }

    # Build a real MP4
    my $mp4 = "$tmpdir/preview.mp4";
    my $pattern = "$tmpdir/frame_%04d.jpg";
    my $ffcmd = "$ffmpeg -y -framerate 25 -i $pattern -c:v libx264 -pix_fmt yuv420p -crf 23 $mp4";
    my $rc = system($ffcmd);
    if ($rc != 0 || !-f $mp4) {
        warn "ffmpeg failed to create MP4 (exit $rc)\n";
        return 0;
    }

    if ($ffplay && -x $ffplay) {
        system("$ffplay $mp4 >/dev/null 2>&1 &");
        $frame_label->configure(-text => "External playback started (ffplay)") if $frame_label;
    }
    else {
        # No ffplay – just leave the MP4 and tell the user
        warn "ffplay not found. MP4 written to $mp4\n";
        $frame_label->configure(-text => "MP4 ready: $mp4") if $frame_label;
    }
    return 1;
}

sub play_tick {

    return unless $playing;

    # Lightweight display path for playback (previews already prepared)
    if ($preview_photos[$current]) {
        $play_canvas->delete('all');
        $play_canvas->createImage(
            0, 0,
            -image => $preview_photos[$current],
            -anchor => 'nw'
        );
        # Update label only every 5 frames to reduce overhead
        if ($frame_label && ($current % 5 == 0 || $current == $#frames)) {
            $frame_label->configure(
                -text => "Frame: " . ($current + 1) . " / " . scalar(@frames)
            );
        }
    }
    else {
        display_frame($current);
    }

    if ($current >= $#frames) {
        pause();
        return;
    }

    $current++;

    $after_id = $mw->after(
        $delay,
        \&play_tick
    );
}

sub pause {

    $playing = 0;

    if (defined $after_id) {
        $mw->afterCancel($after_id);
        undef $after_id;
    }
}

sub step_forward {

    pause();
    display_frame($current + 1);
}

sub step_back {

    pause();
    display_frame($current - 1);
}

sub reset {

    pause();
    display_frame(0);
}

# --------------------------------------------------
# SAVE CSV
# --------------------------------------------------

sub save_csv {

    return unless @frames;

    my $filename = $vars{filename};

    unless ($filename =~ /^[\w.-]+$/) {
        warn "Filename can only contain letters, numbers, _ . and -\n";
        return;
    }

    my $out = "$dir/$filename.csv";

    open(my $fh, '>', $out)
        or die "Cannot write $out: $!";

    for my $f (@frames) {

        print $fh
        ################
            "x,$f->{x},y,$f->{y},w,$f->{w},h,$f->{h}\n";
        ################
    }

    close $fh;

    print "Saved $out\n";
}

# --------------------------------------------------
# SAVE PROJECT (all settings + curve point)
# --------------------------------------------------

sub save_project {

    my $out = $mw->getSaveFile(
        -title => 'Save Project',
        -initialdir => $dir,
        -defaultextension => '.project',
        -filetypes => [
            ['Project files', '.project'],
            ['All files', '*'],
        ],
    );
    return unless defined $out && $out ne '';

    open(my $fh, '>', $out)
        or do { warn "Cannot write $out: $!\n"; return; };

    print $fh "# Camera Movement Project\n";
    print $fh "# Saved by move_generator\n\n";

    for my $key (sort keys %vars) {
        my $val = defined $vars{$key} ? $vars{$key} : '';
        print $fh "$key=$val\n";
    }

    if (defined $curve_cx && defined $curve_cy) {
        print $fh "curve_cx=$curve_cx\n";
        print $fh "curve_cy=$curve_cy\n";
    }

    print $fh "image_index=$image_index\n";
    print $fh "image_name=$images[$image_index]\n" if @images;

    close $fh;

    # Derive base name and save CSV + frame map with the same name
    my $base = $out;
    $base =~ s/\.project$//i;

    # CSV
    if (@frames) {
        my $csv = "$base.csv";
        open(my $cfh, '>', $csv)
            or warn "Cannot write $csv: $!\n";
        if ($cfh) {
            for my $f (@frames) {
          ###########
                print $cfh "image,images/$images[$image_index],x,$f->{x},y,$f->{y},w,$f->{w},h,$f->{h}\n";
          ###########  
            }
            close $cfh;
            print "Saved CSV $csv\n";
        }
    }

    # Frame map (guide image)
    save_frame_map($base);

    print "Saved project $out\n";
    if ($frame_label) {
        $frame_label->configure(-text => "Project + CSV + map saved");
    }
}

# --------------------------------------------------
# LOAD PROJECT
# --------------------------------------------------

sub load_project {

    my $in = $mw->getOpenFile(
        -title => 'Load Project',
        -initialdir => $dir,
        -defaultextension => '.project',
        -filetypes => [
            ['Project files', '.project'],
            ['All files', '*'],
        ],
    );
    return unless defined $in && $in ne '' && -f $in;

    open(my $fh, '<', $in)
        or do { warn "Cannot read $in: $!\n"; return; };

    while (my $line = <$fh>) {
        chomp $line;
        next if $line =~ /^\s*#/ || $line !~ /=/;
        my ($key, $val) = split /=/, $line, 2;
        next unless defined $key && $key ne '';

        if ($key eq 'curve_cx') {
            $curve_cx = $val;
        }
        elsif ($key eq 'curve_cy') {
            $curve_cy = $val;
        }
        elsif ($key eq 'image_index') {
            # optional: switch image if desired
            # load_image($val) if $val =~ /^\d+$/;
        }
        elsif (exists $vars{$key}) {
            $vars{$key} = $val;
        }
    }
    close $fh;

    # Keep linked fields consistent
    sync_timing('track', 'end') if exists $vars{track_end};
    sync_timing('zoom',  'end') if exists $vars{zoom_end};
    sync_viewer_size('w') if exists $vars{viewer_w};

    # Refresh UI and drawing
    draw_rectangles();
    if ($frame_label) {
        $frame_label->configure(-text => "Project loaded: $in");
    }

    print "Loaded project $in\n";
}
#
sub save_frame_map {

    my ($base) = @_;
    $base ||= "$dir/$vars{filename}";

    return unless @frames;

    my $image = Image::Imlib2->new(
        $image_width,
        $image_height
    );

    $image->has_alpha(0);

    # White background
    $image->set_colour(255,255,255,255);
    $image->fill_rectangle(
        0, 0,
        $image_width, $image_height
    );

    for my $i (0 .. $#frames) {


    my $f = $frames[$i];

    # Rectangle position relative to image centre
    my $x = ($image_width - $f->{w}) / 2 + $f->{x};
    my $y = ($image_height - $f->{h}) / 2 + $f->{y};

    my $x1 = int($x);
    my $y1 = int($y);
    my $x2 = int($x + $f->{w});
    my $y2 = int($y + $f->{h});

    # Top and right edges: blue
    $image->set_colour(0,0,0,255);
    $image->draw_line($x1,$y1,$x2,$y1);
    $image->draw_line($x2,$y1,$x2,$y2);

    # Bottom and left edges: red
    $image->set_colour(0,0,0,0);
    $image->draw_line($x2,$y2,$x1,$y2);
    $image->draw_line($x1,$y2,$x1,$y1);

    }

    my $fname = "${base}_frame_map.png";

    warn "Saving PNG: $fname\n";

    $image->save($fname);

    warn "Frame map saved as $fname\n";
}

# --------------------------------------------------
# APPLY VIEWER SIZE
# --------------------------------------------------

sub apply_viewer_size {

    # Prefer width; derive height from ratio so the window always matches
    my $w = $vars{viewer_w};
    unless (defined $w && $w =~ /^\d+$/ && $w > 0) {
        warn "Invalid viewer_w\n";
        return;
    }

    # Keep multiples of 16 for cleanliness (same style as rectangles)
    # and ensure even dimensions for video encoding
    $w = round($w / 16) * 16;
    $w = 16 if $w < 16;
    $w -= $w % 2;

    my $r = $vars{ratio} || (16/9);
    my $h = round($w / $r);
    $h -= $h % 2;
    $h = 2 if $h < 2;

    $vars{viewer_w} = $w;
    $vars{viewer_h} = $h;

    $play_canvas->configure(
        -width  => $w,
        -height => $h
    );

    display_frame($current) if @frames;
}


# --------------------------------------------------
# BUTTONS
# --------------------------------------------------
######### -font => ['Helvetica', 16],
$buttons->Button(
    -text => 'Calculate',
-font => ['Helvetica', 16],
    -command => \&calculate
)->grid(-row => 0, -column => 0, -padx => 3);

$buttons->Button(
    -text => 'Play',
 -font => ['Helvetica', 16],
    -command => \&play
)->grid(-row => 0, -column => 1, -padx => 3);

$buttons->Button(
    -text => 'Pause',
 -font => ['Helvetica', 16],
    -command => \&pause
)->grid(-row => 0, -column => 2, -padx => 3);

$buttons->Button(
    -text => 'Previous',
-font => ['Helvetica', 16],
   -command => \&step_back
)->grid(-row => 0, -column => 3, -padx => 3);

$buttons->Button(
    -text => 'Next',
-font => ['Helvetica', 16],
    -command => \&step_forward
)->grid(-row => 0, -column => 4, -padx => 3);

$buttons->Button(
    -text => 'Reset',
 -font => ['Helvetica', 16],
    -command => \&reset
)->grid(-row => 0, -column => 5, -padx => 3);

$buttons->Button(
    -text => 'Save Project',
    -font => ['Helvetica', 16],
    -command => \&save_project
)->grid(-row => 0, -column => 6, -padx => 3);

$buttons->Button(
    -text => 'Open Image',
    -font => ['Helvetica', 16],
    -background=>'#66cc00',
    -command => \&open_image
)->grid(-row => 0, -column => 7, -padx => 3);

$buttons->Button(
    -text => 'Prev Image',
    -font => ['Helvetica', 16],
    -command => \&previous_image
)->grid(-row => 0, -column => 8, -padx => 3);

$buttons->Button(
    -text => 'Next Image',
    -font => ['Helvetica', 16],
    -command => \&next_image
)->grid(-row => 0, -column => 9, -padx => 3);

$buttons->Button(
    -text => 'Load Project',
    -font => ['Helvetica', 16],
    -command => \&load_project
)->grid(-row => 0, -column => 14, -padx => 3);


$buttons->Button(
    -text => 'Exit',
 -font => ['Helvetica', 16],
    -command => sub {
        pause();
        # Close any ffplay windows we started
        system("pkill -f 'ffplay.*move_play' >/dev/null 2>&1");
        # Clean up playback directories in current dir and /tmp
        system("rm -rf move_play_* /tmp/move_play_* /tmp/move_preview_*.jpg >/dev/null 2>&1");
        $mw->destroy;
    }
)->grid(-row => 0, -column => 10, -padx => 3);

$buttons->Button(
    -text => 'Apply Viewer Size',
 -font => ['Helvetica', 16],
    -command => \&apply_viewer_size
)->grid(-row => 0, -column => 11, -padx => 3);

$buttons->Checkbutton(
    -text => 'Use curve point',
    -font => ['Helvetica', 14],
    -variable => \$vars{use_curve},
    -command => sub {
        undef $drag;
        draw_rectangles();
    },
)->grid(-row => 0, -column => 12, -padx => 8);

$buttons->Checkbutton(
    -text => 'Black out surroundings',
    -font => ['Helvetica', 14],
    -variable => \$vars{blackout},
    -command => sub {
        display_frame($current) if @frames;
    },
)->grid(-row => 0, -column => 13, -padx => 8);

# --------------------------------------------------
# STATUS
# --------------------------------------------------

my $status = $mw->Frame;
$status->grid(
    -row => 3,
    -column => 0,
    -sticky => 'ew',
    -padx => 5
);

$frame_label = $status->Label(
    -text => 'Frame: 0',
-font => ['Helvetica', 16],
);

$frame_label->grid(
    -row => 0,
    -column => 0,
    -padx => 5
);

$image_name_label = $status->Label(
    -text => ''
);

$image_name_label->grid(
    -row => 0,
    -column => 1,
    -padx => 5
);

# --------------------------------------------------
# START
# --------------------------------------------------

# Do not auto-load an image; wait for the user to open one
$image_name_label->configure(-text => 'No image loaded — use Open Image') if $image_name_label;

MainLoop;
