#!/usr/bin/perl
# image_batch_helper_with_csv.pl
# Batch crop / rotate / resize / flip for images in a selected directory
# using Image::Imlib2 + Tk interactive crop rectangle.
# Also supports cropping frames from a long image using a CSV of centre-offset windows.
#   - Top list: directories only. Click → select for batch ops (and load files below)
#   - Bottom list: files only (images + .csv). Click image → long image; click .csv → CSV
#   - Double-click directory to enter it
#
# Crop window uses the same hit-test / drag style as your timeline editor:
#   - click near a corner to resize
#   - click inside to move
#   - timeline scrubber keeps the rectangle fixed while scanning images

use strict;
use warnings;
use Image::Imlib2;
use Tk;
use Tk::PNG;
use File::Spec;
use File::Path qw(make_path);
use File::Temp qw(tempdir);
use Cwd;
use File::Basename qw(dirname);

use Cwd qw(getcwd);          # already have "use Cwd;" — this just imports getcwd

my $script_dir = getcwd();   # start where the user launched the script
my @dir_stack  = ($script_dir);
my $selected_dir = $dir_stack[-1];

my @image_files;
my @exts = qw(png jpg jpeg gif bmp tif tiff webp pnm ppm pgm pbm pam);

my ($crop_x, $crop_y, $crop_w, $crop_h) = (0, 0, 0, 0);
my $selected_csv = '';
my $selected_long_image = '';
my $batch_dir = $selected_dir;

#----------
my $mw = MainWindow->new(-title => "Image Batch Helper (with CSV crop)");

my $win_w = 900;
my $win_h = 1420;

my $screen_w = $mw->screenwidth;
my $screen_h = $mw->screenheight;

# Position so the window’s right edge is a bit left of screen centre
# (or change the offset to taste)
my $x = int($screen_w / 2 - $win_w - 20);
my $y = int(($screen_h - $win_h) / 2);   # vertically centred

$x = 0 if $x < 0;   # keep it on-screen if the window is very wide

$mw->geometry("${win_w}x${win_h}+${x}+${y}");
#----------
$mw->optionAdd('*font', ['Helvetica', 14]);
$mw->optionAdd('*Dialog*font', ['Helvetica', 14]);
$mw->optionAdd('*FileSelect*font', ['Helvetica', 14]);
$mw->optionAdd('*Listbox*font', ['Helvetica', 16]);
$mw->optionAdd('*Entry*font', ['Helvetica', 14]);
my $dir_frame = $mw->Labelframe(-text => "Directories only (click to select for batch, double-click to enter)")->pack(-fill => 'both', -expand => 1, -padx => 8, -pady => 4);
my $listbox = $dir_frame->Scrolled('Listbox', -scrollbars => 'osoe', -height => 10,
                                   -font => '{Helvetica} 16',
                                   -selectmode => 'single')->pack(-fill => 'both', -expand => 1);
$listbox->bind('<Double-Button-1>', \&select_item);
$listbox->bind('<<ListboxSelect>>', \&on_dir_select);

my $nav_frame = $mw->Frame->pack(-fill => 'x', -padx => 8);
$nav_frame->Button(-text => 'UP', -width => 6, -command => \&go_up)->pack(-side => 'left', -padx => 2);
$nav_frame->Button(-text => 'Refresh', -command => \&refresh_listbox)->pack(-side => 'left', -padx => 2);
my $dir_label = $mw->Label(-text => "Current: $selected_dir", -anchor => 'w', -relief => 'sunken')
    ->pack(-fill => 'x', -padx => 8, -pady => 2);

my $img_frame = $mw->Labelframe(-text => "Files in selected directory (black=image, green=csv) — click to select for CSV crop")->pack(-fill => 'both', -expand => 1, -padx => 8, -pady => 4);
my $img_list = $img_frame->Scrolled('Listbox', -scrollbars => 'osoe', -height => 8,
                                    -selectmode => 'single')->pack(-fill => 'both', -expand => 1);
$img_list->bind('<<ListboxSelect>>', \&on_file_select);

my $status = $mw->Label(-text => "Click a directory above to select for batch; click a file below to select for CSV crop.", -relief => 'sunken', -anchor => 'w')
    ->pack(-fill => 'x', -padx => 8, -pady => 2);

# ---- Batch operations (directory-wide) ----
my $batch_frame = $mw->Labelframe(-text => "Batch operations (crop / rotate / resize / flip)")->pack(-fill => 'x', -padx => 8, -pady => 10);
my $batch_dir_frame = $batch_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 2);
$batch_dir_frame->Label(-text => "Directory selected:")->pack(-side => 'left');
my $batch_dir_display = $batch_dir_frame->Label(-textvariable => \$batch_dir, -relief => 'sunken', -anchor => 'w')->pack(-side => 'left', -fill => 'x', -expand => 1, -padx => 4);

my $crop_frame = $batch_frame->Labelframe(-text => "Crop rectangle")->pack(-fill => 'x', -padx => 4, -pady => 10);
my $crop_btn_frame = $crop_frame->Frame->pack(-fill => 'x');
$crop_btn_frame->Button(-text => "Open Crop Window",
                        -command => \&open_crop_window)->pack(-side => 'left', -padx => 4, -pady => 2);
$crop_btn_frame->Button(-text => "Apply current crop to ALL images",
                        -command => sub { batch_crop() })->pack(-side => 'left', -padx => 4, -pady => 2);
$crop_frame->Label(-textvariable => \my $crop_label)->pack(-anchor => 'w', -padx => 4);
update_crop_label();

my $rot_frame = $batch_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 8);
$rot_frame->Label(-text => "Rotate:")->pack(-side => 'left');
my $rot_deg = 0;
$rot_frame->Entry(-textvariable => \$rot_deg, -width => 6)->pack(-side => 'left', -padx => 4);
$rot_frame->Button(-text => "Rotate all", -command => sub { batch_rotate($rot_deg) })->pack(-side => 'left', -padx => 4);

my $scale_frame = $batch_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 2);
$scale_frame->Label(-text => "Resize:")->pack(-side => 'left');
my ($new_w, $new_h) = (0, 0);
my $ratio_var = 'native';
my $updating = 0;   # must be declared before the callbacks that use it
my %ratios = (
    'native' => undef,
    '1:1'    => 1,
    '4:3'    => 4/3,
    '3:2'    => 3/2,
    '16:9'   => 16/9,
    '21:9'   => 21/9,
    '9:16'   => 9/16,
    '3:4'    => 3/4,
    '2:3'    => 2/3,
);

$scale_frame->Label(-text => "Ratio:")->pack(-side => 'left', -padx => 4);
my $ratio_menu = $scale_frame->Optionmenu(
    -options => [sort keys %ratios],
    -textvariable => \$ratio_var,
    -command => sub {
        # Recompute the other dimension if one is set
        return if $updating;
        if ($new_w && $new_w =~ /^\d+$/ && $ratios{$ratio_var}) {
            $updating = 1;
            $new_h = int($new_w / $ratios{$ratio_var} + 0.5);
            $updating = 0;
        } elsif ($new_h && $new_h =~ /^\d+$/ && $ratios{$ratio_var}) {
            $updating = 1;
            $new_w = int($new_h * $ratios{$ratio_var} + 0.5);
            $updating = 0;
        }
    },
)->pack(-side => 'left', -padx => 2);

$scale_frame->Label(-text => "W:")->pack(-side => 'left');
my $w_entry = $scale_frame->Entry(-textvariable => \$new_w, -width => 5)->pack(-side => 'left', -padx => 2);

$scale_frame->Label(-text => "H:")->pack(-side => 'left');
my $h_entry = $scale_frame->Entry(-textvariable => \$new_h, -width => 5)->pack(-side => 'left', -padx => 2);

$scale_frame->Button(-text => "Scale all", -command => sub { batch_scale($new_w, $new_h) })->pack(-side => 'left', -padx => 4);

# Live proportion update using chosen ratio (or native image ratio if 'native')

sub get_aspect {
    my $r = $ratios{$ratio_var};
    return $r if defined $r;
    return unless @image_files;
    my $img = Image::Imlib2->load(File::Spec->catfile($batch_dir, $image_files[0])) or return;
    return $img->width / $img->height;  # width/height for computing height from width? wait
}

$w_entry->bind('<KeyRelease>' => sub {
    return if $updating;
    return unless $new_w && $new_w =~ /^\d+$/;
    my $aspect = get_aspect();  # width / height
    return unless $aspect && $aspect > 0;
    $updating = 1;
    $new_h = int($new_w / $aspect + 0.5);
    $updating = 0;
});

$h_entry->bind('<KeyRelease>' => sub {
    return if $updating;
    return unless $new_h && $new_h =~ /^\d+$/;
    my $aspect = get_aspect();  # width / height
    return unless $aspect && $aspect > 0;
    $updating = 1;
    $new_w = int($new_h * $aspect + 0.5);
    $updating = 0;
});

##########
my $flip_frame = $batch_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 2);
$flip_frame->Label(-text => "Flip:")->pack(-side => 'left');
$flip_frame->Button(-text => "Horizontal", -command => sub { batch_flip('horizontal') })->pack(-side => 'left', -padx => 2);
$flip_frame->Button(-text => "Vertical",   -command => sub { batch_flip('vertical') })->pack(-side => 'left', -padx => 2);
$flip_frame->Button(-text => "Diagonal",   -command => sub { batch_flip('diagonal') })->pack(-side => 'left', -padx => 2);

# ---- CSV crop (isolated, individual file selection) ----
my $csv_frame = $mw->Labelframe(-text => "CSV crop (select individual long image + CSV)")->pack(-fill => 'x', -padx => 8, -pady => 8);
my $csv_img_frame = $csv_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 2);
$csv_img_frame->Label(-text => "Image selected:")->pack(-side => 'left');
my $csv_img_display = $csv_img_frame->Label(-textvariable => \$selected_long_image, -relief => 'sunken', -anchor => 'w')->pack(-side => 'left', -fill => 'x', -expand => 1, -padx => 4);

my $csv_file_frame = $csv_frame->Frame->pack(-fill => 'x', -padx => 4, -pady => 2);
$csv_file_frame->Label(-text => "CSV selected:")->pack(-side => 'left');
my $csv_display = $csv_file_frame->Label(-textvariable => \$selected_csv, -relief => 'sunken', -anchor => 'w')->pack(-side => 'left', -fill => 'x', -expand => 1, -padx => 4);

$csv_frame->Button(-text => "Crop selected long image using CSV",
                   -command => \&crop_from_csv)->pack(-fill => 'x', -padx => 4, -pady => 4);

$mw->Button(-text => "Quit", -command => sub { exit })->pack(-pady => 4);

sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');
    opendir(my $dh, $dir) or do { set_status("Can't open $dir: $!"); return; };
    my @contents = readdir($dh);
    closedir($dh);
    @contents = sort { lc($a) cmp lc($b) } @contents;
    foreach my $item (@contents) {
        next if $item =~ /^\./;
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');
        }
    }
    $dir_label->configure(-text => "Browsing: $dir");
}

sub select_item {
    my $selection = $listbox->get('active');
    return unless defined $selection && $selection ne '';
    my $path = File::Spec->catfile($dir_stack[-1], $selection);
    if (-d $path) {
        push @dir_stack, $path;
        $selected_dir = $path;
        $batch_dir = $path;          # also set as batch dir
        refresh_listbox();
        load_files_from_dir($batch_dir);
    }
}

sub on_dir_select {
    my @sel = $listbox->curselection;
    return unless @sel;
    my $item = $listbox->get($sel[0]);
    my $path = File::Spec->catfile($dir_stack[-1], $item);
    return unless -d $path;

    $batch_dir = $path;
    set_status("Batch directory set: $item");
    load_files_from_dir($batch_dir);
}

sub on_file_select {
    my @sel = $img_list->curselection;
    return unless @sel;
    my $item = $img_list->get($sel[0]);
    my $path = File::Spec->catfile($batch_dir, $item);
    return unless -f $path;

    if ($item =~ /\.csv$/i) {
        $selected_csv = $path;
        set_status("CSV selected: $item");
    } else {
        my $is_image = 0;
        for my $e (@exts) {
            if ($item =~ /\.$e$/i) { $is_image = 1; last; }
        }
        if ($is_image) {
            $selected_long_image = $path;
            set_status("Long image selected: $item");
        } else {
            set_status("Ignored (not an image or CSV): $item");
        }
    }
}

sub go_up {
    if (@dir_stack > 1) {
        pop @dir_stack;
        $selected_dir = $dir_stack[-1];
        $batch_dir = $selected_dir;     # also set as batch dir
        refresh_listbox();
        load_files_from_dir($batch_dir);
    }
}

sub load_files_from_dir {
    my ($dir) = @_;
    $img_list->delete(0, 'end');
    @image_files = ();
    opendir(my $dh, $dir) or return;
    my @all = readdir($dh);
    closedir($dh);
    my $csv_count = 0;
    my $other_count = 0;
    for my $f (sort { lc($a) cmp lc($b) } @all) {
        next if $f =~ /^\./;
        my $path = File::Spec->catfile($dir, $f);
        next unless -f $path;
        if ($f =~ /\.csv$/i) {
            $img_list->insert('end', $f);
            $img_list->itemconfigure('end', -foreground => '#669900');
            $csv_count++;
        } else {
            my $ok = 0;
            for my $e (@exts) {
                if ($f =~ /\.$e$/i) { $ok = 1; last; }
            }
            if ($ok) {
                $img_list->insert('end', $f);
                $img_list->itemconfigure('end', -foreground => 'black');
                push @image_files, $f;
            } else {
                $img_list->insert('end', $f);
                $img_list->itemconfigure('end', -foreground => 'gray');
                $other_count++;
            }
        }
    }
    set_status(scalar(@image_files) . " images, $csv_count CSV, $other_count other files in $dir");
}

sub update_crop_label {
    $crop_label = sprintf("Current crop: x=%d y=%d w=%d h=%d", $crop_x, $crop_y, $crop_w, $crop_h);
}

sub unique_output_dir_for {
    my ($op) = @_;
    my $processed = File::Spec->catdir($batch_dir, 'processed');
    make_path($processed) unless -d $processed;

    my $base = File::Spec->catdir($processed, $op);
    if (! -d $base) {
        make_path($base);
        return $base;
    }

    # Existing directory found — find the next free numbered variant
    my $n = 2;
    while (1) {
        my $cand = File::Spec->catdir($processed, "${op}-${n}");
        if (! -d $cand) {
            make_path($cand);
            return $cand;
        }
        $n++;
    }
}

sub output_dir_for {
    my ($op) = @_;
    my $dir = File::Spec->catdir($batch_dir, 'processed', $op);
    make_path($dir) unless -d $dir;
    return $dir;
}

sub set_status {
    my ($msg) = @_;
    $status->configure(-text => $msg);
    $mw->update if $mw;
}

sub batch_crop {
    return set_status("No images selected") unless @image_files;
    my $outdir = unique_output_dir_for('cropped');

    # Determine sequence number from directory name for filename suffix
    # cropped     -> 1
    # cropped-2   -> 2
    # cropped-3   -> 3
    # etc.
    my $seq = 1;
    if ($outdir =~ m{/cropped-(\d+)$}) {
        $seq = $1;
    } elsif ($outdir =~ m{/cropped$}) {
        $seq = 1;
    }

    my $total = scalar(@image_files);
    set_status("Cropping 0/$total ...");
    my $n = 0;
    for my $f (@image_files) {
        $n++;
        set_status("Cropping $n/$total: $f");
        my $path = File::Spec->catfile($batch_dir, $f);
        my $img = Image::Imlib2->load($path) or next;
        my $x = $crop_x; my $y = $crop_y; my $w = $crop_w; my $h = $crop_h;
        $x = 0 if $x < 0; $y = 0 if $y < 0;
        $w = $img->width  - $x if $x + $w > $img->width;
        $h = $img->height - $y if $y + $h > $img->height;
        next if $w <= 0 || $h <= 0;
        my $cropped = $img->crop($x, $y, $w, $h);

        my $outname = $f;
        $outname =~ s/\.(pnm|ppm|pgm|pbm|pam)$/.png/i;   # only rewrite the problematic ones

        # Insert sequence number before extension: 0027.png -> 0027-1.png
        $outname =~ s/(\.[^.]+)$/-$seq$1/;

        $cropped->save(File::Spec->catfile($outdir, $outname));
    }
    set_status("Cropped $total images -> $outdir");
}

sub batch_rotate {
    my ($deg) = @_;
    return if $deg == 0;
    return set_status("No images selected") unless @image_files;
    my $radians = $deg / 360 * 2 * 3.141592653589793;
    my $outdir = output_dir_for("rotated_${deg}");
    my $total = scalar(@image_files);
    set_status("Rotating 0/$total by $deg° ...");
    my $n = 0;
    for my $f (@image_files) {
        $n++;
        set_status("Rotating $n/$total: $f");
        my $img = Image::Imlib2->load(File::Spec->catfile($batch_dir, $f)) or next;
        my $rot = $img->create_rotated_image($radians);
     my $outname = $f;
     $outname =~ s/\.(pnm|ppm|pgm|pbm|pam)$/.png/i;   # only rewrite the problematic ones
     $rot->save(File::Spec->catfile($outdir, $outname));

    }
    set_status("Rotated $total images -> $outdir");
}


sub batch_scale {
    my ($w, $h) = @_;
    return set_status("No images selected") unless @image_files;
    return set_status("Enter a width and/or height") unless $w || $h;

    my $outdir = output_dir_for("scaled_${w}x${h}");
    my $total  = scalar(@image_files);
    set_status("Scaling 0/$total ...");
    my $n = 0;

    for my $f (@image_files) {
        $n++;
        set_status("Scaling $n/$total: $f");
        my $img = Image::Imlib2->load(File::Spec->catfile($batch_dir, $f)) or next;

        my $orig_w = $img->width;
        my $orig_h = $img->height;
        my $scale  = 1;

        if ($w && $h) {
            # fit inside the box while keeping proportions
            my $sx = $w / $orig_w;
            my $sy = $h / $orig_h;
            $scale = ($sx < $sy) ? $sx : $sy;
        }
        elsif ($w) {
            $scale = $w / $orig_w;
        }
        elsif ($h) {
            $scale = $h / $orig_h;
        }

        my $new_w = int($orig_w * $scale + 0.5);
        my $new_h = int($orig_h * $scale + 0.5);
        $new_w = 1 if $new_w < 1;
        $new_h = 1 if $new_h < 1;

        my $scaled = $img->create_scaled_image($new_w, $new_h);

        # same extension-rewrite trick we used for rotate
        my $outname = $f;
        $outname =~ s/\.(pnm|ppm|pgm|pbm|pam)$/.png/i;
        $scaled->save(File::Spec->catfile($outdir, $outname));
    }
    set_status("Scaled $total images -> $outdir");
}


sub batch_flip {
    my ($how) = @_;
    return set_status("No images selected") unless @image_files;
    my $outdir = output_dir_for("flip_$how");
    my $total = scalar(@image_files);
    set_status("Flipping 0/$total $how ...");
    my $n = 0;
    for my $f (@image_files) {
        $n++;
        set_status("Flipping $n/$total: $f");
        my $img = Image::Imlib2->load(File::Spec->catfile($batch_dir, $f)) or next;
        if    ($how eq 'horizontal') { $img->flip_horizontal(); }
        elsif ($how eq 'vertical')   { $img->flip_vertical(); }
        elsif ($how eq 'diagonal')   { $img->flip_diagonal(); }

    my $outname = $f;
    $outname =~ s/\.(pnm|ppm|pgm|pbm|pam)$/.png/i;   # only rewrite the problematic ones
    $img->save(File::Spec->catfile($outdir, $outname));

    }
    set_status("Flipped $total images -> $outdir");
}

sub crop_from_csv {
    return set_status("No CSV selected") unless $selected_csv && -f $selected_csv;
    return set_status("No long image selected") unless $selected_long_image && -f $selected_long_image;

    my $src_image = $selected_long_image;
    my ($vol, $dir, $fname) = File::Spec->splitpath($src_image);

    my $out_dir = File::Spec->catdir($batch_dir, 'processed', 'csv_frames');
    make_path($out_dir) unless -d $out_dir;

    my $img = Image::Imlib2->load($src_image) or return set_status("Cannot load $fname");
    my $img_w = $img->width;
    my $img_h = $img->height;

    open my $fh, '<', $selected_csv or return set_status("Cannot read CSV: $!");
    my $frame = 1;
    while (my $line = <$fh>) {
        chomp $line;
        next unless $line =~ /\S/;

        my %rec;
        my @f = split /,/, $line, -1;
        for (my $i = 0; $i + 1 < @f; $i += 2) {
            my $key = $f[$i] // '';
            my $val = $f[$i + 1] // '';
            next if $key eq '' || $val eq '';
            # ignore image,"path_to-image" pairs and any quoted values
            next if $key =~ /^image$/i || $key =~ /^["']/ || $val =~ /^["']/;
            $rec{$key} = $val;
        }
        next unless exists $rec{x} || exists $rec{w} || exists $rec{y} || exists $rec{h};

        my $cx = $rec{x} // 0;   # offset from image centre
        my $cy = $rec{y} // 0;
        my $w  = $rec{w} // $img_w;
        my $h  = $rec{h} // $img_h;

        # Absolute centre of the crop window
        my $abs_cx = int($img_w / 2) + $cx;
        my $abs_cy = int($img_h / 2) + $cy;

        # Convert to top-left for Imlib2
        my $x = $abs_cx - int($w / 2);
        my $y = $abs_cy - int($h / 2);

        # Clamp so the crop stays inside the source image
        $x = 0 if $x < 0;
        $y = 0 if $y < 0;
        $w = $img_w - $x if $x + $w > $img_w;
        $h = $img_h - $y if $y + $h > $img_h;
        next if $w < 1 || $h < 1;

        my $crop = $img->crop($x, $y, $w, $h);
        my $dest = File::Spec->catfile($out_dir, sprintf("frame_%04d.png", $frame));
        $crop->save($dest);
        $frame++;
    }
    close $fh;

    set_status("Wrote " . ($frame - 1) . " frames to $out_dir");
}

sub make_preview_image {
    my ($src_img, $max_w, $max_h) = @_;
    my $iw = $src_img->width;
    my $ih = $src_img->height;
    my $scale = 1.0;
    if ($iw > $max_w || $ih > $max_h) {
        my $sx = $max_w / $iw;
        my $sy = $max_h / $ih;
        $scale = $sx < $sy ? $sx : $sy;
    }
    my $dw = int($iw * $scale + 0.5);
    my $dh = int($ih * $scale + 0.5);
    $dw = 1 if $dw < 1;
    $dh = 1 if $dh < 1;

    # Fast solid background (light gray) instead of per-pixel checkerboard
    my $bg = Image::Imlib2->new($dw, $dh);
    $bg->has_alpha(0);
    $bg->set_color(180, 180, 180, 255);
    $bg->fill_rectangle(0, 0, $dw, $dh);

    my $scaled = $src_img->create_scaled_image($dw, $dh);
    # Blend only if the source might have transparency; otherwise just use scaled
    if ($src_img->has_alpha) {
        $scaled->has_alpha(1);
        $bg->blend($scaled, 1, 0, 0, $dw, $dh, 0, 0, $dw, $dh);
        return ($bg, $scale, $dw, $dh);
    }
    return ($scaled, $scale, $dw, $dh);
}

sub open_crop_window {
    return set_status("No images in current directory") unless @image_files;

    my $idx = 0;
    my $sel = $img_list->curselection;
    if (defined $sel && @$sel) {
        my $selected_name = $img_list->get($sel->[0]);
        # find matching index in @image_files (skip CSVs)
        for my $i (0 .. $#image_files) {
            if ($image_files[$i] eq $selected_name) {
                $idx = $i;
                last;
            }
        }
    }

    my $cw = $mw->Toplevel(-title => "Crop rectangle");
 $mw->update;
my $px = $mw->rootx;
my $py = $mw->rooty;
my $pw = $mw->width;
my $cx = $px + $pw + 10;   # 10 px gap to the right
my $cy = $py;
$cw->geometry("960x820+${cx}+${cy}");
 
 
#    $cw->geometry("960x820+1000+200");

    my $load_current;
    my $drag;
    my $hit_rectangle;
    my $redraw_rect;

    my $timeline_frame = $cw->Frame->pack(-fill => 'x', -padx => 8, -pady => 4);
    $timeline_frame->Label(-text => "Timeline (drag to scrub, ← → to step frame):")->pack(-side => 'left');
    my $timeline_var = $idx;
    my $timeline = $timeline_frame->Scale(
        -orient       => 'horizontal',
        -from         => 0,
        -to           => $#image_files,
        -variable     => \$timeline_var,
        -resolution   => 1,
        -showvalue    => 0,
        -sliderlength => 12,
        -length       => 600,
        -command      => sub {
            my $new = int($timeline_var);
            return if $new == $idx;
            $idx = $new;
            $load_current->() if defined $load_current;
        }
    )->pack(-side => 'left', -fill => 'x', -expand => 1, -padx => 4);
    $timeline->configure(-troughcolor => '#dddddd', -background => 'red', -activebackground => 'darkred');

    my $canvas = $cw->Canvas(-bg => '#cccccc')->pack(-expand => 1, -fill => 'both');
    my $info = $cw->Label(-text => "", -anchor => 'w')->pack(-fill => 'x');

    my ($photo, $img_id, $rect_id);
    my $display_scale = 1.0;
    my $orig_w = 0;
    my $orig_h = 0;

    # Pre-generate scaled preview images for faster scrubbing
    my $preview_tmpdir = tempdir(CLEANUP => 1);
    my @preview_paths;
    my @preview_scales;
    my @preview_dws;
    my @preview_dhs;
    my @orig_ws;
    my @orig_hs;

    my $total_frames = scalar(@image_files);
    set_status("Generating previews 0/$total_frames ...");
    $mw->update;
    for my $i (0 .. $#image_files) {
        my $fname = $image_files[$i];
        my $img_path = File::Spec->catfile($batch_dir, $fname);
        my $img = Image::Imlib2->load($img_path);
        if (!$img) {
            push @preview_paths, undef;
            push @preview_scales, 1;
            push @preview_dws, 1;
            push @preview_dhs, 1;
            push @orig_ws, 1;
            push @orig_hs, 1;
            next;
        }
        my ($preview, $scale, $dw, $dh) = make_preview_image($img, 900, 620);
        my $prev_path = File::Spec->catfile($preview_tmpdir, sprintf("preview_%04d.png", $i));
        $preview->save($prev_path);
        push @preview_paths, $prev_path;
        push @preview_scales, $scale || 1;
        push @preview_dws, $dw;
        push @preview_dhs, $dh;
        push @orig_ws, $img->width;
        push @orig_hs, $img->height;

        if ($i % 5 == 0 || $i == $#image_files) {
            set_status("Generating previews " . ($i+1) . "/$total_frames ...");
            $mw->update;
        }
    }
    set_status("Previews ready");

    $load_current = sub {
        my $fname = $image_files[$idx];
        $orig_w = $orig_ws[$idx] || 1;
        $orig_h = $orig_hs[$idx] || 1;
        $display_scale = $preview_scales[$idx] || 1;

        if ($crop_w <= 0 || $crop_h <= 0) {
            $crop_x = int($orig_w * 0.15);
            $crop_y = int($orig_h * 0.15);
            $crop_w = int($orig_w * 0.7);
            $crop_h = int($orig_h * 0.7);
        }

        $crop_x = 0 if $crop_x < 0;
        $crop_y = 0 if $crop_y < 0;
        $crop_w = $orig_w if $crop_w > $orig_w;
        $crop_h = $orig_h if $crop_h > $orig_h;
        $crop_x = $orig_w - $crop_w if $crop_x + $crop_w > $orig_w;
        $crop_y = $orig_h - $crop_h if $crop_y + $crop_h > $orig_h;
        $crop_w = 4 if $crop_w < 4;
        $crop_h = 4 if $crop_h < 4;

        my $prev_path = $preview_paths[$idx];
        if (!$prev_path || !-f $prev_path) {
            $info->configure(-text => "Cannot load preview for $fname");
            return;
        }

        $photo = $cw->Photo(-file => $prev_path);

        my $dw = $preview_dws[$idx];
        my $dh = $preview_dhs[$idx];

        $canvas->delete('all');
        $img_id = $canvas->createImage(0, 0, -image => $photo, -anchor => 'nw');
        $canvas->configure(-width => $dw, -height => $dh);

        my $dx = int($crop_x * $display_scale);
        my $dy = int($crop_y * $display_scale);
        my $dw_rect = int($crop_w * $display_scale);
        my $dh_rect = int($crop_h * $display_scale);
        # Rectangle colours (change these if you want different look)
        my $frame_colour   = 'red';
        my $stipple_colour = 'red';
        my $stipple_pattern = 'gray12';   # gray12 / gray25 / gray50 / gray75

        $rect_id = $canvas->createRectangle($dx, $dy, $dx + $dw_rect, $dy + $dh_rect,
                                            -outline => $frame_colour, -width => 3,
                                            -fill => $stipple_colour, -stipple => $stipple_pattern,
                                            -tags => 'croprect');
        $canvas->raise('croprect');
        $canvas->focus;

        $info->configure(-text => sprintf("%s  (%dx%d)  crop=(%d,%d,%d,%d)",
                                          $fname, $orig_w, $orig_h,
                                          $crop_x, $crop_y, $crop_w, $crop_h));
        update_crop_label();
        $timeline_var = $idx;

        # Bind directly to the rectangle item so clicks are sure to be seen
        $canvas->bind('croprect', '<Button-1>' => sub {
            my $e = $canvas->XEvent;
            my $x = $canvas->canvasx($e->x);
            my $y = $canvas->canvasy($e->y);
            my @hit = $hit_rectangle->($x, $y);
            if (@hit) {
                $drag = {
                    mode    => $hit[0],
                    mouse_x => $x,
                    mouse_y => $y,
                    orig_x  => $crop_x,
                    orig_y  => $crop_y,
                    orig_w  => $crop_w,
                    orig_h  => $crop_h,
                    sign_x  => $hit[1] || 0,
                    sign_y  => $hit[2] || 0,
                };
            } else {
                $drag = undef;
            }
        });
        $canvas->bind('croprect', '<B1-Motion>' => sub {
            return unless $drag;
            my $e = $canvas->XEvent;
            my $x = $canvas->canvasx($e->x);
            my $y = $canvas->canvasy($e->y);
            my $dx = ($x - $drag->{mouse_x}) / ($display_scale || 1);
            my $dy = ($y - $drag->{mouse_y}) / ($display_scale || 1);

            if ($drag->{mode} eq 'move') {
                $crop_x = int($drag->{orig_x} + $dx);
                $crop_y = int($drag->{orig_y} + $dy);
            } elsif ($drag->{mode} eq 'resize') {
                if ($drag->{sign_x} < 0) {
                    $crop_x = int($drag->{orig_x} + $dx);
                    $crop_w = int($drag->{orig_w} - $dx);
                } else {
                    $crop_w = int($drag->{orig_w} + $dx);
                }
                if ($drag->{sign_y} < 0) {
                    $crop_y = int($drag->{orig_y} + $dy);
                    $crop_h = int($drag->{orig_h} - $dy);
                } else {
                    $crop_h = int($drag->{orig_h} + $dy);
                }
            }
            $crop_x = 0 if $crop_x < 0;
            $crop_y = 0 if $crop_y < 0;
            $crop_w = 4 if $crop_w < 4;
            $crop_h = 4 if $crop_h < 4;
            $crop_w = $orig_w - $crop_x if $crop_x + $crop_w > $orig_w;
            $crop_h = $orig_h - $crop_y if $crop_y + $crop_h > $orig_h;
            $redraw_rect->();
            update_crop_label();
        });
        $canvas->bind('croprect', '<ButtonRelease-1>' => sub { $drag = undef; });
    };

    $redraw_rect = sub {
        return unless $rect_id;
        my $dx = int($crop_x * $display_scale);
        my $dy = int($crop_y * $display_scale);
        my $dw_rect = int($crop_w * $display_scale);
        my $dh_rect = int($crop_h * $display_scale);
        $canvas->coords($rect_id, $dx, $dy, $dx + $dw_rect, $dy + $dh_rect);
    };

    # $drag already declared above

    $hit_rectangle = sub {
        my ($x, $y) = @_;
        my $dx = int($crop_x * $display_scale);
        my $dy = int($crop_y * $display_scale);
        my $dw_rect = int($crop_w * $display_scale);
        my $dh_rect = int($crop_h * $display_scale);
        my $tolerance = 20;

        my @corners = (
            [$dx,           $dy,           -1, -1],
            [$dx+$dw_rect,  $dy,            1, -1],
            [$dx,           $dy+$dh_rect,  -1,  1],
            [$dx+$dw_rect,  $dy+$dh_rect,   1,  1],
        );
        for my $c (@corners) {
            my ($cx, $cy, $sx, $sy) = @$c;
            my $dist = sqrt(($x - $cx)**2 + ($y - $cy)**2);
            if ($dist <= $tolerance) {
                return ('resize', $sx, $sy);
            }
        }
        if ($x >= $dx && $x <= $dx+$dw_rect && $y >= $dy && $y <= $dy+$dh_rect) {
            return ('move');
        }
        return;
    };

    $canvas->bind('<Button-1>' => sub {
        my $e = $canvas->XEvent;
        my $x = $canvas->canvasx($e->x);
        my $y = $canvas->canvasy($e->y);
        my @hit = $hit_rectangle->($x, $y);
        if (@hit) {
            $drag = {
                mode    => $hit[0],
                mouse_x => $x,
                mouse_y => $y,
                orig_x  => $crop_x,
                orig_y  => $crop_y,
                orig_w  => $crop_w,
                orig_h  => $crop_h,
                sign_x  => $hit[1] || 0,
                sign_y  => $hit[2] || 0,
            };
        } else {
            $drag = undef;
        }
    });

    $canvas->bind('<B1-Motion>' => sub {
        return unless $drag;
        my $e = $canvas->XEvent;
        my $x = $canvas->canvasx($e->x);
        my $y = $canvas->canvasy($e->y);
        my $dx = ($x - $drag->{mouse_x}) / ($display_scale || 1);
        my $dy = ($y - $drag->{mouse_y}) / ($display_scale || 1);

        if ($drag->{mode} eq 'move') {
            $crop_x = int($drag->{orig_x} + $dx);
            $crop_y = int($drag->{orig_y} + $dy);
        } elsif ($drag->{mode} eq 'resize') {
            if ($drag->{sign_x} < 0) {
                $crop_x = int($drag->{orig_x} + $dx);
                $crop_w = int($drag->{orig_w} - $dx);
            } else {
                $crop_w = int($drag->{orig_w} + $dx);
            }
            if ($drag->{sign_y} < 0) {
                $crop_y = int($drag->{orig_y} + $dy);
                $crop_h = int($drag->{orig_h} - $dy);
            } else {
                $crop_h = int($drag->{orig_h} + $dy);
            }
        }

        $crop_x = 0 if $crop_x < 0;
        $crop_y = 0 if $crop_y < 0;
        $crop_w = 4 if $crop_w < 4;
        $crop_h = 4 if $crop_h < 4;
        $crop_w = $orig_w - $crop_x if $crop_x + $crop_w > $orig_w;
        $crop_h = $orig_h - $crop_y if $crop_y + $crop_h > $orig_h;

        $redraw_rect->();
        update_crop_label();
    });

    $canvas->bind('<ButtonRelease-1>' => sub { $drag = undef; });

    my $bf = $cw->Frame->pack(-fill => 'x');
    $bf->Button(-text => "Crop all", -command => sub {
        batch_crop();
    })->pack(-side => 'left', -padx => 2);
    $bf->Button(-text => "Close", -command => sub {
        # Clean up temporary preview files
        if ($preview_tmpdir && -d $preview_tmpdir) {
            File::Path::remove_tree($preview_tmpdir);
        }
        $cw->destroy;
    })->pack(-side => 'right', -padx => 2);

    # Arrow keys to step frame-by-frame
    $cw->bind('<Left>' => sub {
        return if $idx <= 0;
        $idx--;
        $timeline_var = $idx;
        $load_current->();
    });
    $cw->bind('<Right>' => sub {
        return if $idx >= $#image_files;
        $idx++;
        $timeline_var = $idx;
        $load_current->();
    });
    # Also bind on canvas so keys work even if canvas has focus
    $canvas->bind('<Left>' => sub {
        return if $idx <= 0;
        $idx--;
        $timeline_var = $idx;
        $load_current->();
    });
    $canvas->bind('<Right>' => sub {
        return if $idx >= $#image_files;
        $idx++;
        $timeline_var = $idx;
        $load_current->();
    });

    $load_current->();
    $cw->protocol(WM_DELETE_WINDOW => sub {
        if ($preview_tmpdir && -d $preview_tmpdir) {
            File::Path::remove_tree($preview_tmpdir);
        }
        $cw->destroy;
    });
}

refresh_listbox();
# initial batch dir is the starting directory
$batch_dir = $dir_stack[-1];
load_files_from_dir($batch_dir);
MainLoop();
