{
    for monitor_id in 0..2 {
        let pane = widgets.display_panes[monitor_id].clone();
        let widgets_for_ui = widgets.clone();
        let save_state = Rc::new(RefCell::new(EyeRecordState::default()));
        sync_record_audio_button(&pane.record_audio_button, EyeRecordAudioMode::NoAudio, false);

        {
            let pane = pane.clone();
            let widgets = widgets_for_ui.clone();
            let save_state = Rc::clone(&save_state);
            let window_for_save = window.clone();
            pane.save_button.connect_clicked(move |_| {
                let chooser = gtk::FileChooserNative::new(
                    Some("Choose Eye Capture Folder"),
                    Some(&window_for_save),
                    gtk::FileChooserAction::SelectFolder,
                    Some("Select"),
                    Some("Cancel"),
                );
                chooser.set_modal(true);
                let save_state = Rc::clone(&save_state);
                let widgets = widgets.clone();
                let eye_name = pane.title.clone();
                chooser.connect_response(move |dialog, response| {
                    if response == gtk::ResponseType::Accept {
                        if let Some(folder) = dialog.file().and_then(|file| file.path()) {
                            save_state.borrow_mut().save_dir_override = Some(folder.clone());
                            widgets.status_label.set_text(&format!(
                                "{} saves now go to {}.",
                                eye_name,
                                folder.display()
                            ));
                        } else {
                            widgets.status_label.set_text(
                                "Capture folder selection did not return a filesystem path.",
                            );
                        }
                    }
                    dialog.destroy();
                });
                chooser.show();
            });
        }

        {
            let pane = pane.clone();
            let widgets = widgets_for_ui.clone();
            let save_state = Rc::clone(&save_state);
            pane.clip_button.connect_clicked(move |_| {
                let root = {
                    let borrowed = save_state.borrow();
                    match ensure_eye_capture_dir(borrowed.save_dir_override.as_deref(), "clips") {
                        Ok(path) => path,
                        Err(err) => {
                            widgets
                                .status_label
                                .set_text(&format!("Could not prepare capture folder: {err}"));
                            return;
                        }
                    }
                };

                let stem = format!("{}-clip-{}", eye_slug(&pane.title), timestamp_slug());
                let clip_path = unique_capture_path(&root, &stem, "png");
                match current_eye_texture(&pane.picture)
                    .and_then(|texture| save_texture_png(&texture, &clip_path))
                {
                    Ok(()) => {
                        widgets.status_label.set_text(&format!(
                            "{} clip saved to {}.",
                            pane.title,
                            clip_path.display()
                        ));
                    }
                    Err(err) => {
                        widgets
                            .status_label
                            .set_text(&format!("{} clip failed: {err}", pane.title));
                    }
                }
            });
        }

        {
            let pane = pane.clone();
            let widgets = widgets_for_ui.clone();
            let save_state = Rc::clone(&save_state);
            pane.record_audio_button.connect_clicked(move |button| {
                let mut state = save_state.borrow_mut();
                if state.recording_active {
                    sync_record_audio_button(button, state.audio_mode, true);
                    widgets.status_label.set_text(&format!(
                        "{} recording audio is locked at {} until recording stops.",
                        pane.title,
                        state.audio_mode.status_label()
                    ));
                    return;
                }
                state.audio_mode = state.audio_mode.next();
                sync_record_audio_button(button, state.audio_mode, false);
                widgets.status_label.set_text(&format!(
                    "{} next recording will include {}.",
                    pane.title,
                    state.audio_mode.status_label()
                ));
            });
        }

        {
            let pane = pane.clone();
            let widgets = widgets_for_ui.clone();
            let save_state = Rc::clone(&save_state);
            let state = Rc::clone(&state);
            let preview = preview.clone();
            let record_button = pane.record_button.clone();
            let record_audio_button = pane.record_audio_button.clone();
            record_button.connect_clicked(move |button| {
                if save_state.borrow().recording_active {
                    button.remove_css_class("recording-active");
                    let (finalize_rx, audio_mode) = {
                        let mut state = save_state.borrow_mut();
                        stop_audio_recording(&mut state.audio_recording);
                        if let Some(control_tx) = state.recording_control_tx.take() {
                            let _ = control_tx.send(RecordFrameTask::Finish);
                        }
                        state.recording_active = false;
                        state.frame_dir = None;
                        (state.finalize_rx.take(), state.audio_mode)
                    };
                    let Some(finalize_rx) = finalize_rx else {
                        button.set_label("⏺");
                        sync_record_audio_button(&record_audio_button, audio_mode, false);
                        widgets.status_label.set_text(&format!(
                            "{} recording stop failed: recording worker state was missing.",
                            pane.title
                        ));
                        return;
                    };

                    button.set_sensitive(false);
                    button.set_label("▰▰");
                    sync_record_audio_button(&record_audio_button, audio_mode, true);
                    let button = button.clone();
                    let record_audio_button = record_audio_button.clone();
                    let widgets = widgets.clone();
                    let pane_title = pane.title.clone();
                    glib::timeout_add_local(Duration::from_millis(100), move || {
                        match finalize_rx.try_recv() {
                            Ok(Ok(output)) => {
                                button.set_sensitive(true);
                                button.remove_css_class("recording-active");
                                button.set_label("⏺");
                                sync_record_audio_button(&record_audio_button, audio_mode, false);
                                widgets.status_label.set_text(&format!(
                                    "{} recording saved to {}.",
                                    pane_title,
                                    output.display()
                                ));
                                glib::ControlFlow::Break
                            }
                            Ok(Err(err)) => {
                                button.set_sensitive(true);
                                button.remove_css_class("recording-active");
                                button.set_label("⏺");
                                sync_record_audio_button(&record_audio_button, audio_mode, false);
                                widgets.status_label.set_text(&format!(
                                    "{} recording stop failed: {err}",
                                    pane_title,
                                ));
                                glib::ControlFlow::Break
                            }
                            Err(std::sync::mpsc::TryRecvError::Empty) => {
                                glib::ControlFlow::Continue
                            }
                            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                                button.set_sensitive(true);
                                button.remove_css_class("recording-active");
                                button.set_label("⏺");
                                sync_record_audio_button(&record_audio_button, audio_mode, false);
                                widgets.status_label.set_text(&format!(
                                    "{} recording stop failed: recording worker disconnected.",
                                    pane_title
                                ));
                                glib::ControlFlow::Break
                            }
                        }
                    });
                    return;
                }

                let (record_fps, record_bitrate_kbit) = {
                    let state = state.borrow();
                    best_effort_recording_profile(&state, preview.as_deref(), monitor_id)
                };
                let recording_surface = match state.borrow().display_surface(monitor_id) {
                    DisplaySurface::Preview => PreviewSurface::Inline,
                    DisplaySurface::Window => PreviewSurface::Window,
                };
                let Some(frame_tap) = preview.as_ref().and_then(|preview| {
                    preview.start_recording_tap(monitor_id, recording_surface)
                }) else {
                    widgets.status_label.set_text(&format!(
                        "{} recording needs a live preview stream first.",
                        pane.title
                    ));
                    return;
                };
                let root = {
                    let borrowed = save_state.borrow();
                    match ensure_eye_capture_dir(borrowed.save_dir_override.as_deref(), "recordings") {
                        Ok(path) => path,
                        Err(err) => {
                            widgets
                                .status_label
                                .set_text(&format!("Could not prepare capture folder: {err}"));
                            return;
                        }
                    }
                };

                let recording_stem = format!("{}-record-{}", eye_slug(&pane.title), timestamp_slug());
                let output_path = unique_capture_path(&root, &recording_stem, "mp4");
                let frame_dir = root.join(format!("{}.frames", recording_stem));
                if let Err(err) = std::fs::create_dir_all(&frame_dir) {
                    widgets.status_label.set_text(&format!(
                        "{} record failed creating frame cache {}: {err}",
                        pane.title,
                        frame_dir.display()
                    ));
                    return;
                }
                let audio_mode = save_state.borrow().audio_mode;
                let audio_recording =
                    match start_eye_audio_recording(audio_mode, &frame_dir, &recording_stem) {
                        Ok(recording) => recording,
                        Err(err) => {
                            let _ = std::fs::remove_dir_all(&frame_dir);
                            widgets.status_label.set_text(&format!(
                                "{} record failed starting audio capture: {err}",
                                pane.title
                            ));
                            return;
                        }
                    };
                let audio_paths = audio_recording
                    .as_ref()
                    .map(EyeAudioRecording::audio_paths)
                    .unwrap_or_default();

                let (control_tx, control_rx) = std::sync::mpsc::channel::<RecordFrameTask>();
                let (result_tx, result_rx) = std::sync::mpsc::channel::<Result<PathBuf, String>>();
                let frame_dir_worker = frame_dir.clone();
                let output_path_worker = output_path.clone();
                std::thread::spawn(move || {
                    let result = run_recording_worker(
                        frame_tap,
                        control_rx,
                        EyeRecordingWorkerConfig {
                            frame_dir: frame_dir_worker,
                            output_path: output_path_worker,
                            encode_fps: record_fps,
                            encode_bitrate_kbit: record_bitrate_kbit,
                            audio_mode,
                            audio_paths,
                        },
                    );
                    let _ = result_tx.send(result);
                });

                {
                    let mut state = save_state.borrow_mut();
                    state.frame_dir = Some(frame_dir);
                    state.recording_control_tx = Some(control_tx);
                    state.finalize_rx = Some(result_rx);
                    state.audio_recording = audio_recording;
                    state.recording_active = true;
                }

                button.set_sensitive(true);
                button.add_css_class("recording-active");
                button.set_label("⏺");
                sync_record_audio_button(&record_audio_button, audio_mode, true);
                widgets.status_label.set_text(&format!(
                    "Recording {} at {} fps (~{} kbit, {})... press the record button again to finish.",
                    pane.title,
                    record_fps,
                    record_bitrate_kbit,
                    audio_mode.status_label()
                ));
            });
        }
    }
}
