#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Tk;
use Tk::PNG;
use Tk::JPEG;
use Tk::LabFrame;
use File::Spec;
use File::Basename qw(basename dirname);
use Cwd qw(abs_path);

my $project_root = abs_path(shift // '.');
my $browse_dir = $project_root;
my @tracks;
my $next_track_id = 1;
my $next_clip_id = 1;
my $selected_track = 1;
my $selected_clip;
my $solo_clip;          # if set, only this clip is drawn in the preview
my $playhead_drag = 0;
my $playhead_item;
my $pixels_per_frame = 8;
my $row_height = 52;
my $label_width = 115;
my $ruler_height = 28;
my $current_frame = 1;
my %photo_cache;
my $canvas_w = 1170;
my $canvas_h = 658;

# Re-position marker (canvas coordinates)
my $marker_x;
my $marker_y;
my $marker_id;
my $show_marker = 0;   # visual dot off by default

my $mw = MainWindow->new;
$mw->title('Timeline Re-position');
$mw->geometry('1600x1000');
$mw->optionAdd('*Font', 'Helvetica 12');

my $top = $mw->Frame()->pack(-side=>'top', -fill=>'x', -padx=>6, -pady=>5);
$top->Button(-text=>'Add Block', -command=>\&add_track)->pack(-side=>'left', -padx=>3);
$top->Button(-text=>'Remove Selected Block', -command=>\&remove_track)->pack(-side=>'left', -padx=>3);
$top->Label(-text=>'Start frame:')->pack(-side=>'left', -padx=>4);
my $start_frame_var = 1;
$top->Entry(-textvariable=>\$start_frame_var, -width=>7)->pack(-side=>'left');
$top->Button(-text=>'Add selected directory', -command=>\&add_selected_directory)->pack(-side=>'left', -padx=>5);
$top->Button(-text=>'Re-position', -command=>\&reposition_selected, -background=>'#ffcc00')->pack(-side=>'left', -padx=>12);
my $see_dot_button;
$see_dot_button = $top->Button(-text=>'See dot', -command=>sub {
    $show_marker = !$show_marker;
    my $keep = $selected_clip;
    draw_marker();
    $selected_clip = $keep if defined $keep;
    if ($show_marker) {
        $see_dot_button->configure(-background=>'#ffcc00');
    } else {
        $see_dot_button->configure(-background=>$mw->cget('-background'));
    }
    redraw_timeline() if defined $keep;
    set_status($show_marker ? "Dot visible" : "Dot hidden (click still records position)");
})->pack(-side=>'left', -padx=>3);

my $main = $mw->Frame()->pack(-side=>'top', -fill=>'both', -expand=>1, -padx=>6, -pady=>4);
my $left = $main->Frame(-width=>280)->pack(-side=>'left', -fill=>'y');
$left->packPropagate(0);
$left->Label(-text=>'Project directories', -anchor=>'w')->pack(-side=>'top', -fill=>'x');
my $path_label = $left->Label(-text=>$browse_dir, -anchor=>'w', -justify=>'left', -wraplength=>260);
$path_label->pack(-side=>'top', -fill=>'x', -pady=>3);
my $browser_frame = $left->Frame()->pack(-side=>'top', -fill=>'both', -expand=>1);
my $browser_scroll = $browser_frame->Scrollbar(-orient=>'vertical');
my $browser = $browser_frame->Listbox(-selectmode=>'browse', -yscrollcommand=>['set'=>$browser_scroll]);
$browser_scroll->configure(-command=>['yview'=>$browser]);
$browser_scroll->pack(-side=>'right', -fill=>'y');
$browser->pack(-side=>'left', -fill=>'both', -expand=>1);
$browser->bind('<Double-Button-1>' => sub {
    my $path = selected_item();
    add_selected_directory() if defined $path && -d $path;
});
my $nav = $left->Frame()->pack(-side=>'bottom', -fill=>'x', -pady=>5);
$nav->Button(-text=>'Up', -command=>\&go_up)->pack(-side=>'left', -padx=>2);
$nav->Button(-text=>'Refresh', -command=>\&refresh_browser)->pack(-side=>'left', -padx=>2);

my $right = $main->Frame()->pack(-side=>'left', -fill=>'both', -expand=>1, -padx=>8);
my $preview_frame = $right->LabFrame(-label=>'Preview — click to set re-position marker', -labelside=>'acrosstop')->pack(-side=>'top', -fill=>'x', -pady=>3);
my $preview = $preview_frame->Canvas(-width=>$canvas_w, -height=>$canvas_h, -background=>'#202830', -highlightthickness=>0)->pack(-side=>'left', -padx=>6, -pady=>6);
my $frame_controls = $preview_frame->Frame()->pack(-side=>'left', -fill=>'y', -padx=>8);
$frame_controls->Label(-text=>'Canvas W:')->pack(-anchor=>'w');
$frame_controls->Entry(-textvariable=>\$canvas_w, -width=>8)->pack(-anchor=>'w', -pady=>2);
$frame_controls->Label(-text=>'Canvas H:')->pack(-anchor=>'w');
$frame_controls->Entry(-textvariable=>\$canvas_h, -width=>8)->pack(-anchor=>'w', -pady=>2);
$frame_controls->Button(-text=>'Apply size', -command=>sub {
    $preview->configure(-width=>$canvas_w, -height=>$canvas_h);
    redraw_preview();
})->pack(-anchor=>'w', -pady=>4);
$frame_controls->Label(-text=>'Current frame')->pack(-anchor=>'w');
$frame_controls->Entry(-textvariable=>\$current_frame, -width=>8)->pack(-anchor=>'w', -pady=>3);
$frame_controls->Button(-text=>'Go', -command=>sub {
    $current_frame = 1 if !$current_frame || $current_frame < 1;
    redraw_timeline();
})->pack(-anchor=>'w');

my $timeline_frame = $right->Frame()->pack(-side=>'top', -fill=>'both', -expand=>1, -pady=>5);
$timeline_frame->Label(-text=>'Timeline — select a level, then Re-position', -anchor=>'w')->pack(-side=>'top', -fill=>'x');
my $canvas_holder = $timeline_frame->Frame()->pack(-side=>'top', -fill=>'both', -expand=>1);
my $xscroll = $canvas_holder->Scrollbar(-orient=>'horizontal');
my $yscroll = $canvas_holder->Scrollbar(-orient=>'vertical');
my $timeline = $canvas_holder->Canvas(-background=>'white', -xscrollcommand=>['set'=>$xscroll], -yscrollcommand=>['set'=>$yscroll], -scrollregion=>[0,0,1200,500], -highlightthickness=>1);
$xscroll->configure(-command=>['xview'=>$timeline]);
$yscroll->configure(-command=>['yview'=>$timeline]);
$xscroll->pack(-side=>'bottom', -fill=>'x');
$yscroll->pack(-side=>'right', -fill=>'y');
$timeline->pack(-side=>'left', -fill=>'both', -expand=>1);

my $status = $mw->Label(-text=>'Ready — load CSVs, select a level, click canvas, Re-position', -anchor=>'w', -relief=>'sunken')->pack(-side=>'bottom', -fill=>'x');
my $offscreen_label = $mw->Label(-text=>'Off-screen levels: none', -anchor=>'w', -background=>'#fff3cd', -font=>'{Helvetica} 11')->pack(-side=>'bottom', -fill=>'x');

add_track();
refresh_browser();
redraw_timeline();

sub set_status { $status->configure(-text=>$_[0]); }

sub refresh_browser {
    $path_label->configure(-text=>$browse_dir);
    $browser->delete(0,'end');
    $browser->insert('end','..');
    opendir(my $dh,$browse_dir) or do { set_status("Cannot open $browse_dir: $!"); return; };
    my @entries = readdir($dh);
    closedir($dh);
    my @dirs = sort grep { $_ ne '.' && $_ ne '..' && -d File::Spec->catdir($browse_dir,$_) } @entries;
    my @csvs = sort grep { /\.csv\z/i && -f File::Spec->catfile($browse_dir,$_) } @entries;
    $browser->insert('end', $_) for @dirs;
    $browser->insert('end', $_) for @csvs;
}

sub go_up {
    my $parent = abs_path(File::Spec->catdir($browse_dir,'..'));
    return unless defined $parent;
    $browse_dir = $parent;
    refresh_browser();
}

sub selected_item {
    my ($idx) = $browser->curselection;
    return unless defined $idx;
    my $name = $browser->get($idx);
    return if $name eq '..';
    my $path = File::Spec->catfile($browse_dir, $name);
    return $path if -e $path;
    return;
}

sub selected_directory {
    my $path = selected_item();
    return unless defined $path && -d $path;
    return $path;
}

sub add_selected_directory {
    my $dir = selected_directory();
    unless ($dir) {
        set_status('Select a directory first');
        return;
    }
    my @csv = csv_files_in_dir($dir);
    unless (@csv) {
        set_status("No CSV files found in $dir");
        return;
    }
    my $rel = File::Spec->abs2rel($dir, $project_root);
    my $added = 0;
    for my $file (@csv) {
        my $path = File::Spec->catfile($dir, $file);
        my $duration = count_csv_frames($path);
        next unless $duration;
        my $track;
        if (@tracks == 1 && !@{$tracks[0]{clips}} && !$added) {
            $track = $tracks[0];
        } else {
            my $id = $next_track_id++;
            $track = { id => $id, name => "Level $id", clips => [] };
            push @tracks, $track;
        }
        push @{$track->{clips}}, {
            id       => $next_clip_id++,
            dir      => $rel,
            csv      => $file,
            start    => $start_frame_var || 1,
            duration => $duration,
        };
        $selected_track = $track->{id};
        $selected_clip = $track->{clips}[-1]{id};
        $added++;
    }
    if ($added) {
        $current_frame = 1;
        redraw_timeline();
        my $off = report_offscreen();
        $offscreen_label->configure(-text => $off ? "Off-screen levels: $off" : "Off-screen levels: none");
        set_status("Added $added CSV blocks from $rel");
    } else {
        set_status('No non-empty CSV files found');
    }
}

sub report_offscreen {
    my $half_w = $canvas_w / 2;
    my $half_h = $canvas_h / 2;
    my @off;
    for my $t (@tracks) {
        for my $c (@{$t->{clips}}) {
            my @recs = load_csv_recs($c);
            next unless @recs;
            my $off = $current_frame - $c->{start};
            $off = 0 if $off < 0;
            $off = $#recs if $off > $#recs;
            my $rx = $recs[$off]{x} // 0;
            my $ry = $recs[$off]{y} // 0;
            if (abs($rx) > $half_w || abs($ry) > $half_h) {
                push @off, $c->{id};
            }
        }
    }
    return @off ? join(', ', @off) : '';
}

sub csv_files_in_dir {
    my ($dir)=@_;
    opendir(my $dh,$dir) or return ();
    my @csv=sort grep { /\.csv\z/i && -f File::Spec->catfile($dir,$_) } readdir($dh);
    closedir($dh);
    return @csv;
}

sub count_csv_frames {
    my ($file) = @_;
    open my $fh, '<', $file or return 0;
    my $count = 0;
    while (my $line = <$fh>) { $count++ if $line =~ /\S/; }
    close $fh;
    return $count;
}

sub add_track {
    my $id=$next_track_id++;
    push @tracks, { id=>$id, name=>'Block '.$id, clips=>[] };
    $selected_track=$id;
    redraw_timeline() if defined $timeline;
}

sub remove_track {
    return if @tracks<=1;
    @tracks=grep { $_->{id} != $selected_track } @tracks;
    $selected_track=$tracks[-1]{id};
    $selected_clip=undef;
    redraw_timeline();
}

sub track_by_id { my ($id)=@_; for (@tracks) { return $_ if $_->{id}==$id; } return; }
sub clip_by_id {
    my ($id)=@_;
    for my $t (@tracks) { for my $c (@{$t->{clips}}) { return ($t,$c) if $c->{id}==$id; } }
    return;
}

sub max_frame {
    my $end=0;
    for my $t (@tracks) { for my $c (@{$t->{clips}}) { my $e=$c->{start}+$c->{duration}-1; $end=$e if $e>$end; } }
    return $end;
}

sub timeline_extent {
    my $end=max_frame();
    $end=100 if $end<100;
    return $end+10;
}

sub redraw_timeline {
    return unless defined $timeline;
    $timeline->delete('all');
    my $end=timeline_extent();
    my $width=$label_width+$end*$pixels_per_frame;
    my $height=$ruler_height+@tracks*$row_height+10;
    $timeline->configure(-scrollregion=>[0,0,$width,$height]);
    $timeline->createRectangle(0,0,$width,$ruler_height,-fill=>'#e8e8e8',-outline=>'#c0c0c0');
    for (my $f=1;$f<=$end;$f+=10) {
        my $x=$label_width+($f-1)*$pixels_per_frame;
        $timeline->createLine($x,$ruler_height,$x,$height,-fill=>'#e1e1e1');
        $timeline->createText($x+2,14,-text=>$f,-anchor=>'w',-font=>'{Helvetica} 9',-fill=>'#333333');
    }
    my $row=0;
    for my $t (@tracks) {
        my $y=$ruler_height+$row*$row_height;
        $timeline->createRectangle(0,$y,$width,$y+$row_height,-fill=>($t->{id}==$selected_track?'#f5f8ff':'#fafafa'),-outline=>'#dddddd');
        $timeline->createRectangle(0,$y,$label_width,$y+$row_height,-fill=>'#e9edf0',-outline=>'#c8cdd0');
        $timeline->createText(7,$y+$row_height/2,-text=>$t->{name},-anchor=>'w');
        # Eye / solo button
        my $eye_x = $label_width - 28;
        my $eye_tag = "eye_$t->{id}";
        $timeline->createOval($eye_x, $y+12, $eye_x+16, $y+28, -fill=>(defined $solo_clip && $solo_clip == ($t->{clips}[0]{id} // 0) ? '#ff0' : '#ccc'), -outline=>'#666', -tags=>[$eye_tag, 'eye']);
        $timeline->createText($eye_x+8, $y+20, -text=>'o', -font=>'{Helvetica} 8', -tags=>[$eye_tag, 'eye']);
        for my $c (@{$t->{clips}}) {
            my $x1=$label_width+($c->{start}-1)*$pixels_per_frame;
            my $x2=$label_width+($c->{start}-1+$c->{duration})*$pixels_per_frame;
            my $fill=(defined $selected_clip && $c->{id}==$selected_clip)?'#287db0':'#5498bd';
            $timeline->createRectangle($x1,$y+5,$x2,$y+$row_height-5,-fill=>$fill,-outline=>'#205a7d',-width=>(defined $selected_clip && $c->{id}==$selected_clip?2:1),-tags=>["clip_$c->{id}",'clip']);
            $timeline->createText($x1+5,$y+$row_height/2,-text=>$c->{csv},-anchor=>'w',-fill=>'white',-font=>'{Helvetica} 12 bold',-tags=>["clip_$c->{id}",'clip']);
        }
        $row++;
    }
    my $px=$label_width+($current_frame-1)*$pixels_per_frame;
    $playhead_item = $timeline->createLine($px,$ruler_height,$px,$height,-fill=>'#d22', -width=>3, -tags=>['playhead']);
    redraw_preview();
}

sub canvas_frame_from_x { my ($x)=@_; my $cx=$timeline->canvasx($x); my $f=int(($cx-$label_width)/$pixels_per_frame)+1; return $f<1?1:$f; }
sub canvas_track_from_y {
    my ($y)=@_; my $cy=$timeline->canvasy($y); my $r=int(($cy-$ruler_height)/$row_height);
    $r=0 if $r<0; $r=$#tracks if $r>$#tracks; return $r;
}

sub clip_at {
    my ($x,$y)=@_;
    my @items=$timeline->find('withtag','current');
    for my $item (reverse @items) {
        my @tags=$timeline->gettags($item);
        for my $tag (@tags) { return $1 if $tag =~ /^clip_(\d+)$/; }
    }
    return;
}

$timeline->CanvasBind('<Button-1>' => sub {
    my $x = $timeline->canvasx($Tk::event->x);
    my $y = $timeline->canvasy($Tk::event->y);

    # Eye click → toggle solo for that clip
    my @items = $timeline->find('withtag', 'current');
    for my $item (@items) {
        my @tags = $timeline->gettags($item);
        for my $tag (@tags) {
            if ($tag =~ /^eye_(\d+)$/) {
                my $tid = $1;
                my $track = track_by_id($tid);
                if ($track && @{$track->{clips}}) {
                    my $cid = $track->{clips}[0]{id};
                    if (defined $solo_clip && $solo_clip == $cid) {
                        $solo_clip = undef;
                        set_status("Solo off — showing all levels");
                    } else {
                        $solo_clip = $cid;
                        set_status("Solo: only level $cid visible");
                    }
                    redraw_timeline();
                }
                return;
            }
        }
    }

    my $playhead_x = $label_width + ($current_frame - 1) * $pixels_per_frame;
    if (abs($x - $playhead_x) <= 6 && $y >= $ruler_height) {
        $playhead_drag = 1;
        return;
    }
    my $id = clip_at($x, $y);
    if (defined $id) {
        my ($t, $c) = clip_by_id($id);
        $selected_clip = $id;
        $selected_track = $t->{id} if $t;
        redraw_timeline();
        set_status("Selected level: " . ($c ? $c->{csv} : $id));
    } else {
        my $f = canvas_frame_from_x($x);
        $current_frame = $f;
        redraw_timeline();
    }
});

$timeline->CanvasBind('<B1-Motion>' => sub {
    return unless $playhead_drag;
    my $x = $timeline->canvasx($Tk::event->x);
    my $f = canvas_frame_from_x($x);
    $current_frame = $f;
    my $px = $label_width + ($current_frame - 1) * $pixels_per_frame;
    if (defined $playhead_item) {
        $timeline->coords($playhead_item, $px, $ruler_height, $px,
                          $ruler_height + @tracks * $row_height + 10);
    }
    redraw_preview();
});

$timeline->CanvasBind('<ButtonRelease-1>' => sub {
    if ($playhead_drag) {
        $playhead_drag = 0;
        redraw_timeline();
    }
});

# Click on preview: if on an image, select that level; otherwise set marker
$preview->CanvasBind('<Button-1>' => sub {
    my $x = $preview->canvasx($Tk::event->x);
    my $y = $preview->canvasy($Tk::event->y);

    # Find which level's image contains the click (topmost / last drawn wins)
    my $hit_clip;
####################
my $background_id;
if (@tracks && @{$tracks[0]{clips}}) {
    $background_id = $tracks[0]{clips}[0]{id};
}

for my $t (reverse @tracks) {
    for my $clip (reverse @{$t->{clips}}) {
        next if defined $background_id && $clip->{id} == $background_id;  # skip background
        next if defined $solo_clip && $clip->{id} != $solo_clip;
        next if $current_frame < $clip->{start} || $current_frame >= $clip->{start}+$clip->{duration};
        my $offset = $current_frame - $clip->{start};
        my @recs = load_csv_recs($clip);
        next unless @recs && $offset >= 0 && $offset <= $#recs;
        my $rec = $recs[$offset];
        next if ($rec->{image}//'') eq 'blank.png';
        my $dir = File::Spec->catdir($project_root, $clip->{dir});
        my $path = find_image_path($rec->{image}, $dir);
        next unless $path;
        my $photo = $photo_cache{$path};
        next unless $photo;
        my $img_w = $photo->width;
        my $img_h = $photo->height;
        my $tl_x = int(($canvas_w - $img_w) / 2 + ($rec->{x} // 0));
        my $tl_y = int(($canvas_h - $img_h) / 2 + ($rec->{y} // 0));
        if ($x >= $tl_x && $x <= $tl_x + $img_w && $y >= $tl_y && $y <= $tl_y + $img_h) {
            $hit_clip = $clip;
            last;
        }
    }
    last if $hit_clip;
}

if ($hit_clip) {
    $selected_clip = $hit_clip->{id};
    for my $t (@tracks) {
        for my $c (@{$t->{clips}}) {
            if ($c->{id} == $hit_clip->{id}) {
                $selected_track = $t->{id};
                last;
            }
        }
    }
    redraw_timeline();
    set_status("Selected level: $hit_clip->{csv}");
} else {
    # Background or empty → only set marker, keep current selection
    $marker_x = int($x);
    $marker_y = int($y);
    draw_marker();
    set_status("Position recorded at $marker_x, $marker_y" . ($show_marker ? "" : " (dot hidden)"));
}
});

sub draw_marker {
    $preview->delete('marker');
    return unless $show_marker && defined $marker_x && defined $marker_y;
    my $r = 5;   # smaller dot
    $marker_id = $preview->createOval(
        $marker_x-$r, $marker_y-$r, $marker_x+$r, $marker_y+$r,
        -fill=>'yellow', -outline=>'black', -width=>1, -tags=>['marker']
    );
    $preview->raise('marker');
}

sub parse_placement_line {
    my ($line) = @_;
    chomp $line;
    return unless $line =~ /\S/;
    my %rec;
    my @parts = split /,/, $line;
    for (my $i=0; $i<@parts-1; $i+=2) {
        my $k = $parts[$i];
        my $v = $parts[$i+1];
        $rec{$k} = $v if defined $k && $k ne '';
    }
    return \%rec if exists $rec{image};
    return;
}

sub load_csv_recs {
    my ($clip) = @_;
    return () unless $clip;
    my $dir = File::Spec->catdir($project_root, $clip->{dir});
    my $path = File::Spec->catfile($dir, $clip->{csv});
    open my $fh, '<', $path or return ();
    my @recs;
    while (my $line = <$fh>) {
        my $rec = parse_placement_line($line);
        push @recs, $rec if $rec;
    }
    close $fh;
    return @recs;
}

sub find_image_path {
    my ($image,$clip_dir)=@_;
    return unless defined $image && $image ne '';
    return $image if File::Spec->file_name_is_absolute($image) && -f $image;
    my @try=(File::Spec->catfile($project_root,$image), File::Spec->catfile($clip_dir,$image));
    for my $p (@try) { return abs_path($p) if -f $p; }
    return;
}

sub redraw_preview {
    return unless defined $preview;
    $preview->delete('all');
    $preview->createRectangle(0,0,$canvas_w,$canvas_h,-fill=>'#202830',-outline=>'#202830');
    my $shown=0;
    for my $t (@tracks) {
        for my $clip (@{$t->{clips}}) {
            next if defined $solo_clip && $clip->{id} != $solo_clip;
            next if $current_frame < $clip->{start} || $current_frame >= $clip->{start}+$clip->{duration};
            my $offset=$current_frame-$clip->{start};
            my $dir=File::Spec->catdir($project_root,$clip->{dir});
            my @recs = load_csv_recs($clip);
            next unless @recs && $offset >= 0 && $offset <= $#recs;
            my $rec = $recs[$offset];
            next if ($rec->{image}//'') eq 'blank.png';
            my $path=find_image_path($rec->{image},$dir);
            next unless $path;
            my $photo=$photo_cache{$path};
            if (!$photo) {
                my $ok=eval { $photo=$mw->Photo(-file=>$path); 1 };
                next unless $ok && $photo;
                $photo_cache{$path}=$photo;
            }
            my $raw_x = $rec->{x} // 0;
            my $raw_y = $rec->{y} // 0;
            my $img_w = $photo->width;
            my $img_h = $photo->height;
            # Centre-relative → top-left for display
            my $x = int(($canvas_w - $img_w) / 2 + $raw_x);
            my $y = int(($canvas_h - $img_h) / 2 + $raw_y);
            $preview->createImage($x,$y,-anchor=>'nw',-image=>$photo);
            $shown++;
        }
    }
    draw_marker();
    if (!$shown) {
        $preview->createText($canvas_w/2,$canvas_h/2,-text=>"No images at frame $current_frame",-fill=>'white',-font=>'{Helvetica} 14');
    }
}

sub reposition_selected {
    unless (defined $selected_clip) {
        set_status('Select a level on the timeline first');
        return;
    }
    unless (defined $marker_x && defined $marker_y) {
        set_status('Click on the preview canvas to set the target marker first');
        return;
    }

    my ($t, $clip) = clip_by_id($selected_clip);
    return unless $clip;

    my @recs = load_csv_recs($clip);
    unless (@recs) {
        set_status('Could not read CSV for selected level');
        return;
    }

    my $offset = $current_frame - $clip->{start};
    if ($offset < 0 || $offset > $#recs) {
        set_status("Current frame $current_frame is outside the selected level");
        return;
    }

    my $rec = $recs[$offset];
    my $img_path = find_image_path($rec->{image}, File::Spec->catdir($project_root, $clip->{dir}));
    my ($img_w, $img_h) = (0, 0);
    if ($img_path && -f $img_path) {
        my $photo = $photo_cache{$img_path} || eval { $mw->Photo(-file=>$img_path) };
        if ($photo) {
            $img_w = $photo->width;
            $img_h = $photo->height;
            $photo_cache{$img_path} = $photo;
        }
    }

    # Current top-left of this frame
    my $cur_tl_x = int(($canvas_w - $img_w) / 2 + ($rec->{x} // 0));
    my $cur_tl_y = int(($canvas_h - $img_h) / 2 + ($rec->{y} // 0));

    # We want the centre of the image to land on the marker
    # (or the top-left if you prefer — centre is the natural match to the stored coords)
    my $desired_tl_x = $marker_x - int($img_w / 2);
    my $desired_tl_y = $marker_y - int($img_h / 2);

    my $dx = $desired_tl_x - $cur_tl_x;
    my $dy = $desired_tl_y - $cur_tl_y;

    # Apply constant offset to every record (centre-relative values)
    for my $r (@recs) {
        $r->{x} = int(($r->{x} // 0) + $dx);
        $r->{y} = int(($r->{y} // 0) + $dy);
    }

    # Write new CSV (stable name, no repeated suffixes)
    my $dir = File::Spec->catdir($project_root, $clip->{dir});
    my $base = $clip->{csv};
    $base =~ s/_repositioned\.csv\z/.csv/i;
    $base =~ s/\.csv\z//i;
    my $new_name = "${base}_repositioned.csv";
    my $new_path = File::Spec->catfile($dir, $new_name);

    open my $out, '>', $new_path or do {
        set_status("Cannot write $new_path: $!");
        return;
    };
    for my $r (@recs) {
        print $out join(',',
            'image', ($r->{image} // ''),
            'x', $r->{x},
            'y', $r->{y}
        ), "\n";
    }
    close $out;

    # Point the clip at the new CSV
    $clip->{csv} = $new_name;
    redraw_timeline();
    redraw_preview();
    my $off = report_offscreen();
    $offscreen_label->configure(-text => $off ? "Off-screen levels: $off" : "Off-screen levels: none");
    set_status("Re-positioned $new_name (offset dx=$dx, dy=$dy) — marker was $marker_x,$marker_y");
}

MainLoop;
