use std::ops::Range;

use regex::Regex;

use crate::filter::{CompiledFilter, FilterMatch};
use crate::grep::GrepPredicate;
use crate::or::OrGroups;
use crate::line_index::LineIndex;
use crate::render::{count_rows, render_line, Cell, RenderOpts};
use crate::source::Source;

/// Maximum number of lines to walk backwards when reconstructing SGR state
/// for a scroll-up. Picked to comfortably cover a screen-height plus
/// headroom; bounds cost so that scrolling in huge files stays snappy.
const MAX_RECONSTRUCT_LINES: usize = 256;

/// Reconstruct the SGR state at the start of `target_line` by walking up
/// to MAX_RECONSTRUCT_LINES lines back and replaying byte-by-byte through
/// the ANSI parser. Lines beyond the cap are skipped: if there's an
/// unclosed SGR more than 256 lines above the top, the reconstruction starts
/// from default — first visible lines may render in default colors until a
/// reset appears (rare for normal log files).
fn reconstruct_render_state(
    src: &dyn Source,
    idx: &crate::line_index::LineIndex,
    target_line: usize,
) -> crate::render::RenderState {
    let start = target_line.saturating_sub(MAX_RECONSTRUCT_LINES);
    let mut state = crate::render::RenderState::default();
    for line_no in start..target_line {
        let range = idx.line_range(line_no, src);
        let raw = src.bytes(range);
        for &b in raw.as_ref() {
            let _ = crate::ansi::step(
                &mut state.parse,
                &mut state.style,
                &mut state.hyperlink,
                b,
            );
        }
    }
    state
}

/// Build the rendered text of a display row plus a `starts` table mapping
/// each char index in that text back to its starting cell column. The last
/// entry is a sentinel pointing one past the row's width, so a match's
/// `[char_start, char_end)` translates to the cell range
/// `starts[char_start]..starts[char_end]`.
fn row_text_and_starts(row: &[Cell]) -> (String, Vec<usize>) {
    let mut text = String::new();
    let mut starts: Vec<usize> = Vec::with_capacity(row.len() + 1);
    for (col, cell) in row.iter().enumerate() {
        match cell {
            Cell::Char { ch, .. } => {
                starts.push(col);
                text.push(*ch);
            }
            Cell::Empty => {
                starts.push(col);
                text.push(' ');
            }
            Cell::Continuation => {}
        }
    }
    starts.push(row.len());
    (text, starts)
}

/// Find every regex match in the rendered text of a row, translating each
/// True when the byte slice contains only whitespace (space, tab, CR, LF)
/// or is empty. Used by `-s` / `--squeeze-blank-lines` to detect runs of
/// blank lines at frame-composition time.
fn line_is_blank(bytes: &[u8]) -> bool {
    bytes.iter().all(|&b| b == b' ' || b == b'\t' || b == b'\r' || b == b'\n')
}

/// to a cell column range. Empty matches are dropped. Trailing-padding
/// spaces on a row would otherwise satisfy patterns like `\s+`; we trim
/// those by clamping match ends to where actual content stops.
fn find_row_highlights(row: &[Cell], regex: &Regex) -> Vec<Range<usize>> {
    if row.is_empty() {
        return Vec::new();
    }
    let last_content_col = row
        .iter()
        .enumerate()
        .rev()
        .find_map(|(c, cell)| match cell {
            Cell::Char { width, .. } => Some(c + *width as usize),
            Cell::Continuation => Some(c + 1),
            Cell::Empty => None,
        })
        .unwrap_or(0);
    if last_content_col == 0 {
        return Vec::new();
    }
    let (text, starts) = row_text_and_starts(row);
    let mut out = Vec::new();
    for m in regex.find_iter(&text) {
        if m.start() == m.end() {
            continue;
        }
        let char_start = text[..m.start()].chars().count();
        let char_end = text[..m.end()].chars().count();
        if char_start >= starts.len() - 1 || char_end <= char_start {
            continue;
        }
        let col_start = starts[char_start];
        let col_end = starts[char_end].min(last_content_col);
        if col_end > col_start {
            out.push(col_start..col_end);
        }
    }
    out
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowStyle {
    Normal,
    /// Render with a reduced-emphasis terminal attribute. Used by `--dim` to
    /// keep filtered-out lines visible as context.
    Dim,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchDirection {
    Forward,
    Backward,
}

/// How `--grep`, `--filter ~/!~`, `/`, `?`, and `:tag` patterns interpret
/// case. `Smart` matches less / ripgrep / vim `smartcase`: a pattern with
/// no uppercase characters is treated as case-insensitive; one with any
/// uppercase character is case-sensitive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaseMode {
    #[default]
    Sensitive,
    Smart,
    Insensitive,
}

/// Controls auto-exit on end-of-file. `Off` (default) never quits.
/// `Second` (less `-e`) quits on the second forward-motion that lands at
/// EOF in a row. `First` (less `-E`) quits the moment a forward motion
/// lands at EOF.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QuitAtEof {
    #[default]
    Off,
    Second,
    First,
}

impl CaseMode {
    /// Compile this case policy into a regex pattern by prepending the
    /// `(?i)` inline flag when case-insensitive matching is desired.
    pub fn apply_to_pattern(self, pattern: &str) -> String {
        match self {
            CaseMode::Sensitive => pattern.to_string(),
            CaseMode::Insensitive => format!("(?i){pattern}"),
            CaseMode::Smart => {
                if pattern.chars().any(|c| c.is_uppercase()) {
                    pattern.to_string()
                } else {
                    format!("(?i){pattern}")
                }
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct SearchState {
    pub raw: String,
    pub regex: Regex,
    pub direction: SearchDirection,
}

#[derive(Debug, Clone)]
pub struct Frame {
    pub body: Vec<Vec<Cell>>,        // exactly (rows-1) entries
    pub row_styles: Vec<RowStyle>,   // parallel to body
    /// Per-row column ranges to render with reverse-video. Used by `/`
    /// search to highlight just the matched phrase rather than the whole row.
    /// Indexed parallel to `body`; each inner Vec holds column ranges in
    /// `[start, end)` form (cell columns).
    pub highlights: Vec<Vec<std::ops::Range<usize>>>,
    pub status: String,
    /// Style applied to the status row by the writer.
    pub status_style: crate::ansi::Style,
    /// `AnsiMode::Raw` passthrough hints — parallel to `body`. `Some(bytes)`
    /// on a row instructs the writer to emit those original source bytes
    /// instead of rendering the cell grid (lets escape sequences pass to
    /// the terminal verbatim). `Some(empty)` skips emission (continuation
    /// row of a wrapped line whose first row already wrote the bytes).
    /// `None` means "render cells normally". Only populated when the
    /// viewport's ansi_mode is Raw.
    pub raw_rows: Vec<Option<Vec<u8>>>,
    /// When `Some`, the whole body is a single terminal-graphics escape blob
    /// (Sixel/Kitty). `write_frame` clears the body once, positions the cursor
    /// at (0,0), and writes these bytes verbatim instead of the per-row cell
    /// loop. `None` for all text/hex/ASCII-image frames.
    pub image_blob: Option<Vec<u8>>,
}

/// How images are rendered to the terminal. `Ascii` is the default (colored
/// ASCII / half-block art via `image_render`); `Kitty` / `Sixel` emit native
/// terminal-graphics escape blobs via `image_protocol`.
#[cfg(feature = "image")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImageProtocol {
    #[default]
    Ascii,
    Kitty,
    Sixel,
}

pub struct Viewport {
    top_line: usize,
    top_row: usize,
    /// Horizontal scroll offset (display columns). Only meaningful when not
    /// wrapping (chop text / image). Clamped per-frame; reset on new file /
    /// wrap-on. See `hscroll_active`.
    left_col: usize,
    cols: u16,
    rows: u16,
    pub opts: RenderOpts,
    pub show_line_numbers: bool,
    pub source_label: String,
    follow_mode: bool,
    live_mode: bool,
    prettify_label: Option<String>,
    format_label: Option<String>,
    filter: Option<CompiledFilter>,
    grep: Option<GrepPredicate>,
    or_groups: OrGroups,
    dim_mode: bool,
    /// In hide mode (filter active, !dim), maps visible position → logical line
    /// index. Empty otherwise.
    visible_lines: Vec<usize>,
    /// How many logical lines we've evaluated for filter membership. Used by
    /// `extend_visible_lines` to avoid re-scanning lines on every tick.
    visible_scanned: usize,
    search: Option<SearchState>,
    /// Active display template + format regex. When set, lines are rendered
    /// through the template before being shown, searched, or counted for wraps.
    /// Filtering still operates on the raw line (it uses captures, not text).
    display: Option<crate::format::DisplayRenderer>,
    hex_mode: bool,
    #[cfg(feature = "image")]
    image: Option<image::RgbaImage>,
    #[cfg(feature = "image")]
    animation: Option<crate::anim::AnimationState>,
    #[cfg(feature = "image")]
    image_protocol: ImageProtocol,
    /// Pixel dimensions of one terminal cell (w, h), used by protocol rendering
    /// to scale the image to fit terminal width and map text rows to pixels.
    #[cfg(feature = "image")]
    cell_px: (u16, u16),
    /// Width-scaled image cache. The `u16` is the scaled WIDTH the cache was
    /// built for; reused across vertical scrolls until the target width changes.
    #[cfg(feature = "image")]
    image_scaled: Option<(u16, image::RgbaImage)>,
    image_mode: bool,
    image_no_color: bool,
    #[cfg_attr(not(feature = "image"), allow(dead_code))]
    image_format: String,
    #[cfg(feature = "image")]
    image_style: crate::image_render::AsciiStyle,
    #[cfg_attr(not(feature = "image"), allow(dead_code))]
    image_width: Option<usize>,
    /// Bytes per hex group in `--hex` mode. One of 1, 2, 4, 8, 16.
    /// Default 2 (matches the historical `xxd` 2-byte / 4-char grouping).
    hex_group_size: usize,
    /// Custom status-line prompt template. When set, replaces the built-in
    /// format_status output with the template rendered against PromptContext.
    prompt: Option<crate::prompt::ParsedPrompt>,
    /// Error message from a failed preprocessor run. When set, surfaces
    /// a `[preprocess-failed: ...]` tag in the status line.
    preprocess_failure: Option<String>,
    /// When `count > 1`, status line shows `<label>  [current+1/count]`.
    file_index: Option<(usize, usize)>,
    /// When set, status line and prompt context include `[tag: <name> (N/M)]`.
    tag_active: Option<(String, usize, usize)>,  // (name, cursor+1, total)
    /// ANSI interpretation mode, resolved from --no-color / -r / env at startup.
    ansi_mode: crate::render::AnsiMode,
    /// Style applied to the status row at the writer level. Default
    /// `reverse` for backwards-compat. Overridden by --status-style /
    /// --prompt-style / per-format prompt_style.
    status_style: crate::ansi::Style,
    /// Transient status message shown for a few ticks (e.g. "(F reopened)"
    /// after a file rotation). The `u32` is the remaining tick count; the
    /// app loop decrements via `tick_flash` and the formatter renders the
    /// message as long as it's non-empty.
    status_flash: Option<(String, u32)>,
    /// Ticks since the line index last grew. Used to render `(F idle)`
    /// instead of `(F)` after a few seconds with no new bytes. Reset to
    /// 0 in `note_growth`, incremented in `tick_idle`. 20 ticks ≈ 5s at
    /// the 250 ms poll cadence.
    ticks_since_growth: u32,
    /// Case-sensitivity policy for search / filter / grep regex compile.
    /// Resolved from -i / -I CLI flags at startup; mutated by the `:case`
    /// colon command at runtime.
    case_mode: CaseMode,
    /// When false, search-match highlighting is suppressed in frame
    /// composition (but search navigation still works). Toggled by
    /// `-G` / `--no-hilite-search` and `:hlsearch` / `:nohlsearch`.
    hilite_search: bool,
    /// `-a` / `--search-skip-screen`: forward search and `n` anchor at the
    /// last displayed logical line instead of `top_line`, skipping matches on
    /// the current screen. Default off.
    search_skip_screen: bool,
    /// `-g` / `--hilite-only-match`: highlight only the single match last
    /// jumped to, not every match on screen. Default off.
    hilite_only_match: bool,
    /// `--tilde`: show a dim `~` on rows past end-of-file (default blank).
    tilde_eof: bool,
    /// Logical line the last search landed on. Drives `-g` highlight scoping.
    last_match_line: Option<usize>,
    /// Auto-exit-on-EOF policy resolved from `-e` / `-E` at startup.
    quit_at_eof: QuitAtEof,
    /// Counter for `QuitAtEof::Second`: number of consecutive forward
    /// motions that landed at EOF. Reset by any backward motion.
    eof_hits: u8,
    /// `-s` / `--squeeze-blank-lines`: collapse runs of blank lines to
    /// a single blank line at display time. Real line numbers / counts
    /// in `idx` are preserved.
    squeeze_blanks: bool,
    /// `--header=L,C`: pin the top `L` source lines at the top of the
    /// viewport and the left `C` columns at the left. The cols dimension
    /// is currently inert (no horizontal scroll yet); wired so future
    /// horizontal-scroll support can opt into it without re-plumbing.
    header_lines: usize,
    header_cols: usize,
    /// `-z` / `--window=N`: PageDown / PageUp step size in lines. `None`
    /// (default) means "use body_rows" — full-screen page step. Half-page
    /// commands always use body_rows/2 regardless.
    page_size: Option<u16>,
    /// Cached SGR/hyperlink state at the start of `render_state_for`.
    /// Invalidated when top_line changes or source grows; reconstructed
    /// by walking up to MAX_RECONSTRUCT_LINES lines back.
    render_state: crate::render::RenderState,
    /// Line number that `render_state` matches the start of. Sentinel
    /// `usize::MAX` means "invalid, must reconstruct".
    render_state_for: usize,
    /// `--incsearch` / `:incsearch`: when on, each keystroke in the `/`/`?`
    /// search prompt previews the first match (jump + highlight) from the
    /// position the prompt opened at. Esc restores; Enter commits. Default off.
    incsearch: bool,
    /// `-J` / `--status-column`: when on, a 1-column gutter is drawn at the far
    /// left (left of the line-number gutter) showing a mark letter, else `*`
    /// on lines with a current-search match. Default off. No-op in hex/raw/image.
    status_column: bool,
    /// Per-frame input: current file's marks keyed by line → mark letter.
    /// Set by the app loop before composing each frame when `status_column`
    /// is on. Drives the mark glyph in the status column.
    status_marks: std::collections::HashMap<usize, char>,
    /// When true, renders `[lock]` in the status line and `lock` in the
    /// `<lock>` prompt placeholder. Set by the event loop on the focused
    /// split pane while scroll-lock is active.
    scroll_lock: bool,
    /// When true, renders `[nomouse]` in the status line and `nomouse` in the
    /// `<mouse>` prompt placeholder. Set across all panes by the event loop
    /// when mouse capture is off (a global terminal state shown once).
    mouse_off: bool,
}

impl Viewport {
    pub fn new(cols: u16, rows: u16, source_label: String) -> Self {
        let opts = RenderOpts { cols, ..RenderOpts::default() };
        Self {
            top_line: 0,
            top_row: 0,
            left_col: 0,
            cols,
            rows,
            opts,
            show_line_numbers: false,
            source_label,
            follow_mode: false,
            live_mode: false,
            prettify_label: None,
            format_label: None,
            filter: None,
            grep: None,
            or_groups: OrGroups::default(),
            dim_mode: false,
            visible_lines: Vec::new(),
            visible_scanned: 0,
            search: None,
            display: None,
            hex_mode: false,
            #[cfg(feature = "image")]
            image: None,
            #[cfg(feature = "image")]
            animation: None,
            #[cfg(feature = "image")]
            image_protocol: ImageProtocol::Ascii,
            #[cfg(feature = "image")]
            cell_px: (8, 16),
            #[cfg(feature = "image")]
            image_scaled: None,
            image_mode: false,
            image_no_color: false,
            image_format: String::new(),
            #[cfg(feature = "image")]
            image_style: crate::image_render::AsciiStyle::Ramp,
            image_width: None,
            hex_group_size: 2,
            prompt: None,
            preprocess_failure: None,
            file_index: None,
            tag_active: None,
            ansi_mode: crate::render::AnsiMode::Strict,
            status_style: crate::ansi::Style { reverse: true, ..Default::default() },
            status_flash: None,
            ticks_since_growth: 0,
            case_mode: CaseMode::default(),
            hilite_search: true,
            search_skip_screen: false,
            hilite_only_match: false,
            tilde_eof: false,
            last_match_line: None,
            quit_at_eof: QuitAtEof::default(),
            eof_hits: 0,
            squeeze_blanks: false,
            header_lines: 0,
            header_cols: 0,
            page_size: None,
            render_state: crate::render::RenderState::default(),
            render_state_for: usize::MAX,
            incsearch: false,
            status_column: false,
            status_marks: std::collections::HashMap::new(),
            scroll_lock: false,
            mouse_off: false,
        }
    }

    pub fn status_column(&self) -> bool { self.status_column }

    pub fn set_status_column(&mut self, on: bool) { self.status_column = on; }

    /// Provide the current file's marks (line → mark letter) for the next
    /// frame. Cheap no-op cost when status_column is off (the frame never
    /// reads it then), but the app gates the call anyway.
    pub fn set_status_marks(&mut self, marks: std::collections::HashMap<usize, char>) {
        self.status_marks = marks;
    }

    /// Width of the far-left status column (1 if `-J` active, else 0). Forced
    /// to 0 in raw passthrough since `-J` is a no-op there (hex/image use
    /// separate frame paths and never reach the text composition).
    fn status_col_width(&self) -> u16 {
        if self.status_column && self.ansi_mode != crate::render::AnsiMode::Raw { 1 } else { 0 }
    }

    /// A single status-column cell carrying `glyph`. Styled plainly to match
    /// the line-number gutter label cells.
    fn status_cell(glyph: char) -> Cell {
        Cell::Char { ch: glyph, width: 1, style: crate::ansi::Style::default(), hyperlink: None }
    }

    /// Glyph for the status column on source line `line_n`'s first display row:
    /// a mark letter (precedence) if the line is marked, else `*` when the line
    /// contains a current-search match, else a blank.
    fn status_glyph(&self, line_n: usize, has_match: bool) -> char {
        if let Some(&ch) = self.status_marks.get(&line_n) {
            ch
        } else if has_match {
            '*'
        } else {
            ' '
        }
    }

    pub fn case_mode(&self) -> CaseMode { self.case_mode }

    pub fn hilite_search(&self) -> bool { self.hilite_search }

    pub fn set_hilite_search(&mut self, on: bool) { self.hilite_search = on; }

    pub fn set_search_skip_screen(&mut self, on: bool) { self.search_skip_screen = on; }
    pub fn search_skip_screen(&self) -> bool { self.search_skip_screen }
    pub fn set_hilite_only_match(&mut self, on: bool) { self.hilite_only_match = on; }
    pub fn hilite_only_match(&self) -> bool { self.hilite_only_match }
    pub fn set_tilde_eof(&mut self, on: bool) { self.tilde_eof = on; }
    pub fn tilde_eof(&self) -> bool { self.tilde_eof }

    pub fn incsearch(&self) -> bool { self.incsearch }

    pub fn set_incsearch(&mut self, on: bool) { self.incsearch = on; }

    pub fn top_row(&self) -> usize { self.top_row }

    /// Show the `[lock]` status badge / `<lock>` prompt value. Set by the
    /// event loop on the focused split pane while scroll-lock is active.
    pub fn set_scroll_lock(&mut self, on: bool) { self.scroll_lock = on; }

    /// Show the `[nomouse]` status badge / `nomouse` `<mouse>` value.
    pub fn set_mouse_off(&mut self, off: bool) { self.mouse_off = off; }

    /// Set the scroll position directly (logical line + wrap-row within it).
    pub fn set_top(&mut self, line: usize, row: usize) {
        self.top_line = line;
        self.top_row = row;
    }

    /// Preview an incremental-search pattern from `origin` (a (top_line, top_row)
    /// captured when the prompt opened), scrolling to the first match. Empty or
    /// invalid patterns are a silent no-op. Used by `--incsearch`.
    pub fn incsearch_preview(&mut self, src: &dyn Source, idx: &mut LineIndex,
                             pattern: &str, direction: SearchDirection,
                             origin: (usize, usize)) {
        if pattern.is_empty() { return; }
        self.set_top(origin.0, origin.1);
        if self.set_search(pattern.to_string(), direction).is_ok() {
            self.search_repeat(src, idx, false);
        }
    }

    pub fn set_quit_at_eof(&mut self, mode: QuitAtEof) {
        self.quit_at_eof = mode;
        self.eof_hits = 0;
    }

    pub fn set_squeeze_blanks(&mut self, on: bool) { self.squeeze_blanks = on; }
    pub fn squeeze_blanks(&self) -> bool { self.squeeze_blanks }

    pub fn set_header(&mut self, lines: usize, cols: usize) {
        self.header_lines = lines;
        self.header_cols = cols;
        // Don't let top_line land inside the pinned region — the scrolling
        // window starts at line `header_lines` once the feature is on.
        if self.top_line < self.header_lines {
            self.top_line = self.header_lines;
        }
    }
    pub fn header_lines(&self) -> usize { self.header_lines }
    pub fn header_cols(&self) -> usize { self.header_cols }

    pub fn set_page_size(&mut self, n: Option<u16>) { self.page_size = n; }
    pub fn page_size(&self) -> Option<u16> { self.page_size }

    /// Notify the EOF state machine of a motion. Returns `true` when the
    /// caller should quit. `forward = true` for any motion that could
    /// advance past EOF; `false` for backward motions (which reset the
    /// hit counter under `QuitAtEof::Second`).
    pub fn note_motion_for_eof(&mut self, forward: bool, src: &dyn Source, idx: &LineIndex) -> bool {
        match self.quit_at_eof {
            QuitAtEof::Off => false,
            QuitAtEof::First if forward && self.is_at_bottom(src, idx) => true,
            QuitAtEof::Second if forward && self.is_at_bottom(src, idx) => {
                self.eof_hits = self.eof_hits.saturating_add(1);
                self.eof_hits >= 2
            }
            _ => {
                if !forward { self.eof_hits = 0; }
                false
            }
        }
    }

    /// Switch the case-mode policy. Re-compiles any active search so the
    /// new policy takes effect on the next frame without the user having
    /// to retype the pattern.
    pub fn set_case_mode(&mut self, mode: CaseMode) {
        self.case_mode = mode;
        if let Some(s) = self.search.clone() {
            let _ = self.set_search(s.raw, s.direction);
        }
    }

    pub fn set_status_style(&mut self, style: crate::ansi::Style) {
        self.status_style = style;
    }

    pub fn status_style(&self) -> crate::ansi::Style {
        self.status_style
    }

    /// Show `msg` in the status row for the next `ticks` calls to the
    /// timeout branch (~250 ms each). Overrides the normal status during
    /// that window.
    pub fn flash(&mut self, msg: impl Into<String>, ticks: u32) {
        self.status_flash = Some((msg.into(), ticks));
    }

    /// Decrement the flash countdown by one tick. Clears the flash when
    /// it reaches zero.
    pub fn tick_flash(&mut self) {
        if let Some((_, n)) = &mut self.status_flash {
            *n = n.saturating_sub(1);
            if *n == 0 {
                self.status_flash = None;
            }
        }
    }

    /// Reset the idle counter; the source just produced fresh bytes.
    pub fn note_growth(&mut self) {
        self.ticks_since_growth = 0;
    }

    /// Increment the idle counter. Called in the timeout branch when the
    /// line index didn't grow.
    pub fn tick_idle(&mut self) {
        self.ticks_since_growth = self.ticks_since_growth.saturating_add(1);
    }

    /// True when the source has been quiet long enough to surface
    /// `(F idle)` instead of `(F)`. Threshold: 20 ticks ≈ 5s.
    pub fn is_idle(&self) -> bool {
        self.ticks_since_growth >= 20
    }

    pub fn set_display(&mut self, renderer: Option<crate::format::DisplayRenderer>) {
        self.display = renderer;
    }

    pub fn set_hex_mode(&mut self, on: bool) {
        self.hex_mode = on;
    }

    /// Returns whether `--hex` rendering is active.
    pub fn hex_mode(&self) -> bool {
        self.hex_mode
    }

    #[cfg(feature = "image")]
    fn reset_image_view(&mut self, format: &str, style: crate::image_render::AsciiStyle, width: Option<usize>) {
        self.image_format = format.to_string();
        self.image_style = style;
        self.image_width = width;
        self.image_mode = true;
        self.top_line = 0;
        self.top_row = 0;
        self.image_scaled = None;
    }

    #[cfg(feature = "image")]
    pub fn set_image(&mut self, img: image::RgbaImage, format: &str, style: crate::image_render::AsciiStyle, width: Option<usize>) {
        self.reset_image_view(format, style, width);
        self.image = Some(img);
        self.animation = None;
    }

    #[cfg(feature = "image")]
    pub fn set_animation(&mut self, anim: crate::image_render::Animation, format: &str,
                         style: crate::image_render::AsciiStyle, width: Option<usize>) {
        self.reset_image_view(format, style, width);
        self.image = None;
        self.animation = Some(crate::anim::AnimationState::new(anim.frames, anim.loop_count));
    }

    #[cfg(feature = "image")]
    pub fn has_animation(&self) -> bool { self.animation.is_some() }

    #[cfg(feature = "image")]
    fn current_image(&self) -> Option<&image::RgbaImage> {
        match &self.animation {
            Some(a) => Some(a.current_frame()),
            None => self.image.as_ref(),
        }
    }

    #[cfg(feature = "image")]
    pub fn tick(&mut self, dt: std::time::Duration) -> bool {
        if let Some(a) = &mut self.animation {
            if a.advance(dt) { self.image_scaled = None; return true; }
        }
        false
    }

    #[cfg(feature = "image")]
    pub fn anim_deadline(&self) -> Option<std::time::Duration> {
        self.animation.as_ref().and_then(|a| a.next_deadline())
    }

    #[cfg(feature = "image")]
    pub fn anim_toggle_pause(&mut self) {
        if let Some(a) = &mut self.animation { a.toggle_pause(); self.image_scaled = None; }
    }

    #[cfg(feature = "image")]
    pub fn anim_step(&mut self, delta: i32) {
        if let Some(a) = &mut self.animation { a.step(delta); self.image_scaled = None; }
    }

    #[cfg(feature = "image")]
    pub fn anim_restart(&mut self) {
        if let Some(a) = &mut self.animation { a.restart(); self.image_scaled = None; }
    }

    #[cfg(feature = "image")]
    fn anim_badge(&self) -> String {
        match &self.animation {
            Some(a) => {
                let (i, n) = (a.frame_index() + 1, a.frame_count());
                if a.is_finished() { format!("  [done {n}/{n}]") }
                else if a.is_playing() { format!("  [play {i}/{n}]") }
                else { format!("  [pause {i}/{n}]") }
            }
            None => String::new(),
        }
    }

    pub fn set_image_no_color(&mut self, on: bool) { self.image_no_color = on; }

    #[cfg(feature = "image")]
    pub fn set_image_protocol(&mut self, proto: ImageProtocol, cell_px: Option<(u16, u16)>) {
        self.image_protocol = proto;
        if let Some(c) = cell_px {
            if c.0 > 0 && c.1 > 0 { self.cell_px = c; }
        }
        self.image_scaled = None;
    }

    #[cfg(feature = "image")]
    pub fn image_protocol(&self) -> ImageProtocol { self.image_protocol }

    pub fn image_mode(&self) -> bool { self.image_mode }

    #[cfg(feature = "image")]
    fn image_cols(&self) -> u16 {
        self.image_width.map(|w| w.clamp(1, u16::MAX as usize) as u16).unwrap_or(self.cols.max(1))
    }

    #[cfg(feature = "image")]
    pub fn image_total_rows(&self) -> usize {
        match self.current_image() {
            Some(img) => {
                let (w, h) = img.dimensions();
                if self.image_protocol != ImageProtocol::Ascii {
                    protocol_occupied_rows(w, h, self.cols, self.cell_px, self.image_width)
                } else {
                    crate::image_render::output_rows(w, h, self.image_cols(), self.image_style)
                }
            }
            None => 0,
        }
    }

    #[cfg(feature = "image")]
    pub fn is_at_bottom_image(&self) -> bool {
        let body = self.body_rows() as usize;
        self.top_line + body >= self.image_total_rows()
    }

    /// Set bytes-per-group for `--hex` rendering. Accepts 1, 2, 4, 8, or 16.
    /// Invalid values are ignored.
    pub fn set_hex_group_size(&mut self, bytes_per_group: usize) {
        if matches!(bytes_per_group, 1 | 2 | 4 | 8 | 16) {
            self.hex_group_size = bytes_per_group;
        }
    }

    /// Current bytes-per-group for `--hex` rendering.
    pub fn hex_group_size(&self) -> usize {
        self.hex_group_size
    }

    pub fn set_prompt(&mut self, prompt: Option<crate::prompt::ParsedPrompt>) {
        self.prompt = prompt;
    }

    pub fn set_preprocess_failure(&mut self, msg: Option<String>) {
        self.preprocess_failure = msg;
    }

    pub fn set_file_index(&mut self, current: usize, total: usize) {
        self.file_index = if total > 1 {
            Some((current, total))
        } else {
            None
        };
    }

    pub fn set_tag_active(&mut self, info: Option<(String, usize, usize)>) {
        self.tag_active = info;
    }

    pub fn set_encoding(&mut self, enc: crate::charset::Encoding) { self.opts.encoding = enc; }

    /// Return the active charset encoding (for callers that need to decode line bytes).
    pub fn encoding(&self) -> crate::charset::Encoding { self.opts.encoding }

    /// Return the WHATWG name of the active encoding (e.g. `"UTF-8"`, `"windows-1252"`).
    pub fn encoding_label(&self) -> &'static str { self.opts.encoding.label() }

    pub fn set_ansi_mode(&mut self, mode: crate::render::AnsiMode) {
        self.ansi_mode = mode;
    }

    pub fn ansi_mode(&self) -> crate::render::AnsiMode {
        self.ansi_mode
    }

    /// Force cell rendering for split mode: if the current ANSI mode is Raw
    /// (which emits whole-row raw bytes the split compositor can't merge),
    /// switch to Interpret. Strict/Interpret are left unchanged.
    pub fn set_ansi_mode_cells(&mut self) {
        if matches!(self.ansi_mode, crate::render::AnsiMode::Raw) {
            self.ansi_mode = crate::render::AnsiMode::Interpret;
        }
    }

    pub fn set_source_label(&mut self, label: String) {
        self.source_label = label;
    }

    pub fn source_label_clone(&self) -> String {
        self.source_label.clone()
    }

    /// Fetch a logical line's display bytes — rendered through the active
    /// display template if one is set and the line parses against the format
    /// regex, otherwise the raw bytes. Used everywhere the *visible* form of
    /// the line matters: rendering, search, wrap-row counting.
    fn line_display_bytes<'a>(&self, src: &'a dyn Source, idx: &LineIndex, line_n: usize) -> std::borrow::Cow<'a, [u8]> {
        let range = idx.line_range(line_n, src);
        let raw = src.bytes(range);
        if let Some(r) = self.display.as_ref() {
            if let Some(rendered) = r.render_line(&raw, self.opts.encoding) {
                return std::borrow::Cow::Owned(rendered.into_bytes());
            }
        }
        raw
    }

    /// Compile and store a search pattern. Returns the parse error from the
    /// regex crate if the pattern is invalid; the previous search (if any)
    /// is preserved on error.
    pub fn set_search(&mut self, raw: String, direction: SearchDirection) -> Result<(), String> {
        let compiled = self.case_mode.apply_to_pattern(&raw);
        let regex = Regex::new(&compiled).map_err(|e| e.to_string())?;
        self.search = Some(SearchState { raw, regex, direction });
        Ok(())
    }

    pub fn clear_search(&mut self) { self.search = None; }

    pub fn search_active(&self) -> bool { self.search.is_some() }

    pub fn search_direction(&self) -> SearchDirection {
        self.search.as_ref().map(|s| s.direction).unwrap_or(SearchDirection::Forward)
    }

    /// Jump to the next match of the active search, in `direction` (or its
    /// reverse if `reverse` is true). Wraps at the end of the source.
    /// Returns true iff a match was found and the viewport moved.
    pub fn search_repeat(&mut self, src: &dyn Source, idx: &mut LineIndex, reverse: bool) -> bool {
        if idx.records_mode() {
            self.search_repeat_records(src, idx, reverse)
        } else {
            self.search_repeat_lines(src, idx, reverse)
        }
    }

    /// Line-mode search: unchanged original logic.
    fn search_repeat_lines(&mut self, src: &dyn Source, idx: &mut LineIndex, reverse: bool) -> bool {
        let Some(s) = self.search.as_ref() else { return false; };
        let forward = matches!(
            (s.direction, reverse),
            (SearchDirection::Forward, false) | (SearchDirection::Backward, true)
        );
        idx.extend_to_end(src);
        let pattern = s.regex.clone();
        if self.hide_mode() {
            self.extend_visible_lines(idx, src);
            self.search_step_in_visible(&pattern, src, idx, forward)
        } else {
            self.search_step_in_logical(&pattern, src, idx, forward)
        }
    }

    /// Records-mode search: iterate records, match against UTF-8-lossy decoded
    /// record bytes (which may contain embedded `\n`s), and jump the viewport
    /// to the first line of the matching record.
    fn search_repeat_records(&mut self, src: &dyn Source, idx: &mut LineIndex, reverse: bool) -> bool {
        let Some(s) = self.search.as_ref() else { return false; };
        let forward = matches!(
            (s.direction, reverse),
            (SearchDirection::Forward, false) | (SearchDirection::Backward, true)
        );
        let pattern = s.regex.clone();
        idx.extend_to_end(src);

        let total = idx.record_count();
        if total == 0 { return false; }

        // `-a` (search-skip-screen): forward search anchors at the record of the
        // last on-screen line, so matches in records already visible are skipped
        // (parity with the line/hide-mode paths). Backward stays top-anchored.
        let anchor_line = if self.search_skip_screen && forward {
            self.bottom_visible_line(idx)
        } else {
            self.top_line
        };
        let cur_record = idx.line_to_record(anchor_line);

        let range: Box<dyn Iterator<Item = usize>> = if forward {
            Box::new(((cur_record + 1)..total).chain(0..=cur_record))
        } else {
            let earlier: Vec<usize> = (0..cur_record).rev().collect();
            let later: Vec<usize> = (cur_record..total).rev().collect();
            Box::new(earlier.into_iter().chain(later))
        };

        for r in range {
            let bytes = idx.record_bytes_stripped(r, src);
            let text = crate::charset::decode_line(&bytes, self.opts.encoding);
            if pattern.is_match(&text) {
                let line_range = idx.record_line_range(r);
                self.top_line = line_range.start;
                self.last_match_line = Some(line_range.start);
                self.top_row = 0;
                return true;
            }
        }
        false
    }

    fn line_matches(&self, pattern: &Regex, src: &dyn Source, idx: &LineIndex, line_n: usize) -> bool {
        // Search runs against the *displayed* bytes so what the user sees is
        // what they can find. With a template active, that's the rendered form;
        // otherwise the raw line. ANSI color sequences are stripped so that
        // `/error` finds a red `error` regardless of escape codes.
        // Decode via the active charset so non-ASCII text in non-UTF-8 files
        // is matched as the user typed it (e.g. ISO-8859-1 "café").
        let display = self.line_display_bytes(src, idx, line_n);
        let bytes = crate::ansi::strip_sgr(&display);
        let text = crate::charset::decode_line(&bytes, self.opts.encoding);
        pattern.is_match(&text)
    }

    fn search_step_in_logical(&mut self, pattern: &Regex, src: &dyn Source, idx: &LineIndex, forward: bool) -> bool {
        let total = idx.line_count();
        if total == 0 { return false; }
        let start = if self.search_skip_screen && forward {
            self.bottom_visible_line(idx)
        } else {
            self.top_line
        };
        // Walk every logical line once, starting from start+1 (or start-1)
        // and wrapping at the end / beginning.
        for offset in 1..=total {
            let line_n = if forward {
                (start + offset) % total
            } else {
                (start + total - offset) % total
            };
            if self.line_matches(pattern, src, idx, line_n) {
                self.top_line = line_n;
                self.last_match_line = Some(line_n);
                self.top_row = 0;
                return true;
            }
        }
        false
    }

    fn search_step_in_visible(&mut self, pattern: &Regex, src: &dyn Source, idx: &LineIndex, forward: bool) -> bool {
        let total = self.visible_lines.len();
        if total == 0 { return false; }
        // Find current visible position for top_line.
        let anchor = if self.search_skip_screen && forward {
            self.bottom_visible_line(idx)
        } else {
            self.top_line
        };
        let cur = self.visible_lines.iter().position(|&l| l >= anchor).unwrap_or(0);
        for offset in 1..=total {
            let visible_idx = if forward {
                (cur + offset) % total
            } else {
                (cur + total - offset) % total
            };
            let line_n = self.visible_lines[visible_idx];
            if self.line_matches(pattern, src, idx, line_n) {
                self.top_line = line_n;
                self.last_match_line = Some(line_n);
                self.top_row = 0;
                return true;
            }
        }
        false
    }

    pub fn set_filter(&mut self, filter: Option<CompiledFilter>) {
        self.filter = filter;
        self.visible_lines.clear();
        self.visible_scanned = 0;
        // Drop scroll state — line numbering may have changed under us.
        self.top_line = 0;
        self.top_row = 0;
        self.left_col = 0;
    }

    pub fn set_grep(&mut self, grep: Option<GrepPredicate>) {
        self.grep = grep;
        self.visible_lines.clear();
        self.visible_scanned = 0;
        self.top_line = 0;
        self.top_row = 0;
        self.left_col = 0;
    }

    pub fn set_or_groups(&mut self, or_groups: OrGroups) {
        self.or_groups = or_groups;
        self.visible_lines.clear();
        self.visible_scanned = 0;
        self.top_line = 0;
        self.top_row = 0;
        self.left_col = 0;
    }

    pub fn or_active(&self) -> bool {
        self.or_groups.is_active()
    }

    pub fn grep_active(&self) -> bool { self.grep.is_some() }

    pub fn set_dim_mode(&mut self, on: bool) {
        self.dim_mode = on;
        // Hide mode is the only mode that needs visible_lines; clear when
        // turning dim ON, and re-derive from scratch when turning dim OFF
        // (next extend_visible_lines call rebuilds it).
        self.visible_lines.clear();
        self.visible_scanned = 0;
    }

    pub fn filter_active(&self) -> bool { self.filter.is_some() }

    pub fn dim_mode(&self) -> bool { self.dim_mode }

    fn hide_mode(&self) -> bool {
        (self.filter.is_some() || self.grep.is_some() || self.or_groups.is_active())
            && !self.dim_mode
    }

    /// Walk any newly indexed logical lines and append matching ones to
    /// `visible_lines` if we're in hide mode. No-op otherwise. Cheap to call
    /// every loop tick — keeps a `visible_scanned` cursor (line mode only;
    /// records mode rebuilds from scratch each call).
    pub fn extend_visible_lines(&mut self, idx: &LineIndex, src: &dyn Source) {
        if !self.hide_mode() {
            return;
        }
        if idx.records_mode() {
            self.extend_visible_lines_records(idx, src);
        } else {
            self.extend_visible_lines_per_line(idx, src);
        }
    }

    /// Line-mode: incrementally append newly indexed matching lines.
    fn extend_visible_lines_per_line(&mut self, idx: &LineIndex, src: &dyn Source) {
        let total = idx.line_count();
        while self.visible_scanned < total {
            let line_n = self.visible_scanned;
            let bytes = idx.line_bytes_stripped(line_n, src);
            if self.line_passes(&bytes) {
                self.visible_lines.push(line_n);
            }
            self.visible_scanned += 1;
        }
    }

    /// Records-mode: evaluate predicates once per record on the full record
    /// bytes (which include embedded `\n`s). All physical lines of a matching
    /// record are pushed to `visible_lines`; non-matching records are dropped
    /// entirely (hide mode). Rebuilds from scratch on each call — O(records)
    /// per frame but acceptable for current workloads; avoids the complexity
    /// of tracking a records-scanned cursor alongside `visible_scanned`.
    fn extend_visible_lines_records(&mut self, idx: &LineIndex, src: &dyn Source) {
        self.visible_lines.clear();
        self.visible_scanned = 0; // not used by records path; reset for clarity
        let total_records = idx.record_count();
        for r in 0..total_records {
            if self.record_passes(idx, src, r) {
                for line_n in idx.record_line_range(r) {
                    self.visible_lines.push(line_n);
                }
            }
        }
    }

    /// Combined predicate: bytes pass iff the (optional) filter matches AND
    /// the (optional) grep matches. Missing predicates vacuously pass.
    /// `bytes` is always a single logical line — records-mode callers go
    /// through `record_passes` instead because the two predicates have
    /// different granularity (filter = header line, grep = whole record).
    fn line_passes(&self, line: &[u8]) -> bool {
        let filter_ok = match self.filter.as_ref() {
            Some(f) => matches!(f.evaluate(line, self.opts.encoding), FilterMatch::Matched),
            None => true,
        };
        let grep_ok = match self.grep.as_ref() {
            Some(g) => g.matches(line, self.opts.encoding),
            None => true,
        };
        filter_ok && grep_ok && self.or_groups.matches_line(line, self.opts.encoding)
    }

    /// Records-mode predicate. Both filter and grep are evaluated against
    /// the full multi-line record bytes. Filter uses the format regex with
    /// dotall + multi-line semantics so greedy captures like
    /// `(?P<message>.*)$` span the whole record body — `--filter
    /// message~foo` matches when `foo` appears anywhere in the record, not
    /// only on the header. Grep matches anywhere in the record bytes too,
    /// so `(?s)foo.*bar` keeps working across continuation lines.
    fn record_passes(&self, idx: &LineIndex, src: &dyn Source, r: usize) -> bool {
        let need = self.filter.is_some() || self.grep.is_some() || self.or_groups.is_active();
        let bytes = if need {
            Some(idx.record_bytes_stripped(r, src))
        } else {
            None
        };
        let filter_ok = match self.filter.as_ref() {
            Some(f) => matches!(
                f.evaluate_record(bytes.as_deref().unwrap(), self.opts.encoding),
                FilterMatch::Matched,
            ),
            None => true,
        };
        let grep_ok = match self.grep.as_ref() {
            Some(g) => g.matches(bytes.as_deref().unwrap(), self.opts.encoding),
            None => true,
        };
        let or_ok = if self.or_groups.is_active() {
            self.or_groups.matches_record(bytes.as_deref().unwrap(), self.opts.encoding)
        } else {
            true
        };
        filter_ok && grep_ok && or_ok
    }

    /// Return true iff line `line_n` should be rendered dim. In records mode,
    /// the match decision is made once per record and applied to all its
    /// physical lines. In line mode, the decision is made per line.
    fn should_dim_line(&self, line_n: usize, idx: &LineIndex, src: &dyn Source) -> bool {
        if !self.dim_mode {
            return false;
        }
        if idx.records_mode() {
            let r = idx.line_to_record(line_n);
            !self.record_passes(idx, src, r)
        } else {
            let bytes = idx.line_bytes_stripped(line_n, src);
            !self.line_passes(&bytes)
        }
    }

    /// Logical line index of the *last* row drawn in the body, given the
    /// current `top_line` and `body_rows`. In line mode this is just
    /// `top_line + body_rows - 1` clamped to the indexed line count. In hide
    /// mode it's the logical line that sits at the bottom of the visible
    /// slice — i.e. `visible_lines[cur + body_rows - 1]`. Always returns a
    /// value `>= self.top_line`, so callers passing it to `line_to_record`
    /// never get a "bottom record < top record" inversion.
    fn bottom_visible_line(&self, idx: &LineIndex) -> usize {
        let body_rows = self.body_rows() as usize;
        if self.hide_mode() && !self.visible_lines.is_empty() {
            let cur = self
                .visible_lines
                .iter()
                .position(|&l| l >= self.top_line)
                .unwrap_or(self.visible_lines.len().saturating_sub(1));
            let last_pos = (cur + body_rows.saturating_sub(1)).min(self.visible_lines.len() - 1);
            return self.visible_lines[last_pos];
        }
        let total = idx.line_count();
        if total == 0 {
            return self.top_line;
        }
        (self.top_line + body_rows.saturating_sub(1)).min(total - 1)
    }

    pub fn body_rows(&self) -> u16 { self.rows.saturating_sub(1).max(1) }

    pub fn follow_mode(&self) -> bool { self.follow_mode }

    /// Conditionally turn follow mode off. Used by motion handlers when
    /// `--follow-suspend-on-motion` is in effect — any motion (scroll,
    /// page, goto-line) suspends following until the user re-engages
    /// with Shift-F.
    pub fn suspend_follow_if(&mut self, flag: bool) {
        if flag {
            self.follow_mode = false;
        }
    }

    pub fn set_follow_mode(&mut self, on: bool) { self.follow_mode = on; }

    pub fn toggle_follow(&mut self) { self.follow_mode = !self.follow_mode; }

    pub fn live_mode(&self) -> bool { self.live_mode }

    pub fn set_live_mode(&mut self, on: bool) { self.live_mode = on; }

    /// Status-line label for active pretty-print state, e.g. `"json"` or
    /// `"json:err"`. `None` means no indicator is shown.
    pub fn set_prettify_label(&mut self, label: Option<String>) {
        self.prettify_label = label;
    }

    /// Active --format name shown in <format-tag>. Set from main when a named
    /// format is resolved; independent of whether --filter is also active.
    pub fn set_format_label(&mut self, label: Option<String>) {
        self.format_label = label;
    }

    /// Returns the active format label (the name passed to `set_format_label`),
    /// or `None` if no named format is active.
    pub fn format_label(&self) -> Option<&str> {
        self.format_label.as_deref()
    }

    /// Drop the per-line filter-membership cache without disturbing the filter
    /// itself or scroll position. Used after a `--live` rebuild: line numbering
    /// may have changed, so cached `visible_lines` is stale, but we want to
    /// keep the same filter applied and let the user stay where they were.
    pub fn invalidate_filter_cache(&mut self) {
        self.visible_lines.clear();
        self.visible_scanned = 0;
    }

    /// Clamp `top_line` so it doesn't fall past the new end of the source.
    /// Pairs with `invalidate_filter_cache` after a content rewrite.
    pub fn clamp_top_line(&mut self, line_count: usize) {
        if line_count == 0 {
            self.top_line = 0;
            self.top_row = 0;
        } else if self.top_line >= line_count {
            self.top_line = line_count - 1;
            self.top_row = 0;
        }
    }

    /// True when the viewport's body window already covers the last line of
    /// the source. New content added past this point should auto-scroll if
    /// follow mode is on.
    pub fn is_at_bottom(&self, src: &dyn Source, idx: &LineIndex) -> bool {
        #[cfg(feature = "image")]
        if self.image_mode {
            return self.is_at_bottom_image();
        }
        if self.hide_mode() {
            // Wrap-aware: at the bottom once (top_line, top_row) is at/after
            // the visible-line anchor that puts the last match's tail on the
            // last body row.
            (self.top_line, self.top_row) >= self.hide_bottom_anchor(src, idx)
        } else {
            // Compare in display-row units against the wrap-aware bottom
            // anchor — `top_line + body >= line_count` would read true while
            // a wrapped tail is still off-screen below.
            (self.top_line, self.top_row) >= self.bottom_anchor(src, idx)
        }
    }

    /// Width of the line-number gutter (digits + 1 space separator), 0 if disabled.
    fn gutter_width(&self, idx: &LineIndex) -> u16 {
        if !self.show_line_numbers { return 0; }
        let n = idx.line_count().max(1);
        let digits = (n as f64).log10().floor() as u16 + 1;
        digits + 1
    }

    fn render_opts(&self, gutter: u16) -> RenderOpts {
        let mut o = self.opts.clone();
        // The status column (`-J`) reserves a fixed far-left cell outside the
        // scrolled content, so its width comes off the content budget too.
        o.cols = self.cols.saturating_sub(self.status_col_width() + gutter);
        o.mode = self.ansi_mode;
        o.left_col = self.left_col;   // horizontal scroll offset carried into the kernel
        o.frozen_cols = self.header_cols; // kernel ignores it in wrap mode
        o
    }

    pub fn frame(&mut self, src: &dyn Source, idx: &mut LineIndex) -> Frame {
        #[cfg(feature = "image")]
        if self.image_mode {
            return self.frame_image();
        }
        if self.hex_mode {
            return self.frame_hex(src);
        }
        let body_rows = self.body_rows() as usize;
        idx.extend_to_line(self.top_line + body_rows + 1, src);

        // Clamp horizontal scroll to the widest line currently visible, so we
        // never scroll into empty space. (Chop/text path only.)
        if self.left_col > 0 && self.hscroll_active() {
            let gutter_for_clamp = self.status_col_width() + self.gutter_width(idx);
            let avail = self.cols.saturating_sub(gutter_for_clamp) as usize;
            // Build opts with left_col=0 — display_width measures full line width
            // regardless of the current scroll offset.
            let mut width_opts = self.opts.clone();
            width_opts.cols = self.cols.saturating_sub(gutter_for_clamp);
            width_opts.mode = self.ansi_mode;
            width_opts.left_col = 0;
            let mut widest = 0usize;
            let total_lines_for_clamp = idx.line_count();
            if self.hide_mode() {
                let hide_pos = self.visible_lines.iter()
                    .position(|&l| l >= self.top_line)
                    .unwrap_or(self.visible_lines.len());
                let end_vi = (hide_pos + body_rows).min(self.visible_lines.len());
                for vi in hide_pos..end_vi {
                    let ln = self.visible_lines[vi];
                    let bytes = self.line_display_bytes(src, idx, ln);
                    widest = widest.max(crate::render::display_width(&bytes, &width_opts));
                }
            } else {
                let start = self.top_line.max(self.header_lines);
                let end = (start + body_rows).min(total_lines_for_clamp);
                for ln in start..end {
                    let bytes = self.line_display_bytes(src, idx, ln);
                    widest = widest.max(crate::render::display_width(&bytes, &width_opts));
                }
            }
            let max_left = if self.header_cols > 0 && self.header_cols + 1 < avail {
                // Frozen engaged: scrollable window = avail - C - 1, scrollable
                // content = widest - C.
                widest.saturating_sub(self.header_cols)
                    .saturating_sub(avail - self.header_cols - 1)
            } else {
                widest.saturating_sub(avail)
            };
            self.left_col = self.left_col.min(max_left);
        }

        let gutter = self.gutter_width(idx);
        let scol = self.status_col_width();
        let r_opts = self.render_opts(gutter);

        // Reconstruct per-line SGR state for the start of the visible window so
        // that unclosed SGR sequences on lines above top_line carry through.
        // Only meaningful in Interpret mode; harmless (and cheap) to skip otherwise.
        let mut render_state = if self.ansi_mode == crate::render::AnsiMode::Interpret {
            reconstruct_render_state(src, idx, self.top_line)
        } else {
            crate::render::RenderState::default()
        };
        // Store in the struct field for future cache use; mark current top_line.
        self.render_state = render_state.clone();
        self.render_state_for = self.top_line;

        let mut body: Vec<Vec<Cell>> = Vec::with_capacity(body_rows);
        let mut row_styles: Vec<RowStyle> = Vec::with_capacity(body_rows);
        let mut highlights: Vec<Vec<std::ops::Range<usize>>> = Vec::with_capacity(body_rows);
        let mut raw_rows: Vec<Option<Vec<u8>>> = Vec::with_capacity(body_rows);
        let raw_passthrough = self.ansi_mode == crate::render::AnsiMode::Raw;
        // In hide mode we walk visible_lines; otherwise we walk logical lines.
        let hide = self.hide_mode();
        let total_lines = idx.line_count();

        // `--header=L`: pin the first L source lines as the top L rows of
        // the body. Renders only the first cell-row of each pinned line
        // (matches less semantics; long pinned lines truncate). Skipped in
        // hide mode where "first L lines" might not be visible. Skipped in
        // raw passthrough since the user's intent there is byte-faithful
        // emission, not pinned headers.
        let header_rows = if !hide && !raw_passthrough {
            self.header_lines.min(body_rows).min(total_lines)
        } else {
            0
        };
        if header_rows > 0 {
            for hl in 0..header_rows {
                let raw = src.bytes(idx.line_range(hl, src));
                let display_bytes = if let Some(r) = self.display.as_ref() {
                    match r.render_line(&raw, self.opts.encoding) {
                        Some(s) => std::borrow::Cow::Owned(s.into_bytes()),
                        None => raw.clone(),
                    }
                } else {
                    raw.clone()
                };
                let rows = render_line(&display_bytes, &r_opts, None);
                let mut content_row = rows.into_iter().next().unwrap_or_else(|| {
                    let mut v = Vec::with_capacity(self.cols as usize);
                    while v.len() < self.cols as usize { v.push(Cell::Empty); }
                    v
                });
                let mut full: Vec<Cell> = Vec::with_capacity(self.cols as usize);
                if scol > 0 {
                    let matched = self.search.as_ref()
                        .is_some_and(|s| !find_row_highlights(&content_row, &s.regex).is_empty());
                    let glyph = self.status_glyph(hl, matched);
                    full.push(Self::status_cell(glyph));
                }
                if gutter > 0 {
                    let label = format!("{:>width$} ", hl + 1, width = (gutter as usize - 1));
                    for c in label.chars() {
                        full.push(Cell::Char {
                            ch: c,
                            width: 1,
                            style: crate::ansi::Style::default(),
                            hyperlink: None,
                        });
                    }
                }
                full.append(&mut content_row);
                body.push(full);
                row_styles.push(RowStyle::Normal);
                highlights.push(Vec::new());
                raw_rows.push(None);
            }
        }

        // For hide mode, find where the viewport starts in visible_lines.
        let mut hide_pos = if hide {
            self.visible_lines
                .iter()
                .position(|&l| l >= self.top_line)
                .unwrap_or(self.visible_lines.len())
        } else {
            0
        };
        let mut line_n = if hide {
            self.visible_lines.get(hide_pos).copied().unwrap_or(total_lines)
        } else {
            // When header pinning is on, skip past the pinned region so the
            // scrolling window doesn't show those lines a second time.
            self.top_line.max(self.header_lines)
        };
        let mut skip = if header_rows > 0 { 0 } else { self.top_row };

        while body.len() < body_rows {
            if line_n >= total_lines {
                let mut row = Vec::with_capacity(self.cols as usize);
                if scol > 0 {
                    for _ in 0..scol { row.push(Cell::Empty); }
                }
                if gutter > 0 {
                    for _ in 0..gutter { row.push(Cell::Empty); }
                }
                while row.len() < self.cols as usize { row.push(Cell::Empty); }
                if self.tilde_eof {
                    let at = (scol + gutter) as usize;
                    if at < row.len() {
                        row[at] = Cell::Char {
                            ch: '~',
                            width: 1,
                            style: crate::ansi::Style { dim: true, ..Default::default() },
                            hyperlink: None,
                        };
                    }
                }
                body.push(row);
                row_styles.push(RowStyle::Normal);
                highlights.push(Vec::new());
                raw_rows.push(None);
                line_n += 1;
                continue;
            }
            // Filter evaluation runs on the raw line (it uses captures, not
            // text), but rendering goes through the template if one is set.
            let raw = src.bytes(idx.line_range(line_n, src));
            // `-s` / --squeeze-blank-lines: skip a blank line if its
            // immediate predecessor (in logical-line space) was also blank.
            // Real line numbers / counts in `idx` stay accurate — this is a
            // display-layer filter only.
            if self.squeeze_blanks && line_is_blank(&raw) {
                let prev_blank = line_n.checked_sub(1).is_some_and(|p| {
                    let prev = src.bytes(idx.line_range(p, src));
                    line_is_blank(&prev)
                });
                if prev_blank {
                    line_n += 1;
                    continue;
                }
            }
            let display_bytes = if let Some(r) = self.display.as_ref() {
                match r.render_line(&raw, self.opts.encoding) {
                    Some(s) => std::borrow::Cow::Owned(s.into_bytes()),
                    None => raw.clone(),
                }
            } else {
                raw.clone()
            };
            let state_arg = if self.ansi_mode == crate::render::AnsiMode::Interpret {
                Some(&mut render_state)
            } else {
                None
            };
            let rows = render_line(&display_bytes, &r_opts, state_arg);
            let style = if self.filter.is_some() || self.grep.is_some() {
                if self.dim_mode {
                    if self.should_dim_line(line_n, idx, src) { RowStyle::Dim } else { RowStyle::Normal }
                } else {
                    // hide mode: only matching lines reach here
                    RowStyle::Normal
                }
            } else {
                RowStyle::Normal
            };

            let mut first_emitted_for_this_line = true;
            // `-J` status column: remember the body index of this line's first
            // emitted display row, and whether ANY of its rows hold a search
            // match. We patch the glyph in after rendering the whole line so a
            // match on a wrapped continuation row still flags the first row.
            let mut status_first_row_idx: Option<usize> = None;
            let mut line_matched = false;
            for (i, mut content_row) in rows.into_iter().enumerate() {
                if i < skip { continue; }
                if body.len() >= body_rows { break; }
                // Track whether this line carries a search match for `-J`,
                // matching against the CONTENT only (before the status cell +
                // gutter are prepended) so gutter digits / padding can't
                // falsely flag a `*`. Independent of `hilite_search` (`-G`):
                // the status column reflects matches even when visual
                // highlighting is suppressed.
                if scol > 0 && !line_matched {
                    if let Some(s) = self.search.as_ref() {
                        if !find_row_highlights(&content_row, &s.regex).is_empty() {
                            line_matched = true;
                        }
                    }
                }
                let mut full: Vec<Cell> = Vec::with_capacity(self.cols as usize);
                if scol > 0 {
                    if status_first_row_idx.is_none() {
                        status_first_row_idx = Some(body.len());
                    }
                    // Placeholder blank; patched to the real glyph after the
                    // line's rows are all rendered (so wrapped-row matches count).
                    full.push(Self::status_cell(' '));
                }
                if gutter > 0 {
                    let label = if i == 0 { format!("{:>width$} ", line_n + 1, width = (gutter as usize - 1)) } else { " ".repeat(gutter as usize) };
                    for c in label.chars() {
                        full.push(Cell::Char { ch: c, width: 1, style: crate::ansi::Style::default(), hyperlink: None });
                    }
                }
                full.append(&mut content_row);
                // Paint the `<` left-edge marker when the view is scrolled right
                // in chop mode, so the user can see that content is off-screen left.
                // Mirrors the `>` rscroll marker style (dim). Placed at the first
                // content column (after the status column + gutter, if any).
                if self.left_col > 0 && !self.opts.wrap && self.header_cols == 0 {
                    let marker_col = (scol + gutter) as usize;
                    if let Some(cell) = full.get_mut(marker_col) {
                        *cell = Cell::Char {
                            ch: '<',
                            width: 1,
                            style: crate::ansi::Style { dim: true, ..Default::default() },
                            hyperlink: None,
                        };
                    }
                }
                // Compute search highlights for this display row by running
                // the regex against the row's rendered text. Each match's
                // char range maps to a cell column range via `starts`.
                let row_highlights = if let (true, Some(s)) = (self.hilite_search, self.search.as_ref()) {
                    if self.hilite_only_match {
                        if Some(line_n) == self.last_match_line {
                            let mut h = find_row_highlights(&full, &s.regex);
                            h.truncate(1); // first match on the landed line
                            h
                        } else {
                            Vec::new()
                        }
                    } else {
                        find_row_highlights(&full, &s.regex)
                    }
                } else {
                    Vec::new()
                };
                body.push(full);
                row_styles.push(style);
                highlights.push(row_highlights);
                if raw_passthrough {
                    if first_emitted_for_this_line {
                        // charset does not apply: raw passthrough emits the
                        // original source bytes verbatim so the terminal's own
                        // decoder handles them — intentional bypass of encoding.
                        // Emit the original line bytes verbatim once. Sub-rows
                        // (mid-line wrap continuations) are no-ops — the
                        // terminal will have already consumed enough columns
                        // from the line's full byte stream to fill them.
                        raw_rows.push(Some(raw.to_vec()));
                        first_emitted_for_this_line = false;
                    } else {
                        raw_rows.push(Some(Vec::new()));
                    }
                } else {
                    raw_rows.push(None);
                }
            }
            // `-J`: now that the whole line is rendered, set the first row's
            // status glyph (mark letter beats search-`*`). Continuation rows
            // keep their blank placeholder.
            if let Some(fi) = status_first_row_idx {
                let glyph = self.status_glyph(line_n, line_matched);
                if glyph != ' ' {
                    if let Some(cell) = body[fi].first_mut() {
                        *cell = Self::status_cell(glyph);
                    }
                }
            }
            skip = 0;
            // Advance to next line — visible-space if hiding, logical-space otherwise.
            if hide {
                hide_pos += 1;
                line_n = self.visible_lines.get(hide_pos).copied().unwrap_or(total_lines);
            } else {
                line_n += 1;
            }
        }

        // After walking through the frame, render_state has been advanced past
        // top_line. Invalidate the cached sentinel so next frame re-reconstructs.
        self.render_state_for = usize::MAX;

        let status = self.format_status(idx, src);
        Frame { body, row_styles, highlights, status, status_style: self.status_style, raw_rows, image_blob: None }
    }

    fn format_status(&self, idx: &LineIndex, src: &dyn Source) -> String {
        if let Some(p) = self.prompt.as_ref() {
            let ctx = self.build_prompt_context(idx, src);
            return p.render(&ctx);
        }
        let body_rows = self.body_rows() as usize;
        let total = idx.line_count();
        // In hide mode, the line range and percentage refer to visible (matched)
        // lines, not the underlying logical line count.
        let (top, bottom, total_for_pct, total_str): (usize, usize, usize, String) = if self.hide_mode() {
            let visible_total = self.visible_lines.len();
            // top_line is a logical line; find its visible index.
            let cur = self
                .visible_lines
                .iter()
                .position(|&l| l >= self.top_line)
                .unwrap_or(visible_total);
            let top = cur + 1;
            let bottom = (cur + body_rows).min(visible_total.max(1));
            let total_str = if src.is_complete() {
                format!("{visible_total}/{total}")
            } else {
                format!("{visible_total}/{total}+")
            };
            (top, bottom, visible_total, total_str)
        } else {
            let top = self.top_line + 1;
            let bottom = (self.top_line + body_rows).min(total.max(1));
            let total_str = if src.is_complete() { format!("{total}") } else { format!("{total}+") };
            (top, bottom, total, total_str)
        };
        let pct = (bottom * 100).checked_div(total_for_pct).unwrap_or(0);
        // In records mode, prefix line numbers with 'L' and append an 'R' record block.
        // The R block always refers to logical lines on screen, which in hide
        // mode is *not* the same as `bottom` (which counts visible matches).
        let bottom_line = self.bottom_visible_line(idx);
        let (line_prefix, records_block) = if idx.records_mode() {
            let line_total = idx.line_count();
            let rec_total = idx.record_count();
            let rec_block = if line_total == 0 || rec_total == 0 {
                format!("R0-0/{}", rec_total)
            } else {
                let rec_top = idx.line_to_record(self.top_line) + 1;
                let rec_bottom = idx.line_to_record(bottom_line) + 1;
                let (rec_top, rec_bottom) = if rec_bottom < rec_top {
                    // Defensive: should be unreachable given `bottom_visible_line`
                    // is always `>= self.top_line`, but guard against future
                    // regressions producing nonsense like `R290-8/...`.
                    (rec_top, rec_top)
                } else {
                    (rec_top, rec_bottom)
                };
                format!("R{}-{}/{}", rec_top, rec_bottom, rec_total)
            };
            ("L", Some(rec_block))
        } else {
            ("", None)
        };
        let middle = match records_block {
            Some(ref rb) => format!("{}{}-{}/{}  {}  {}%", line_prefix, top, bottom, total_str, rb, pct),
            None         => format!("{}-{}/{}  {}%", top, bottom, total_str, pct),
        };
        let label_with_index = match self.file_index {
            Some((current, total)) => format!("{}  [{}/{}]", self.source_label, current + 1, total),
            None => self.source_label.clone(),
        };
        let mut s = format!("{}  {}", label_with_index, middle);
        // Wrap-row offset: when scrolled inside a long wrapping line, surface
        // the offset so the user knows scrolling is happening at sub-line
        // granularity. Without this the line range above stays static while
        // pressing `j` and the scroll is invisible on repeating content.
        if !self.hide_mode() && self.top_row > 0 {
            let line_rows = if total > 0 {
                let bytes = self.line_display_bytes(src, idx, self.top_line);
                count_rows(&bytes, &self.render_opts(self.gutter_width(idx)), None)
            } else { 1 };
            s.push_str(&format!("  +{}/{}", self.top_row, line_rows));
        }
        if self.left_col > 0 {
            s.push_str(&format!("  \u{00bb}{}", self.left_col));
        }
        if let Some(f) = self.filter.as_ref() {
            s.push_str(&format!("  [{}]", f.format_name));
        }
        if self.grep.is_some() {
            s.push_str("  [grep]");
        }
        if self.or_groups.is_active() {
            s.push_str("  [or]");
        }
        if self.scroll_lock {
            s.push_str("  [lock]");
        }
        if self.mouse_off {
            s.push_str("  [nomouse]");
        }
        if self.filter.is_some() || self.grep.is_some() || self.or_groups.is_active() {
            s.push_str(if self.dim_mode { "  [dim]" } else { "  [hide]" });
        }
        if let Some(sr) = self.search.as_ref() {
            let prefix = if matches!(sr.direction, SearchDirection::Forward) { "/" } else { "?" };
            s.push_str(&format!("  [{}{}]", prefix, sr.raw));
        }
        if let Some(label) = self.prettify_label.as_ref() {
            s.push_str(&format!("  [pretty:{label}]"));
        }
        if self.live_mode { s.push_str("  (L)"); }
        if self.follow_mode {
            if let Some((msg, _)) = self.status_flash.as_ref() {
                s.push_str("  ");
                s.push_str(msg);
            } else if self.is_idle() {
                s.push_str("  (F idle)");
            } else {
                s.push_str("  (F)");
            }
        }
        if let Some(msg) = self.preprocess_failure.as_ref() {
            let first_line = msg.lines().next().unwrap_or("");
            s.push_str(&format!("  [preprocess-failed: {}]", first_line));
        }
        let tag_suffix = match &self.tag_active {
            Some((name, cur, total)) if *total > 1 => {
                format!("  [tag: {name} ({cur}/{total})]")
            }
            _ => String::new(),
        };
        s.push_str(&tag_suffix);
        // Right-aligned :help hint. If the existing status already overshoots
        // the width, no pad — the renderer will clip on draw.
        let used = s.chars().count();
        let hint = ":help";
        if (self.cols as usize) > used + 1 + hint.chars().count() {
            let pad = self.cols as usize - used - hint.chars().count();
            s.push_str(&" ".repeat(pad));
            s.push_str(hint);
        } else {
            s.push(' ');
            s.push_str(hint);
        }
        s
    }

    fn build_prompt_context(&self, idx: &LineIndex, src: &dyn Source) -> crate::prompt::PromptContext {
        use crate::prompt::PromptContext;

        let body_rows = self.body_rows() as usize;
        let total = idx.line_count();
        let top = self.top_line + 1;
        let bottom = (self.top_line + body_rows).min(total.max(1));
        let pct = (bottom * 100).checked_div(total).unwrap_or(0);
        let bottom_line = self.bottom_visible_line(idx);

        let records_mode = idx.records_mode();
        let (rec_top, rec_bottom, rec_total) = if records_mode {
            let rt = idx.line_to_record(self.top_line) + 1;
            let rb_raw = idx.line_to_record(bottom_line) + 1;
            let rb = if rb_raw < rt { rt } else { rb_raw };
            (rt, rb, idx.record_count())
        } else {
            (0, 0, 0)
        };

        let wrap_offset = if !self.hide_mode() && self.top_row > 0 {
            let line_rows = if total > 0 {
                let bytes = self.line_display_bytes(src, idx, self.top_line);
                count_rows(&bytes, &self.render_opts(self.gutter_width(idx)), None)
            } else { 1 };
            format!("+{}/{}", self.top_row, line_rows)
        } else {
            String::new()
        };

        let col_offset = if self.left_col > 0 { format!("  \u{00bb}{}", self.left_col) } else { String::new() };

        let format_tag = self.format_label.as_ref()
            .map(|n| format!("  [{}]", n))
            .unwrap_or_default();
        let filter_tag = self.filter.as_ref()
            .map(|f| format!("  [{}]", f.format_name))
            .unwrap_or_default();
        let grep_tag = if self.grep.is_some() { "  [grep]".to_string() } else { String::new() };
        let or_tag = if self.or_groups.is_active() { "  [or]".to_string() } else { String::new() };
        let hide_tag = if self.filter.is_some() || self.grep.is_some() || self.or_groups.is_active() {
            if self.dim_mode { "  [dim]".to_string() } else { "  [hide]".to_string() }
        } else {
            String::new()
        };
        let search_tag = self.search.as_ref()
            .map(|s| {
                let p = if matches!(s.direction, SearchDirection::Forward) { "/" } else { "?" };
                format!("  [{}{}]", p, s.raw)
            })
            .unwrap_or_default();
        let pretty_tag = self.prettify_label.as_ref()
            .map(|l| format!("  [pretty:{l}]"))
            .unwrap_or_default();
        let live_tag = if self.live_mode { "  (L)".to_string() } else { String::new() };
        let follow_tag = if self.follow_mode { "  (F)".to_string() } else { String::new() };
        let preprocess_failed_tag = self.preprocess_failure.as_ref()
            .map(|msg| {
                let first_line = msg.lines().next().unwrap_or("");
                format!("  [preprocess-failed: {}]", first_line)
            })
            .unwrap_or_default();

        let file_index_tag = match self.file_index {
            Some((current, total)) => format!("  [{}/{}]", current + 1, total),
            None => String::new(),
        };

        let tag_tag = match &self.tag_active {
            Some((name, cur, total)) if *total > 1 => {
                format!("  [tag: {name} ({cur}/{total})]")
            }
            _ => String::new(),
        };

        let lock = if self.scroll_lock { "lock".to_string() } else { String::new() };
        let mouse_tag = if self.mouse_off { "nomouse".to_string() } else { String::new() };

        PromptContext {
            label: self.source_label.clone(),
            top,
            bottom,
            total,
            pct: pct.min(100) as u8,
            rec_top,
            rec_bottom,
            rec_total,
            records_mode,
            wrap_offset,
            col_offset,
            format_tag,
            filter_tag,
            grep_tag,
            or_tag,
            lock,
            mouse_tag,
            hide_tag,
            search_tag,
            pretty_tag,
            live_tag,
            follow_tag,
            preprocess_failed_tag,
            file_index_tag,
            tag_tag,
        }
    }

    fn frame_hex(&self, src: &dyn Source) -> Frame {
        use crate::hex::format_hex_row;
        use crate::render::{render_line, Cell, RenderOpts};

        let body_rows = self.rows.saturating_sub(1) as usize;
        let total_bytes = src.len();
        let total_hex_rows = total_bytes.div_ceil(16);

        let mut body: Vec<Vec<Cell>> = Vec::with_capacity(body_rows);
        let mut row_styles: Vec<RowStyle> = Vec::with_capacity(body_rows);
        let mut highlights: Vec<Vec<std::ops::Range<usize>>> = Vec::with_capacity(body_rows);

        // charset does not apply: hex shows raw source bytes as hex digits —
        // encoding is meaningless here; the formatter works on byte values directly.
        let opts = RenderOpts { cols: self.cols, wrap: false, tab_width: 1, mode: crate::render::AnsiMode::Strict, rscroll_char: None, word_wrap: false, left_col: 0, frozen_cols: 0, tab_stops: None, encoding: crate::charset::Encoding::utf8() };

        for row_idx in 0..body_rows {
            let hex_row = self.top_line + row_idx;
            if hex_row >= total_hex_rows {
                body.push(vec![Cell::Empty; self.cols as usize]);
            } else {
                let offset = hex_row * 16;
                let end = (offset + 16).min(total_bytes);
                let bytes_cow = src.bytes(offset..end);
                let text = format_hex_row(offset, &bytes_cow, self.hex_group_size);
                let rows = render_line(text.as_bytes(), &opts, None);
                body.push(rows.into_iter().next().unwrap_or_else(|| {
                    vec![Cell::Empty; self.cols as usize]
                }));
            }
            row_styles.push(RowStyle::Normal);
            highlights.push(Vec::new());
        }

        let status = self.format_status_hex(src);
        let raw_rows = vec![None; body.len()];
        Frame { body, row_styles, highlights, status, status_style: self.status_style, raw_rows, image_blob: None }
    }

    fn format_status_hex(&self, src: &dyn Source) -> String {
        let total_bytes = src.len();
        let body_rows = self.rows.saturating_sub(1) as usize;
        // Byte offset of the first visible byte (start of the top hex row).
        let top_byte = self.top_line * 16;
        // Byte offset just past the last visible byte. Clamped to total_bytes
        // so we never show a value past EOF.
        let bottom_byte = ((self.top_line + body_rows) * 16).min(total_bytes);
        let pct = (bottom_byte * 100).checked_div(total_bytes).unwrap_or(0);
        let label_with_index = match self.file_index {
            Some((current, total)) => format!("{}  [{}/{}]", self.source_label, current + 1, total),
            None => self.source_label.clone(),
        };
        let tag_suffix = match &self.tag_active {
            Some((name, cur, total)) if *total > 1 => {
                format!("  [tag: {name} ({cur}/{total})]")
            }
            _ => String::new(),
        };
        format!(
            "{}  off {}-{}/{}  {}%  [hex]{}",
            label_with_index, top_byte, bottom_byte, total_bytes, pct, tag_suffix
        )
    }

    #[cfg(feature = "image")]
    fn frame_image(&mut self) -> Frame {
        use crate::render::Cell;
        if self.image_protocol != ImageProtocol::Ascii {
            return self.frame_image_protocol();
        }
        let body_rows = self.body_rows() as usize;
        let cols = self.cols as usize;
        let img = match self.current_image() {
            Some(i) => i,
            None => {
                let body = vec![vec![Cell::Empty; cols]; body_rows];
                return Frame {
                    body,
                    row_styles: vec![RowStyle::Normal; body_rows],
                    highlights: vec![Vec::new(); body_rows],
                    status: self.image_format.clone(),
                    status_style: self.status_style,
                    raw_rows: vec![None; body_rows],
                    image_blob: None,
                };
            }
        };
        let color = !self.image_no_color;
        let grid = crate::image_render::render_image(img, self.image_cols(), self.image_style, color);
        let grid_w = grid.first().map(|r| r.len()).unwrap_or(0);
        let max_off = grid_w.saturating_sub(cols);
        if self.left_col > max_off { self.left_col = max_off; }
        let off = self.left_col;
        let mut body: Vec<Vec<Cell>> = Vec::with_capacity(body_rows);
        for r in 0..body_rows {
            let gi = self.top_line + r;
            if gi < grid.len() {
                let mut row: Vec<Cell> = grid[gi].iter().skip(off).take(cols).cloned().collect();
                while row.len() < cols { row.push(Cell::Empty); }
                body.push(row);
            } else {
                body.push(vec![Cell::Empty; cols]);
            }
        }
        let status = self.format_status_image(grid.len());
        Frame {
            body,
            row_styles: vec![RowStyle::Normal; body_rows],
            highlights: vec![Vec::new(); body_rows],
            status,
            status_style: self.status_style,
            raw_rows: vec![None; body_rows],
            image_blob: None,
        }
    }

    #[cfg(feature = "image")]
    fn format_status_image(&self, total_rows: usize) -> String {
        let body = self.body_rows() as usize;
        let top = self.top_line + 1;
        let bottom = (self.top_line + body).min(total_rows.max(1));
        let dims = self.current_image().map(|i| { let (w, h) = i.dimensions(); format!("{w}×{h}") }).unwrap_or_default();
        let mut s = format!("{}  {}  {}  rows {}-{}/{}", self.source_label, dims, self.image_format, top, bottom, total_rows);
        if self.left_col > 0 {
            s.push_str(&format!("  \u{00bb}{}", self.left_col));
        }
        s.push_str(&self.anim_badge());
        s
    }

    #[cfg(feature = "image")]
    fn frame_image_protocol(&mut self) -> Frame {
        use crate::render::Cell;
        let body_rows = self.body_rows() as usize;
        let cols = self.cols as usize;
        let status_style = self.status_style;
        let blank = |status: String, blob: Option<Vec<u8>>| Frame {
            body: vec![vec![Cell::Empty; cols]; body_rows],
            row_styles: vec![RowStyle::Normal; body_rows],
            highlights: vec![Vec::new(); body_rows],
            status,
            status_style,
            raw_rows: vec![None; body_rows],
            image_blob: blob,
        };
        let (iw, ih) = match self.current_image() {
            Some(i) => i.dimensions(),
            None => return blank(self.image_format.clone(), None),
        };
        let ch = self.cell_px.1.max(1) as u32;
        let (scaled_w, scaled_h) = protocol_scaled_dims(iw, ih, self.cols, self.cell_px, self.image_width);

        // Build / reuse the width-scaled image.
        let need = self.image_scaled.as_ref().map(|(c, _)| *c != scaled_w as u16).unwrap_or(true);
        if need {
            let scaled = {
                let src = self.current_image().unwrap();
                image::imageops::resize(src, scaled_w, scaled_h, image::imageops::FilterType::Triangle)
            };
            self.image_scaled = Some((scaled_w as u16, scaled));
        }

        let total_rows = protocol_occupied_rows(iw, ih, self.cols, self.cell_px, self.image_width);
        let max_top = total_rows.saturating_sub(body_rows);
        if self.top_line > max_top { self.top_line = max_top; }
        self.left_col = 0; // horizontal scroll is a no-op in protocol mode

        let y0 = (self.top_line as u32 * ch).min(scaled_h);
        let band_h = ((body_rows as u32) * ch).min(scaled_h - y0).max(1);
        let scaled = &self.image_scaled.as_ref().unwrap().1;
        let band = image::imageops::crop_imm(scaled, 0, y0, scaled_w, band_h).to_image();
        let blob = match self.image_protocol {
            ImageProtocol::Kitty => crate::image_protocol::encode_kitty(&band),
            ImageProtocol::Sixel => crate::image_protocol::encode_sixel(&band),
            ImageProtocol::Ascii => unreachable!("frame_image_protocol only entered for non-Ascii"),
        };
        let status = self.format_status_image_protocol(total_rows);
        blank(status, Some(blob))
    }

    #[cfg(feature = "image")]
    fn format_status_image_protocol(&self, total_rows: usize) -> String {
        let body = self.body_rows() as usize;
        let top = self.top_line + 1;
        let bottom = (self.top_line + body).min(total_rows.max(1));
        let proto = match self.image_protocol {
            ImageProtocol::Kitty => "kitty",
            ImageProtocol::Sixel => "sixel",
            ImageProtocol::Ascii => "ascii",
        };
        let dims = self.current_image().map(|i| { let (w, h) = i.dimensions(); format!("{w}×{h}") }).unwrap_or_default();
        format!("{}  {}  {}  [{}]  rows {}-{}/{}{}", self.source_label, dims, self.image_format, proto, top, bottom, total_rows, self.anim_badge())
    }

    /// Jump by whole logical lines, regardless of wrap rows. `top_row` is
    /// reset to 0 so the start of the destination line is at the top of
    /// the viewport. In hide mode this is equivalent to `scroll_lines`
    /// (which already moves by visible/logical lines).
    pub fn scroll_logical_lines(&mut self, delta: i64, src: &dyn Source, idx: &mut LineIndex) {
        if delta == 0 { return; }
        #[cfg(feature = "image")]
        if self.image_mode {
            self.scroll_lines(delta, src, idx);
            return;
        }
        if self.hide_mode() {
            // J/K move by whole visible lines (ignoring wrap rows), with K
            // first snapping to the start of the current line — the visible-
            // line analogue of the non-hide branch below.
            self.extend_visible_lines(idx, src);
            let n = self.visible_lines.len();
            if n == 0 {
                self.top_line = 0;
                self.top_row = 0;
                return;
            }
            let vi = self
                .visible_lines
                .iter()
                .position(|&l| l >= self.top_line)
                .unwrap_or(n - 1);
            if delta > 0 {
                let target = (vi + delta as usize).min(n - 1);
                self.top_line = self.visible_lines[target];
                self.top_row = 0;
            } else {
                let back = (-delta) as usize;
                let consumed_for_snap = if self.top_row > 0 { 1 } else { 0 };
                let extra_back = back.saturating_sub(consumed_for_snap);
                self.top_line = self.visible_lines[vi.saturating_sub(extra_back)];
                self.top_row = 0;
            }
            return;
        }
        if delta > 0 {
            idx.extend_to_line(self.top_line + delta as usize + 1, src);
            let total = idx.line_count();
            if total == 0 { return; }
            let target = (self.top_line as i64 + delta).min(total as i64 - 1) as usize;
            self.top_line = target;
            self.top_row = 0;
        } else {
            let back = (-delta) as usize;
            // If we're inside a wrapped line (top_row > 0), `K` first snaps to
            // the start of the current line; only the remaining count goes to
            // previous lines. This matches the user's mental model of "jump
            // to the start of the previous line".
            let consumed_for_snap = if self.top_row > 0 { 1 } else { 0 };
            let extra_back = back.saturating_sub(consumed_for_snap);
            self.top_line = self.top_line.saturating_sub(extra_back);
            self.top_row = 0;
        }
    }

    pub fn scroll_lines(&mut self, delta: i64, src: &dyn Source, idx: &mut LineIndex) {
        if delta == 0 { return; }
        #[cfg(feature = "image")]
        if self.image_mode {
            let total = self.image_total_rows();
            let body = self.body_rows() as usize;
            let max_top = total.saturating_sub(body);
            let next = (self.top_line as i64 + delta).clamp(0, max_top as i64);
            self.top_line = next as usize;
            self.top_row = 0;
            return;
        }
        if self.hide_mode() {
            // Scroll by display rows over the visible (matching) lines, honoring
            // wrap rows via top_row — the same model as the non-hide branch
            // below, but walking visible_lines instead of every line.
            self.extend_visible_lines(idx, src);
            let n = self.visible_lines.len();
            if n == 0 {
                self.top_line = 0;
                self.top_row = 0;
                return;
            }
            let mut vi = self
                .visible_lines
                .iter()
                .position(|&l| l >= self.top_line)
                .unwrap_or(n - 1);
            // Keep top anchored on a real visible line; a top_row only means
            // something relative to one.
            if self.visible_lines[vi] != self.top_line {
                self.top_row = 0;
            }
            self.top_line = self.visible_lines[vi];
            let r_opts = self.render_opts(self.gutter_width(idx));
            if delta > 0 {
                let mut remaining = delta as usize;
                while remaining > 0 {
                    let line = self.visible_lines[vi];
                    let rows = count_rows(&self.line_display_bytes(src, idx, line), &r_opts, None).max(1);
                    if self.top_row + 1 < rows {
                        self.top_row += 1;
                    } else if vi + 1 < n {
                        self.top_row = 0;
                        vi += 1;
                        self.top_line = self.visible_lines[vi];
                    } else {
                        break;
                    }
                    remaining -= 1;
                }
                let anchor = self.hide_bottom_anchor(src, idx);
                if (self.top_line, self.top_row) > anchor {
                    self.top_line = anchor.0;
                    self.top_row = anchor.1;
                }
            } else {
                let mut remaining = (-delta) as usize;
                while remaining > 0 {
                    if self.top_row > 0 {
                        self.top_row -= 1;
                    } else if vi > 0 {
                        vi -= 1;
                        self.top_line = self.visible_lines[vi];
                        let line = self.visible_lines[vi];
                        let rows = count_rows(&self.line_display_bytes(src, idx, line), &r_opts, None).max(1);
                        self.top_row = rows.saturating_sub(1);
                    } else {
                        break;
                    }
                    remaining -= 1;
                }
            }
            return;
        }
        if delta > 0 {
            let mut remaining = delta as usize;
            while remaining > 0 {
                idx.extend_to_line(self.top_line + 1, src);
                let total = idx.line_count();
                if total == 0 { break; }
                let bytes = self.line_display_bytes(src, idx, self.top_line);
                let line_rows = count_rows(&bytes, &self.render_opts(self.gutter_width(idx)), None);
                if self.top_row + 1 < line_rows {
                    self.top_row += 1;
                } else if self.top_line + 1 < total {
                    self.top_row = 0;
                    self.top_line += 1;
                } else {
                    break;
                }
                remaining -= 1;
            }
            // Don't scroll past the natural bottom (the last line resting on
            // the last body row). Only clamp once the source is fully
            // scanned — mid-scan the true end is unknown, and clamping to a
            // partial index would strand the viewport short of unread content.
            if idx.scanned_through() >= src.len() {
                let anchor = self.bottom_anchor(src, idx);
                if (self.top_line, self.top_row) > anchor {
                    self.top_line = anchor.0;
                    self.top_row = anchor.1;
                }
            }
        } else {
            let mut remaining = (-delta) as usize;
            while remaining > 0 {
                if self.top_row > 0 {
                    self.top_row -= 1;
                } else if self.top_line > 0 {
                    self.top_line -= 1;
                    let bytes = self.line_display_bytes(src, idx, self.top_line);
                    let line_rows = count_rows(&bytes, &self.render_opts(self.gutter_width(idx)), None);
                    self.top_row = line_rows.saturating_sub(1);
                } else {
                    break;
                }
                remaining -= 1;
            }
        }
    }

    pub fn page_down(&mut self, src: &dyn Source, idx: &mut LineIndex) {
        let n = self.page_size
            .map(|p| p as i64)
            .unwrap_or_else(|| self.body_rows() as i64);
        self.scroll_lines(n, src, idx);
    }

    pub fn page_up(&mut self, src: &dyn Source, idx: &mut LineIndex) {
        let n = self.page_size
            .map(|p| p as i64)
            .unwrap_or_else(|| self.body_rows() as i64);
        self.scroll_lines(-n, src, idx);
    }

    pub fn half_page_down(&mut self, src: &dyn Source, idx: &mut LineIndex) {
        let n = (self.body_rows() / 2).max(1) as i64;
        self.scroll_lines(n, src, idx);
    }

    pub fn half_page_up(&mut self, src: &dyn Source, idx: &mut LineIndex) {
        let n = (self.body_rows() / 2).max(1) as i64;
        self.scroll_lines(-n, src, idx);
    }

    pub fn goto_top(&mut self) {
        self.top_line = 0;
        self.top_row = 0;
    }

    /// The top `(line, row)` position such that the source's final display row
    /// lands on the last body row. Computed in display-row units by walking
    /// backward from the end, so it stays correct when lines wrap (the
    /// default): the last `body` logical lines can occupy more than `body`
    /// rows. Returns `(0, 0)` when the whole document fits within the body.
    /// Non-hide-mode only — hide mode scrolls by whole visible lines.
    fn bottom_anchor(&self, src: &dyn Source, idx: &LineIndex) -> (usize, usize) {
        let body = self.body_rows() as usize;
        let total = idx.line_count();
        if total == 0 || body == 0 {
            return (0, 0);
        }
        let r_opts = self.render_opts(self.gutter_width(idx));
        let mut remaining = body;
        let mut line = total - 1;
        loop {
            let bytes = self.line_display_bytes(src, idx, line);
            let line_rows = count_rows(&bytes, &r_opts, None).max(1);
            if line_rows >= remaining {
                return (line, line_rows - remaining);
            }
            remaining -= line_rows;
            if line == 0 {
                return (0, 0);
            }
            line -= 1;
        }
    }

    /// Hide-mode bottom anchor, in display-row units over the *visible*
    /// (matching) lines: the top `(line, row)` such that the last visible
    /// line's final wrap row lands on the last body row. Mirrors
    /// `bottom_anchor`, but walks `visible_lines` instead of every line.
    fn hide_bottom_anchor(&self, src: &dyn Source, idx: &LineIndex) -> (usize, usize) {
        let body = self.body_rows() as usize;
        let n = self.visible_lines.len();
        if n == 0 || body == 0 {
            return (0, 0);
        }
        let r_opts = self.render_opts(self.gutter_width(idx));
        let mut remaining = body;
        let mut vi = n - 1;
        loop {
            let line = self.visible_lines[vi];
            let rows = count_rows(&self.line_display_bytes(src, idx, line), &r_opts, None).max(1);
            if rows >= remaining {
                return (line, rows - remaining);
            }
            remaining -= rows;
            if vi == 0 {
                return (self.visible_lines[0], 0);
            }
            vi -= 1;
        }
    }

    pub fn goto_bottom(&mut self, src: &dyn Source, idx: &mut LineIndex) {
        #[cfg(feature = "image")]
        if self.image_mode {
            let body = self.body_rows() as usize;
            self.top_line = self.image_total_rows().saturating_sub(body);
            self.top_row = 0;
            return;
        }
        idx.extend_to_end(src);
        if self.hide_mode() {
            self.extend_visible_lines(idx, src);
            let (line, row) = self.hide_bottom_anchor(src, idx);
            self.top_line = line;
            self.top_row = row;
        } else {
            let (line, row) = self.bottom_anchor(src, idx);
            self.top_line = line;
            self.top_row = row;
        }
    }

    /// Position the viewport so line `n` (0-indexed) is the top visible line.
    pub fn goto_line(&mut self, n: usize, src: &dyn Source, idx: &mut LineIndex) {
        idx.extend_to_line(n, src);
        let target = n.min(idx.line_count().saturating_sub(1));
        self.top_line = target;
        self.top_row = 0;
    }

    /// Position the viewport at the start of record `n` (0-indexed).
    pub fn goto_record(&mut self, n: usize, src: &dyn Source, idx: &mut LineIndex) {
        // Ensure the record exists by extending the index. Records can only
        // appear after their constituent lines are scanned; extend repeatedly
        // until the record exists or we hit EOF.
        while idx.record_count() <= n && idx.scanned_through() < src.len() {
            idx.extend_to_end(src);
        }
        if idx.record_count() == 0 {
            return;
        }
        let target = n.min(idx.record_count().saturating_sub(1));
        let line_range = idx.record_line_range(target);
        self.top_line = line_range.start;
        self.top_row = 0;
    }

    /// Position the viewport at `p` percent through the file by bytes.
    /// `p` is clamped to 0..=100. p=100 lands at the last line.
    pub fn goto_percent(&mut self, p: u8, src: &dyn Source, idx: &mut LineIndex) {
        let p = p.min(100) as usize;
        let target_byte = src.len().saturating_mul(p) / 100;
        idx.extend_to_byte_for_query(src, target_byte);
        let line_n = idx.line_at_byte(target_byte)
            .or_else(|| {
                // target_byte at or past EOF: fall through to the last line.
                let lc = idx.line_count();
                if lc > 0 { Some(lc - 1) } else { None }
            })
            .unwrap_or(0);
        self.top_line = line_n;
        self.top_row = 0;
    }

    /// Get the currently top-displayed physical line index.
    pub fn top_line(&self) -> usize {
        self.top_line
    }

    pub fn resize(&mut self, cols: u16, rows: u16) {
        self.cols = cols.max(1);
        self.rows = rows.max(2);
        self.opts.cols = self.cols;
    }

    pub fn toggle_line_numbers(&mut self) {
        self.show_line_numbers = !self.show_line_numbers;
    }

    pub fn toggle_chop(&mut self) {
        self.opts.wrap = !self.opts.wrap;
        if self.opts.wrap {
            self.left_col = 0;
        }
    }

    const HSCROLL_STEP: usize = 8;

    /// Horizontal scroll is available only for non-wrapping content: image
    /// mode, or chop-mode text. Wrap mode has no horizontal axis; hex (fixed
    /// xxd layout) and raw (`AnsiMode::Raw`) are excluded.
    pub fn hscroll_active(&self) -> bool {
        #[cfg(feature = "image")]
        if self.current_image().is_some() {
            return true;
        }
        !self.opts.wrap
            && !self.hex_mode
            && self.ansi_mode != crate::render::AnsiMode::Raw
    }

    fn hscroll_by(&mut self, delta: isize) {
        if !self.hscroll_active() {
            return;
        }
        self.left_col = (self.left_col as isize + delta).max(0) as usize;
        // Upper bound is enforced per-frame by the clamp in Task 3/4.
    }

    pub fn hscroll_left_half(&mut self)  { let h = (self.cols as usize / 2).max(1) as isize; self.hscroll_by(-h); }
    pub fn hscroll_right_half(&mut self) { let h = (self.cols as usize / 2).max(1) as isize; self.hscroll_by(h); }
    pub fn hscroll_left_step(&mut self)  { self.hscroll_by(-(Self::HSCROLL_STEP as isize)); }
    pub fn hscroll_right_step(&mut self) { self.hscroll_by(Self::HSCROLL_STEP as isize); }

    /// Scroll left by an explicit column count (used by `--shift N`).
    pub fn hscroll_left_cols(&mut self, n: u16)  { self.hscroll_by(-(n as isize)); }
    /// Scroll right by an explicit column count (used by `--shift N`).
    pub fn hscroll_right_cols(&mut self, n: u16) { self.hscroll_by(n as isize); }

    pub fn left_col(&self) -> usize { self.left_col }

    /// Drop the horizontal scroll offset. Called when a new file is opened
    /// (a fresh document has no relationship to the prior horizontal position).
    pub fn reset_hscroll(&mut self) { self.left_col = 0; }

    /// Return the current set of visible (matched) line indices. Non-empty only
    /// in hide mode (filter or grep active without --dim). Stable public accessor
    /// so integration tests and external tooling can inspect filter results.
    pub fn visible_lines(&self) -> &[usize] { &self.visible_lines }
}

/// Fit-width scaled pixel dimensions of an image: width = target_cols cells
/// wide (in pixels), height preserving aspect. `width_cols` overrides the
/// terminal `cols` when `Some` (from `--image-width`). Pure; the single source
/// of the protocol fit-width scaling formula.
#[cfg(feature = "image")]
pub fn protocol_scaled_dims(img_w: u32, img_h: u32, cols: u16,
                            cell_px: (u16, u16), width_cols: Option<usize>) -> (u32, u32) {
    let target_cols = width_cols.unwrap_or(cols as usize).max(1) as u32;
    let scaled_w = (target_cols * cell_px.0.max(1) as u32).max(1);
    let img_w = img_w.max(1);
    let scaled_h = (img_h as u64 * scaled_w as u64 / img_w as u64).max(1) as u32;
    (scaled_w, scaled_h)
}

/// Text rows a fit-width protocol image occupies. `width_cols` overrides the
/// terminal `cols` when `Some` (from `--image-width`). Pure; used for scroll math.
#[cfg(feature = "image")]
pub fn protocol_occupied_rows(img_w: u32, img_h: u32, cols: u16,
                              cell_px: (u16, u16), width_cols: Option<usize>) -> usize {
    let (_, scaled_h) = protocol_scaled_dims(img_w, img_h, cols, cell_px, width_cols);
    (scaled_h as usize).div_ceil(cell_px.1.max(1) as usize).max(1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::MockSource;

    fn setup(content: &[u8]) -> (MockSource, LineIndex) {
        let m = MockSource::new();
        m.append(content);
        m.finish();
        let idx = LineIndex::new();
        (m, idx)
    }

    #[test]
    fn search_skip_screen_skips_on_screen_match() {
        let (m, mut idx) = setup(b"a\nhit1\nc\nd\nhit2\nf\n");
        let mut v = Viewport::new(20, 3, "t".into()); // body_rows = 2 → lines 0,1 visible
        v.set_search("hit".into(), SearchDirection::Forward).unwrap();
        v.search_repeat(&m, &mut idx, false);
        assert_eq!(v.top_line(), 1, "default search lands on the on-screen match");

        let (m2, mut idx2) = setup(b"a\nhit1\nc\nd\nhit2\nf\n");
        let mut v2 = Viewport::new(20, 3, "t".into());
        v2.set_search_skip_screen(true);
        v2.set_search("hit".into(), SearchDirection::Forward).unwrap();
        v2.search_repeat(&m2, &mut idx2, false);
        assert_eq!(v2.top_line(), 4, "skip-screen search skips the visible screen");
    }

    #[test]
    fn search_skip_screen_applies_in_records_mode() {
        // One-line records; on-screen records are 0,1 (body_rows=2). Record 1
        // ("[2] hit") matches and is on screen; record 3 ("[4] hit") is below.
        let body = b"[1] aaa\n[2] hit\n[3] bbb\n[4] hit\n";
        let re = regex::bytes::Regex::new(r"^\[").unwrap();

        let m = MockSource::new(); m.append(body);
        let mut idx = LineIndex::new(); idx.set_record_start(re.clone()); idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 3, "t".into()); // body_rows = 2
        v.set_search("hit".into(), SearchDirection::Forward).unwrap();
        v.search_repeat(&m, &mut idx, false);
        assert_eq!(v.top_line(), 1, "default records search lands on the on-screen record");

        let m2 = MockSource::new(); m2.append(body);
        let mut idx2 = LineIndex::new(); idx2.set_record_start(re); idx2.extend_to_end(&m2);
        let mut v2 = Viewport::new(20, 3, "t".into());
        v2.set_search_skip_screen(true);
        v2.set_search("hit".into(), SearchDirection::Forward).unwrap();
        v2.search_repeat(&m2, &mut idx2, false);
        assert_eq!(v2.top_line(), 3, "skip-screen skips the on-screen record in records mode");
    }

    #[test]
    fn hilite_only_match_highlights_just_landed_line() {
        let (m, mut idx) = setup(b"hit one\nhit two\n");
        let mut v = Viewport::new(20, 4, "t".into());
        v.set_hilite_only_match(true);
        v.set_search("hit".into(), SearchDirection::Forward).unwrap();
        v.search_repeat(&m, &mut idx, false); // lands on the first match after top (line 1)
        let landed = v.top_line();
        assert_eq!(landed, 1, "forward search lands on line 1");
        // Scroll back so BOTH matching lines are on screen at known body rows
        // (row 0 = line 0, row 1 = line 1 = landed). `f.highlights` is indexed
        // by body row, not logical line, so we read the rows directly.
        v.set_top(0, 0);
        let f = v.frame(&m, &mut idx);
        assert!(!f.highlights[landed].is_empty(), "landed line is highlighted");
        let other = if landed == 0 { 1 } else { 0 };
        assert!(f.highlights[other].is_empty(), "non-landed matching line is not highlighted");
    }

    #[test]
    fn tilde_marks_lines_past_eof() {
        let (m, mut idx) = setup(b"only\n");
        let mut v = Viewport::new(10, 4, "t".into()); // body_rows = 3
        v.set_tilde_eof(true);
        let f = v.frame(&m, &mut idx);
        assert!(matches!(f.body[1][0], Cell::Char { ch: '~', .. }), "past-EOF row shows '~'");
        let mut v2 = Viewport::new(10, 4, "t".into());
        let f2 = v2.frame(&m, &mut idx);
        assert!(!matches!(f2.body[1][0], Cell::Char { ch: '~', .. }), "default past-EOF is blank");
    }

    /// Read the `ch` of the first cell of a body row (the status column when
    /// `-J` is on). Panics if the cell isn't a `Cell::Char`.
    fn first_cell_char(row: &[Cell]) -> char {
        match row.first() {
            Some(Cell::Char { ch, .. }) => *ch,
            other => panic!("expected Char in first cell, got {:?}", other),
        }
    }

    #[test]
    fn frozen_cols_clamp_reaches_exact_eol_and_shows_divider() {
        // 30-char line, 10 cols, chop, freeze 3 cols. Scroll far right; left_col
        // must clamp to the engaged max, the frozen divider '│' appears, no '<'.
        let content = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123\n"; // 30 chars
        let (m, mut idx) = setup(content);
        let mut v = Viewport::new(10, 3, "t".into());
        v.toggle_chop();
        v.set_header(0, 3); // freeze 3 left columns
        for _ in 0..20 { v.hscroll_right_step(); } // scroll way past the end
        let frame = v.frame(&m, &mut idx);
        // avail = 10 (no gutter/status col). Engaged clamp:
        //   max_left_col = (widest - C).saturating_sub(avail - C - 1)
        //                = (30 - 3) - (10 - 3 - 1) = 27 - 6 = 21
        assert_eq!(v.left_col(), 21, "left_col should clamp to the engaged max");
        assert!(frame.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '\u{2502}', .. })),
            "frozen divider should be present");
        assert!(!frame.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '<', .. })),
            "'<' marker should be suppressed when frozen is engaged");
    }

    #[test]
    fn frozen_cols_zero_keeps_today_clamp_and_marker() {
        let content = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123\n"; // 30 chars
        let (m, mut idx) = setup(content);
        let mut v = Viewport::new(10, 3, "t".into());
        v.toggle_chop();
        for _ in 0..20 { v.hscroll_right_step(); }
        let frame = v.frame(&m, &mut idx);
        assert_eq!(v.left_col(), 20, "today's clamp: widest(30) - avail(10) = 20");
        assert!(frame.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '<', .. })),
            "'<' marker present without a frozen region");
    }

    #[test]
    fn frozen_cols_are_per_viewport_independent() {
        // Each split pane is a Viewport with its own header_cols, so the freeze
        // is per-pane. Pane A freezes 3 cols (divider present); pane B doesn't.
        let content = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123\n";
        let (m, mut idx) = setup(content);

        let mut a = Viewport::new(12, 3, "a".into());
        a.toggle_chop();
        a.set_header(0, 3);
        for _ in 0..3 { a.hscroll_right_step(); }
        let fa = a.frame(&m, &mut idx);
        assert!(fa.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '\u{2502}', .. })),
            "pane A with header_cols set shows the frozen divider");

        let mut b = Viewport::new(12, 3, "b".into());
        b.toggle_chop();
        for _ in 0..3 { b.hscroll_right_step(); }
        let fb = b.frame(&m, &mut idx);
        assert!(!fb.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '\u{2502}', .. })),
            "pane B without header_cols shows no frozen divider");
    }

    #[test]
    fn status_column_shows_mark_then_search_glyphs() {
        // 3 lines, chop mode (no wrap). Mark line 1 ('a'), search matches
        // "bb" on line 2. Line 0 → blank, line 1 → 'a' (mark), line 2 → '*'.
        let (m, mut idx) = setup(b"aa\nbb\ncc\n");
        let mut v = Viewport::new(20, 5, "f".into()); // body = 4
        v.opts.wrap = false;
        v.set_status_column(true);
        let mut marks = std::collections::HashMap::new();
        marks.insert(1usize, 'a');
        v.set_status_marks(marks);
        v.set_search("cc".into(), SearchDirection::Forward).unwrap();

        let frame = v.frame(&m, &mut idx);
        assert_eq!(first_cell_char(&frame.body[0]), ' ', "line 0: no mark, no match");
        assert_eq!(first_cell_char(&frame.body[1]), 'a', "line 1: mark letter");
        assert_eq!(first_cell_char(&frame.body[2]), '*', "line 2: search match");
    }

    #[test]
    fn status_column_mark_beats_search_match() {
        // Line 1 is BOTH marked ('z') AND matched by the search — the mark
        // letter takes precedence over the search `*`.
        let (m, mut idx) = setup(b"aa\nbb\ncc\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.opts.wrap = false;
        v.set_status_column(true);
        let mut marks = std::collections::HashMap::new();
        marks.insert(1usize, 'z');
        v.set_status_marks(marks);
        v.set_search("bb".into(), SearchDirection::Forward).unwrap();

        let frame = v.frame(&m, &mut idx);
        assert_eq!(first_cell_char(&frame.body[1]), 'z', "mark beats search-match");
    }

    #[test]
    fn status_column_matches_content_not_gutter_digits() {
        // Regression: with line numbers (`-N`) on, searching for a digit that
        // appears in a visible LINE NUMBER must not falsely flag `*` in the
        // status column. The `*` must reflect matches in the CONTENT only,
        // never the gutter digits / status cell / padding.
        // 12 lines, all letters, no digits in content. Line number 5 contains
        // the digit '5' in its gutter; searching "5" must NOT mark that line.
        let (m, mut idx) = setup(b"aa\nbb\ncc\ndd\nee\nff\ngg\nhh\nii\njj\nkk\nll\n");
        let mut v = Viewport::new(40, 14, "f".into()); // body = 13
        v.opts.wrap = false;
        v.show_line_numbers = true;
        v.set_status_column(true);
        v.set_search("5".into(), SearchDirection::Forward).unwrap();

        let frame = v.frame(&m, &mut idx);
        // body[4] is line 5 (1-based) — its gutter shows "5" but content "ee"
        // has no '5'. Status column must be blank, not '*'. (Only the 12 real
        // content rows; row 12 is post-EOF filler with an Empty status cell.)
        for i in 0..12 {
            assert_eq!(
                first_cell_char(&frame.body[i]), ' ',
                "body row {i}: no content match for '5' but status column flagged it"
            );
        }

        // Positive case: a search matching actual CONTENT still flags `*`.
        let (m2, mut idx2) = setup(b"aa\nbb\ncc\ndd\nee\nff\ngg\nhh\nii\njj\nkk\nll\n");
        let mut v2 = Viewport::new(40, 14, "f".into());
        v2.opts.wrap = false;
        v2.show_line_numbers = true;
        v2.set_status_column(true);
        v2.set_search("ee".into(), SearchDirection::Forward).unwrap();
        let frame2 = v2.frame(&m2, &mut idx2);
        assert_eq!(first_cell_char(&frame2.body[4]), '*', "line 5 content 'ee' matches search");
    }

    #[test]
    fn status_column_off_leaves_first_cell_as_content() {
        // With the feature off, no extra column is prepended — the first cell
        // of each body row is the line's content (no line numbers here).
        let (m, mut idx) = setup(b"aa\nbb\ncc\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.opts.wrap = false;
        // status_column defaults off; set a mark + search anyway to prove gating.
        let mut marks = std::collections::HashMap::new();
        marks.insert(1usize, 'a');
        v.set_status_marks(marks);
        v.set_search("bb".into(), SearchDirection::Forward).unwrap();

        let frame = v.frame(&m, &mut idx);
        assert_eq!(first_cell_char(&frame.body[0]), 'a', "line 0 content unchanged");
        assert_eq!(first_cell_char(&frame.body[1]), 'b', "line 1 content unchanged");
        assert_eq!(first_cell_char(&frame.body[2]), 'c', "line 2 content unchanged");
    }

    #[test]
    fn frame_renders_body_height_rows() {
        let (m, mut idx) = setup(b"a\nb\nc\nd\ne\n");
        let mut v = Viewport::new(10, 5, "test".into());  // body = 4
        let frame = v.frame(&m, &mut idx);
        assert_eq!(frame.body.len(), 4);
        assert_eq!(frame.body[0][0], Cell::Char { ch: 'a', width: 1, style: crate::ansi::Style::default(), hyperlink: None });
        assert_eq!(frame.body[3][0], Cell::Char { ch: 'd', width: 1, style: crate::ansi::Style::default(), hyperlink: None });
    }

    #[test]
    fn scroll_down_advances_top_line() {
        // 8 lines, body=4 → there are 4 lines below the first screen to scroll
        // into, so scrolling down by 2 lands cleanly above the bottom anchor.
        let (m, mut idx) = setup(b"a\nb\nc\nd\ne\nf\ng\nh\n");
        let mut v = Viewport::new(10, 5, "test".into());
        v.scroll_lines(2, &m, &mut idx);
        assert_eq!(v.top_line, 2);
        assert_eq!(v.top_row, 0);
    }

    #[test]
    fn scroll_up_clamps_at_zero() {
        let (m, mut idx) = setup(b"a\nb\nc\n");
        let mut v = Viewport::new(10, 5, "test".into());
        v.scroll_lines(-5, &m, &mut idx);
        assert_eq!(v.top_line, 0);
        assert_eq!(v.top_row, 0);
    }

    #[test]
    fn scroll_down_clamps_at_last_line() {
        // 8 single-row lines, body=4. Scrolling far past the end clamps at the
        // bottom anchor: the last line resting on the last body row, i.e.
        // top_line = 8 - 4 = 4. (Not line 7 at the top — that would strand the
        // tail off-screen, the bug this guards against.)
        let (m, mut idx) = setup(b"a\nb\nc\nd\ne\nf\ng\nh\n");
        let mut v = Viewport::new(10, 5, "test".into());
        v.scroll_lines(50, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (4, 0));
        assert!(v.is_at_bottom(&m, &idx));
    }

    #[test]
    fn scroll_logical_lines_skips_wrap_rows() {
        // Line 0 has 50 wraps in a 10-col viewport. J should jump straight to line 1.
        let mut content = vec![b'X'; 500];
        content.push(b'\n');
        content.extend_from_slice(b"second\n");
        content.extend_from_slice(b"third\n");
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(10, 8, "f".into());
        v.scroll_logical_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 0));
        v.scroll_logical_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (2, 0));
    }

    #[test]
    fn scroll_logical_lines_back_snaps_to_line_start() {
        // Mid-wrap K should snap to start of current line first, then go back.
        // Three 50-char lines (5 wrap rows each) with body=8 put the bottom
        // anchor at (1, 2), so scrolling down 7 rows lands inside line 1's
        // wraps without being clamped.
        let mut content = vec![b'A'; 50];
        content.push(b'\n');
        content.extend_from_slice(&[b'B'; 50]);
        content.push(b'\n');
        content.extend_from_slice(&[b'C'; 50]);
        content.push(b'\n');
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(10, 8, "f".into());
        v.scroll_lines(7, &m, &mut idx);
        assert_eq!(v.top_line, 1, "should be on line 1");
        assert!(v.top_row > 0, "should be inside line 1's wraps");
        v.scroll_logical_lines(-1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 0), "K snaps to start of current line");
        v.scroll_logical_lines(-1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (0, 0), "K then goes to previous line");
    }

    #[test]
    fn scroll_down_walks_wraps_of_last_line() {
        // Last line is 60 chars in a 10-col viewport → 6 wrap rows. With body=4
        // the bottom anchor sits at (1, 2), so walking into the last line's
        // wraps up to row 2 is legitimate (it doesn't strand the tail).
        let mut content = b"first\n".to_vec();
        content.extend_from_slice(&[b'X'; 60]);
        content.push(b'\n');
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(10, 5, "f".into());
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 0));
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 1), "should advance into wraps of last line");
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 2), "should reach the bottom anchor row");
        // Already at the anchor — scrolling further must not strand the tail.
        v.scroll_lines(5, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 2), "clamped at the bottom anchor");
    }

    #[test]
    fn scroll_down_walks_wrap_rows_within_long_line() {
        // Line 0 is 30 chars in a 10-col viewport → 3 wrap rows. Body = 4.
        // Six short lines follow so the bottom anchor sits well below line 0,
        // leaving room to walk through line 0's wrap rows and into line 1.
        let mut content = vec![b'X'; 30];
        content.push(b'\n');
        content.extend_from_slice(b"a\nb\nc\nd\ne\nf\n");
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(10, 5, "f".into());
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (0, 1), "first j → wrap row 1");
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (0, 2), "second j → wrap row 2");
        v.scroll_lines(1, &m, &mut idx);
        assert_eq!((v.top_line, v.top_row), (1, 0), "third j → next logical line");
    }

    #[test]
    fn status_line_shows_range_and_pct() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n");
        let mut v = Viewport::new(20, 5, "f".into());  // body = 4
        let frame = v.frame(&m, &mut idx);
        assert!(frame.status.starts_with("f  1-4/10"));
    }

    #[test]
    fn page_down_advances_by_body_rows() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n");
        let mut v = Viewport::new(10, 5, "f".into());  // body = 4
        v.page_down(&m, &mut idx);
        assert_eq!(v.top_line, 4);
    }

    #[test]
    fn page_up_then_page_down_returns_to_start_when_no_resize() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n");
        let mut v = Viewport::new(10, 5, "f".into());
        v.page_down(&m, &mut idx);
        v.page_up(&m, &mut idx);
        assert_eq!(v.top_line, 0);
        assert_eq!(v.top_row, 0);
    }

    #[test]
    fn half_page_down_advances_by_half_body() {
        // 12 lines, body=6 → bottom anchor at line 6, so a half-page (3) lands
        // cleanly above it.
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n");
        let mut v = Viewport::new(10, 7, "f".into());  // body = 6, half = 3
        v.half_page_down(&m, &mut idx);
        assert_eq!(v.top_line, 3);
    }

    #[test]
    fn goto_top_resets_position() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n");
        let mut v = Viewport::new(10, 5, "f".into());
        v.scroll_lines(2, &m, &mut idx);
        v.goto_top();
        assert_eq!(v.top_line, 0);
        assert_eq!(v.top_row, 0);
    }

    #[test]
    fn goto_bottom_scrolls_to_last_page() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n");
        let mut v = Viewport::new(10, 5, "f".into());  // body = 4
        v.goto_bottom(&m, &mut idx);
        // Last page should show lines 7..=10 → top_line = 6.
        assert_eq!(v.top_line, 6);
    }

    #[test]
    #[cfg(feature = "image")]
    fn protocol_image_occupied_rows_fit_width() {
        // 100x200 image, cols=50, cell_px=(8,16): scaled_w=400, scaled_h=800, rows=50.
        assert_eq!(crate::viewport::protocol_occupied_rows(100, 200, 50, (8, 16), None), 50);
        // --image-width 25 cols: scaled_w=200, scaled_h=400, rows=25.
        assert_eq!(crate::viewport::protocol_occupied_rows(100, 200, 50, (8, 16), Some(25)), 25);
    }

    #[cfg(feature = "image")]
    #[test]
    fn frame_image_protocol_sets_image_blob() {
        use image::{Rgba, RgbaImage};
        let mut vp = Viewport::new(40, 10, "cat.png".into());
        let mut idx = LineIndex::new();
        let m = MockSource::new();
        vp.set_image(RgbaImage::from_pixel(20, 40, Rgba([10, 20, 30, 255])), "png", crate::image_render::AsciiStyle::Ramp, None);
        vp.set_image_protocol(crate::viewport::ImageProtocol::Kitty, Some((8, 16)));
        let frame = vp.frame(&m, &mut idx);
        assert!(frame.image_blob.is_some(), "Kitty protocol frame carries an image blob");
        // ASCII protocol → no blob
        vp.set_image_protocol(crate::viewport::ImageProtocol::Ascii, None);
        let frame2 = vp.frame(&m, &mut idx);
        assert!(frame2.image_blob.is_none(), "ASCII protocol frame has no blob");
    }

    #[cfg(feature = "image")]
    #[test]
    fn protocol_image_clamps_vertical_scroll() {
        use image::{Rgba, RgbaImage};
        let mut vp = Viewport::new(40, 10, "cat.png".into()); // body = 9
        let mut idx = LineIndex::new();
        let m = MockSource::new();
        // Tall image so it occupies many rows.
        vp.set_image(RgbaImage::from_pixel(20, 2000, Rgba([10, 20, 30, 255])), "png", crate::image_render::AsciiStyle::Ramp, None);
        vp.set_image_protocol(crate::viewport::ImageProtocol::Kitty, Some((8, 16)));
        // Scroll way past the end; frame() applies the clamp.
        for _ in 0..10_000 {
            vp.scroll_lines(1, &m, &mut idx);
        }
        let _ = vp.frame(&m, &mut idx);
        // After scrolling past the end, top_line clamps to (protocol_total - body_rows).
        let total = crate::viewport::protocol_occupied_rows(20, 2000, 40, (8, 16), None);
        let body = vp.body_rows() as usize;
        assert_eq!(
            vp.top_line(),
            total.saturating_sub(body),
            "scroll reaches exactly the protocol image bottom"
        );
    }

    #[cfg(feature = "image")]
    #[test]
    fn image_mode_frame_renders_and_scrolls() {
        use image::{Rgba, RgbaImage};
        let img = RgbaImage::from_pixel(20, 200, Rgba([255, 255, 255, 255]));
        let mut v = Viewport::new(20, 6, "cat.png".into()); // body = 5
        v.set_image(img, "png", crate::image_render::AsciiStyle::Ramp, Some(20));
        assert!(v.image_mode());
        let total = v.image_total_rows();
        assert!(total > 5, "tall image should exceed the body");
        assert!(!v.is_at_bottom_image(), "starts at top");
        let mut idx = LineIndex::new();
        let m = MockSource::new();
        let frame = v.frame(&m, &mut idx);
        assert_eq!(frame.body.len(), 5);
        v.goto_bottom(&m, &mut idx);
        assert!(v.is_at_bottom_image());
    }

    #[cfg(feature = "image")]
    #[test]
    fn frame_image_slices_at_left_col() {
        use crate::render::Cell;
        use image::{Rgba, RgbaImage};

        // Image pixel width = 40, terminal cols = 10.
        // set_image with width=Some(40) → image_cols() = 40 → grid rows are 40 cells wide.
        // Terminal is only 10 cols wide, so the grid is wider than the viewport.
        // Column-varying image so each grid column renders a DISTINCT cell —
        // otherwise the slice-advance assertions below would be tautological.
        let img = RgbaImage::from_fn(40, 20, |x, _y| Rgba([(x as u8).saturating_mul(6), 0, 0, 255]));
        let mut v = Viewport::new(10, 4, "wide.png".into()); // body = 3, cols = 10
        v.set_image(img, "png", crate::image_render::AsciiStyle::Ramp, Some(40));
        assert!(v.hscroll_active(), "image mode should make hscroll active");

        let mut idx = LineIndex::new();
        let m = MockSource::new();

        // --- pass 1: left_col == 0, frame_image returns grid columns 0..10 ---
        assert_eq!(v.left_col(), 0);
        let frame0 = v.frame(&m, &mut idx);
        assert_eq!(frame0.body.len(), 3, "body should have body_rows rows");
        // The grid row at offset 0 (no scroll) should give us exactly cols=10 cells.
        assert_eq!(frame0.body[0].len(), 10);
        // No '<' or '>' marker cells (images never show scroll markers).
        assert!(
            !frame0.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '<', .. } | Cell::Char { ch: '>', .. })),
            "no scroll marker expected on image frame at left_col=0"
        );
        // Record the first cell at offset 0 for comparison after scrolling.
        let cell_at_col0 = frame0.body[0][0].clone();
        let cell_at_col8 = frame0.body[0][8].clone();

        // --- pass 2: scroll right (left_col = HSCROLL_STEP = 8) ---
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 8);
        let frame1 = v.frame(&m, &mut idx);
        assert_eq!(frame1.body[0].len(), 10);
        // No '<' or '>' marker cells on images.
        assert!(
            !frame1.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '<', .. } | Cell::Char { ch: '>', .. })),
            "no scroll marker expected on image frame after hscroll_right_step"
        );
        // The slice DID advance: frame1.body[0][0] is what was at grid column 8.
        assert_eq!(
            frame1.body[0][0], cell_at_col8,
            "after hscroll_right_step the first visible cell should be grid col 8"
        );
        // And — because the image varies by column — it must differ from the
        // pre-scroll first cell, proving the offset was actually applied (not a
        // no-op that the uniform-image version couldn't have detected).
        assert_ne!(
            frame1.body[0][0], cell_at_col0,
            "the scrolled first cell must differ from the unscrolled one"
        );
    }

    #[cfg(feature = "image")]
    #[test]
    fn animation_renders_current_frame_and_advances() {
        use image::{Rgba, RgbaImage};
        use std::time::Duration;
        let m = MockSource::new();
        let mut idx = LineIndex::new();
        let mut vp = Viewport::new(40, 10, "x.gif".into());
        let frames = vec![
            (RgbaImage::from_pixel(4, 4, Rgba([0, 0, 0, 255])), Duration::from_millis(100)),
            (RgbaImage::from_pixel(4, 4, Rgba([255, 255, 255, 255])), Duration::from_millis(100)),
        ];
        vp.set_animation(crate::image_render::Animation { frames, loop_count: None }, "gif",
                         crate::image_render::AsciiStyle::Ramp, None);
        let f0 = vp.frame(&m, &mut idx);
        let changed = vp.tick(Duration::from_millis(120));
        assert!(changed, "tick past the frame delay advances");
        let f1 = vp.frame(&m, &mut idx);
        assert_ne!(format!("{:?}", f0.body), format!("{:?}", f1.body), "frame content changed");
        assert!(vp.has_animation());
        assert!(vp.anim_deadline().is_some());
    }

    #[cfg(feature = "image")]
    #[test]
    fn animation_status_badge_reflects_play_pause() {
        use image::{Rgba, RgbaImage};
        use std::time::Duration;
        let m = MockSource::new();
        let mut idx = LineIndex::new();
        let mut vp = Viewport::new(40, 10, "x.gif".into());
        let frames = vec![
            (RgbaImage::from_pixel(4, 4, Rgba([0, 0, 0, 255])), Duration::from_millis(100)),
            (RgbaImage::from_pixel(4, 4, Rgba([255, 255, 255, 255])), Duration::from_millis(100)),
        ];
        vp.set_animation(crate::image_render::Animation { frames, loop_count: None }, "gif",
                         crate::image_render::AsciiStyle::Ramp, None);
        let playing = vp.frame(&m, &mut idx);
        assert!(playing.status.contains("[play 1/2]"), "status: {:?}", playing.status);
        vp.anim_toggle_pause();
        let paused = vp.frame(&m, &mut idx);
        assert!(paused.status.contains("[pause 1/2]"), "status: {:?}", paused.status);
    }

    #[cfg(feature = "image")]
    #[test]
    fn animation_pause_stops_advance() {
        use image::{Rgba, RgbaImage};
        use std::time::Duration;
        let mut vp = Viewport::new(40, 10, "x.gif".into());
        let frames = vec![
            (RgbaImage::from_pixel(4, 4, Rgba([0, 0, 0, 255])), Duration::from_millis(100)),
            (RgbaImage::from_pixel(4, 4, Rgba([255, 255, 255, 255])), Duration::from_millis(100)),
        ];
        vp.set_animation(crate::image_render::Animation { frames, loop_count: None }, "gif",
                         crate::image_render::AsciiStyle::Ramp, None);
        vp.anim_toggle_pause();
        assert!(!vp.tick(Duration::from_millis(500)), "paused tick does not advance");
        assert_eq!(vp.anim_deadline(), None);
    }

    #[test]
    fn goto_line_positions_top_line() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\nd\ne\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_line(3, &m, &mut idx);
        assert_eq!(v.top_line(), 3);
    }

    #[test]
    fn goto_line_clamps_to_last_line() {
        let m = MockSource::new();
        m.append(b"a\nb\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_line(999, &m, &mut idx);
        assert_eq!(v.top_line(), 1);
    }

    #[test]
    fn goto_record_positions_at_record_start_line() {
        let m = MockSource::new();
        m.append(b"[1] a\n  cont\n[2] b\n[3] c\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_record(1, &m, &mut idx);  // record 1 starts at line 2 ("[2] b")
        assert_eq!(v.top_line(), 2);
    }

    #[test]
    fn goto_record_in_line_per_record_mode_equals_goto_line() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_record(2, &m, &mut idx);
        assert_eq!(v.top_line(), 2);
    }

    #[test]
    fn goto_percent_50_lands_in_middle() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\nd\ne\n");  // 10 bytes
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_percent(50, &m, &mut idx);
        assert_eq!(v.top_line(), 2);  // byte 5 → line 2
    }

    #[test]
    fn goto_percent_100_lands_at_last_line() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\n");  // 6 bytes, 3 lines
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_percent(100, &m, &mut idx);
        assert_eq!(v.top_line(), 2);
    }

    #[test]
    fn goto_percent_0_lands_at_first_line() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        v.goto_record(2, &m, &mut idx);  // first jump elsewhere
        assert_eq!(v.top_line(), 2);
        v.goto_percent(0, &m, &mut idx);
        assert_eq!(v.top_line(), 0);
    }

    #[test]
    fn resize_updates_dimensions_and_render_opts() {
        let (m, mut idx) = setup(b"1\n2\n");
        let mut v = Viewport::new(10, 5, "f".into());
        v.resize(40, 12);
        assert_eq!(v.cols, 40);
        assert_eq!(v.rows, 12);
        assert_eq!(v.opts.cols, 40);
        let _ = v.frame(&m, &mut idx);
    }

    #[test]
    fn toggle_line_numbers_changes_gutter() {
        let (m, mut idx) = setup(b"a\nb\nc\n");
        let mut v = Viewport::new(10, 5, "f".into());
        let frame_off = v.frame(&m, &mut idx);
        v.toggle_line_numbers();
        let frame_on = v.frame(&m, &mut idx);
        // With gutter, first cell is a digit or space, not 'a'.
        assert_eq!(frame_off.body[0][0], Cell::Char { ch: 'a', width: 1, style: crate::ansi::Style::default(), hyperlink: None });
        assert_ne!(frame_on.body[0][0], Cell::Char { ch: 'a', width: 1, style: crate::ansi::Style::default(), hyperlink: None });
    }

    #[test]
    fn toggle_chop_changes_wrap_mode() {
        let (m, mut idx) = setup(b"abcdefghij\n");
        let mut v = Viewport::new(4, 5, "f".into());
        v.toggle_chop();
        let frame = v.frame(&m, &mut idx);
        // After toggle_chop, the line is one row, not wrapped.
        // Body row 0 is "abcd"; rows 1..3 are blank fill.
        assert_eq!(frame.body[0][..4],
            [Cell::Char { ch: 'a', width: 1, style: crate::ansi::Style::default(), hyperlink: None },
             Cell::Char { ch: 'b', width: 1, style: crate::ansi::Style::default(), hyperlink: None },
             Cell::Char { ch: 'c', width: 1, style: crate::ansi::Style::default(), hyperlink: None },
             Cell::Char { ch: 'd', width: 1, style: crate::ansi::Style::default(), hyperlink: None }]);
        // Row 1 should be all-empty (no wrap continuation).
        assert!(frame.body[1].iter().all(|c| matches!(c, Cell::Empty)));
    }

    // ----- Follow mode -----

    #[test]
    fn is_at_bottom_initially_only_when_source_fits() {
        let (m, mut idx) = setup(b"a\nb\n");  // 2 lines
        let v = Viewport::new(10, 5, "f".into());  // body = 4 ≥ 2
        idx.extend_to_end(&m);
        assert!(v.is_at_bottom(&m, &idx), "small file fits in body, top is at bottom");
    }

    #[test]
    fn is_at_bottom_false_when_top_and_more_lines_below() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n");  // 8 lines
        let v = Viewport::new(10, 5, "f".into());  // body = 4
        idx.extend_to_end(&m);
        assert!(!v.is_at_bottom(&m, &idx), "top of 8-line file with body=4 is not at bottom");
    }

    #[test]
    fn is_at_bottom_true_after_goto_bottom() {
        let (m, mut idx) = setup(b"1\n2\n3\n4\n5\n6\n7\n8\n");
        let mut v = Viewport::new(10, 5, "f".into());
        v.goto_bottom(&m, &mut idx);
        assert!(v.is_at_bottom(&m, &idx));
    }

    #[test]
    fn status_shows_follow_suffix_when_follow_mode_on() {
        let (m, mut idx) = setup(b"a\nb\n");
        let mut v = Viewport::new(20, 5, "f".into());
        let frame_off = v.frame(&m, &mut idx);
        assert!(!frame_off.status.contains("(F)"));
        v.set_follow_mode(true);
        let frame_on = v.frame(&m, &mut idx);
        assert!(frame_on.status.contains("(F)"), "expected (F) in status, got: {}", frame_on.status);
    }

    #[test]
    fn toggle_follow_flips_state() {
        let mut v = Viewport::new(10, 5, "f".into());
        assert!(!v.follow_mode());
        v.toggle_follow();
        assert!(v.follow_mode());
        v.toggle_follow();
        assert!(!v.follow_mode());
    }

    #[test]
    fn idle_indicator_kicks_in_at_threshold() {
        let (m, mut idx) = setup(b"a\nb\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_follow_mode(true);
        // 19 idle ticks → still (F).
        for _ in 0..19 { v.tick_idle(); }
        let f1 = v.frame(&m, &mut idx);
        assert!(f1.status.contains("(F)"));
        assert!(!f1.status.contains("idle"));
        // 20th tick crosses the threshold.
        v.tick_idle();
        let f2 = v.frame(&m, &mut idx);
        assert!(f2.status.contains("(F idle)"), "{}", f2.status);
    }

    #[test]
    fn note_growth_resets_idle() {
        let (m, mut idx) = setup(b"a\nb\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_follow_mode(true);
        for _ in 0..25 { v.tick_idle(); }
        assert!(v.is_idle());
        v.note_growth();
        assert!(!v.is_idle());
        let f = v.frame(&m, &mut idx);
        assert!(!f.status.contains("idle"));
    }

    #[test]
    fn qae_off_never_quits_even_at_bottom() {
        let (m, mut idx) = setup(b"a\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_quit_at_eof(QuitAtEof::Off);
        v.goto_bottom(&m, &mut idx);
        assert!(!v.note_motion_for_eof(true, &m, &idx));
    }

    #[test]
    fn qae_first_quits_immediately_at_bottom() {
        let (m, mut idx) = setup(b"a\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_quit_at_eof(QuitAtEof::First);
        v.goto_bottom(&m, &mut idx);
        assert!(v.note_motion_for_eof(true, &m, &idx));
    }

    #[test]
    fn qae_first_only_quits_at_eof_not_mid_file() {
        let mut content = Vec::new();
        for _ in 0..50 { content.extend_from_slice(b"x\n"); }
        let (m, mut idx) = setup(&content);
        idx.extend_to_end(&m);  // populate so is_at_bottom can see the 50 lines
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_quit_at_eof(QuitAtEof::First);
        // top_line is 0; with 50 lines and a 5-row body, we're not at bottom.
        assert!(!v.is_at_bottom(&m, &idx));
        assert!(!v.note_motion_for_eof(true, &m, &idx));
    }

    #[test]
    fn qae_second_quits_on_second_hit() {
        let (m, mut idx) = setup(b"a\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_quit_at_eof(QuitAtEof::Second);
        v.goto_bottom(&m, &mut idx);
        // 1st forward at EOF: count, don't quit.
        assert!(!v.note_motion_for_eof(true, &m, &idx));
        // 2nd forward at EOF: quit.
        assert!(v.note_motion_for_eof(true, &m, &idx));
    }

    #[test]
    fn squeeze_collapses_consecutive_blanks() {
        // Source: a, blank, blank, blank, b.
        let (m, mut idx) = setup(b"a\n\n\n\nb\n");
        let mut v = Viewport::new(10, 8, "f".into());
        v.set_squeeze_blanks(true);
        let f = v.frame(&m, &mut idx);
        // First non-empty body row chars (trimmed).
        let stringify = |row: &Vec<Cell>| -> String {
            row.iter().filter_map(|c| match c {
                Cell::Char { ch, .. } => Some(*ch),
                _ => None,
            }).collect::<String>().trim().to_string()
        };
        let rows: Vec<String> = f.body.iter().map(stringify).collect();
        // With squeeze: a, blank, b. Then padding.
        assert_eq!(&rows[0], "a");
        assert_eq!(&rows[1], "");
        assert_eq!(&rows[2], "b");
    }

    #[test]
    fn header_pins_top_rows_when_scrolling() {
        // 12 lines, 6-row terminal → body_rows = 5. header=2 pins lines 0,1.
        let mut content = Vec::new();
        for n in 0..12 { content.extend_from_slice(format!("line{n}\n").as_bytes()); }
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(20, 6, "f".into());
        v.set_header(2, 0);
        // set_header floors top_line at header_lines, so we start showing
        // line2 in the scroll window. Scrolling down 5 advances by 5
        // logical lines from there.
        v.scroll_lines(5, &m, &mut idx);
        let f = v.frame(&m, &mut idx);
        let chs = |row: &Vec<Cell>| -> String {
            row.iter().filter_map(|c| match c {
                Cell::Char { ch, .. } => Some(*ch),
                _ => None,
            }).collect::<String>().trim().to_string()
        };
        // Rows 0 and 1 are the pinned header (line0, line1) regardless of scroll.
        assert_eq!(&chs(&f.body[0]), "line0");
        assert_eq!(&chs(&f.body[1]), "line1");
        // top_line is now 2 + 5 = 7; row 2 shows line7.
        assert_eq!(&chs(&f.body[2]), "line7");
    }

    #[test]
    fn page_size_when_set_overrides_body_rows() {
        let mut content = Vec::new();
        for n in 0..100 { content.extend_from_slice(format!("L{n}\n").as_bytes()); }
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(20, 10, "f".into());
        v.set_page_size(Some(3));
        let before = v.top_line();
        v.page_down(&m, &mut idx);
        assert_eq!(v.top_line(), before + 3);
        v.page_up(&m, &mut idx);
        assert_eq!(v.top_line(), before);
    }

    #[test]
    fn page_size_unset_uses_body_rows() {
        let mut content = Vec::new();
        for n in 0..100 { content.extend_from_slice(format!("L{n}\n").as_bytes()); }
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(20, 10, "f".into());
        // body_rows = rows - 1 = 9.
        v.page_down(&m, &mut idx);
        assert_eq!(v.top_line(), 9);
    }

    #[test]
    fn header_zero_lines_renders_like_no_header() {
        let mut content = Vec::new();
        for n in 0..10 { content.extend_from_slice(format!("line{n}\n").as_bytes()); }
        let (m, mut idx) = setup(&content);
        let mut v = Viewport::new(20, 6, "f".into());
        v.set_header(0, 0);
        let f = v.frame(&m, &mut idx);
        let chs = |row: &Vec<Cell>| -> String {
            row.iter().filter_map(|c| match c {
                Cell::Char { ch, .. } => Some(*ch),
                _ => None,
            }).collect::<String>().trim().to_string()
        };
        assert_eq!(&chs(&f.body[0]), "line0");
        assert_eq!(&chs(&f.body[1]), "line1");
    }

    #[test]
    fn squeeze_off_preserves_blanks() {
        let (m, mut idx) = setup(b"a\n\n\n\nb\n");
        let mut v = Viewport::new(10, 8, "f".into());
        // Default is off.
        let f = v.frame(&m, &mut idx);
        let stringify = |row: &Vec<Cell>| -> String {
            row.iter().filter_map(|c| match c {
                Cell::Char { ch, .. } => Some(*ch),
                _ => None,
            }).collect::<String>().trim().to_string()
        };
        let rows: Vec<String> = f.body.iter().map(stringify).collect();
        // Without squeeze: a, blank, blank, blank, b.
        assert_eq!(&rows[0], "a");
        assert_eq!(&rows[1], "");
        assert_eq!(&rows[2], "");
        assert_eq!(&rows[3], "");
        assert_eq!(&rows[4], "b");
    }

    #[test]
    fn qae_second_resets_on_backward_motion() {
        let (m, mut idx) = setup(b"a\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_quit_at_eof(QuitAtEof::Second);
        v.goto_bottom(&m, &mut idx);
        assert!(!v.note_motion_for_eof(true, &m, &idx));
        // Backward motion clears the counter.
        v.note_motion_for_eof(false, &m, &idx);
        // Next forward starts fresh: counts, doesn't quit.
        assert!(!v.note_motion_for_eof(true, &m, &idx));
        // Now the second consecutive forward triggers quit.
        assert!(v.note_motion_for_eof(true, &m, &idx));
    }

    #[test]
    fn flash_message_overrides_follow_suffix() {
        let (m, mut idx) = setup(b"a\nb\n");
        let mut v = Viewport::new(40, 5, "f".into());
        v.set_follow_mode(true);
        v.flash("(F reopened)", 3);
        let f = v.frame(&m, &mut idx);
        assert!(f.status.contains("(F reopened)"), "{}", f.status);
        assert!(!f.status.contains("(F idle)"));
    }

    #[test]
    fn flash_countdown_clears() {
        let mut v = Viewport::new(10, 5, "f".into());
        v.flash("hello", 2);
        v.tick_flash();
        assert!(v.status_flash.is_some());
        v.tick_flash();
        assert!(v.status_flash.is_none());
    }

    #[test]
    fn suspend_follow_if_off_is_noop() {
        let mut v = Viewport::new(10, 5, "f".into());
        v.set_follow_mode(true);
        v.suspend_follow_if(false);
        assert!(v.follow_mode());
    }

    #[test]
    fn suspend_follow_if_on_flips_off() {
        let mut v = Viewport::new(10, 5, "f".into());
        v.set_follow_mode(true);
        v.suspend_follow_if(true);
        assert!(!v.follow_mode());
    }

    #[test]
    fn case_mode_sensitive_returns_pattern_unchanged() {
        assert_eq!(CaseMode::Sensitive.apply_to_pattern("foo"), "foo");
        assert_eq!(CaseMode::Sensitive.apply_to_pattern("FOO"), "FOO");
    }

    #[test]
    fn case_mode_insensitive_prepends_i_flag() {
        assert_eq!(CaseMode::Insensitive.apply_to_pattern("foo"), "(?i)foo");
        assert_eq!(CaseMode::Insensitive.apply_to_pattern("FOO"), "(?i)FOO");
    }

    #[test]
    fn case_mode_smart_lowercase_is_insensitive() {
        assert_eq!(CaseMode::Smart.apply_to_pattern("foo"), "(?i)foo");
    }

    #[test]
    fn case_mode_smart_with_uppercase_is_sensitive() {
        assert_eq!(CaseMode::Smart.apply_to_pattern("Foo"), "Foo");
        assert_eq!(CaseMode::Smart.apply_to_pattern("FOO"), "FOO");
    }

    #[test]
    fn set_case_mode_recompiles_active_search() {
        let (m, mut idx) = setup(b"hello WORLD\n");
        let mut v = Viewport::new(40, 5, "f".into());
        v.set_search("world".into(), SearchDirection::Forward).unwrap();
        // Sensitive: no match for lowercase against WORLD.
        assert!(!v.search_repeat(&m, &mut idx, false));
        // Switch to insensitive — should re-compile and now match.
        v.set_case_mode(CaseMode::Insensitive);
        assert!(v.search_repeat(&m, &mut idx, false));
    }

    #[test]
    fn status_shows_prettify_label_when_set() {
        let (m, mut idx) = setup(b"a\n");
        let mut v = Viewport::new(40, 5, "f".into());
        let frame_off = v.frame(&m, &mut idx);
        assert!(!frame_off.status.contains("[pretty"));
        v.set_prettify_label(Some("json".into()));
        let frame_on = v.frame(&m, &mut idx);
        assert!(frame_on.status.contains("[pretty:json]"),
            "expected [pretty:json] in status, got: {}", frame_on.status);
        v.set_prettify_label(Some("json:err".into()));
        let frame_err = v.frame(&m, &mut idx);
        assert!(frame_err.status.contains("[pretty:json:err]"),
            "expected [pretty:json:err] in status, got: {}", frame_err.status);
    }

    #[test]
    fn status_shows_l_suffix_when_live_mode_on() {
        let (m, mut idx) = setup(b"a\nb\n");
        let mut v = Viewport::new(20, 5, "f".into());
        let frame_off = v.frame(&m, &mut idx);
        assert!(!frame_off.status.contains("(L)"));
        v.set_live_mode(true);
        let frame_on = v.frame(&m, &mut idx);
        assert!(frame_on.status.contains("(L)"), "expected (L) in status, got: {}", frame_on.status);
    }

    #[test]
    fn clamp_top_line_pulls_back_when_total_shrinks() {
        let mut v = Viewport::new(20, 5, "f".into());
        // Pretend we were on line 100, then a rewrite leaves only 10 lines.
        v.scroll_lines(0, &MockSource::new(), &mut LineIndex::new()); // no-op, just to satisfy
        // Force top_line via a sequence; easiest: just call clamp directly.
        // We can't poke private state, but clamp works regardless of how we got there.
        v.clamp_top_line(100);  // total bigger than top_line=0, no change
        v.clamp_top_line(0);    // empty source: must reset
        // After clamp(0), line 0 is the floor.
        // (No public getter for top_line; we verify indirectly by going to top.)
        v.goto_top();
        // Just confirm no panic and no overflow on subsequent frame composition.
        let (m, mut idx) = setup(b"only\n");
        let _ = v.frame(&m, &mut idx);
    }

    /// Simulates the app::run timeout-branch logic to verify auto-scroll engages
    /// when follow mode is on and the viewport is at the bottom.
    fn simulate_growth_tick(
        v: &mut Viewport,
        src: &MockSource,
        idx: &mut LineIndex,
    ) {
        if !v.follow_mode() { return; }
        let was_at_bottom = v.is_at_bottom(src, idx);
        let lines_before = idx.line_count();
        idx.notice_new_bytes(src);
        if idx.line_count() != lines_before && was_at_bottom {
            v.goto_bottom(src, idx);
        }
    }

    #[test]
    fn auto_scroll_engages_when_at_bottom() {
        let m = MockSource::new();
        m.append(b"1\n2\n3\n4\n");  // 4 lines, body=4 fits
        let mut idx = LineIndex::new();
        let mut v = Viewport::new(10, 5, "f".into());
        v.set_follow_mode(true);
        idx.extend_to_end(&m);
        assert!(v.is_at_bottom(&m, &idx));
        let top_before = {
            let f = v.frame(&m, &mut idx);
            f.status.clone()  // unused, just exercise frame
        };
        let _ = top_before;
        // Simulate growth: source gains 4 more lines.
        m.append(b"5\n6\n7\n8\n");
        simulate_growth_tick(&mut v, &m, &mut idx);
        // After auto-scroll, top_line should have advanced so the new last line is in view.
        assert!(v.is_at_bottom(&m, &idx), "after auto-scroll, viewport should still be at bottom");
        let frame = v.frame(&m, &mut idx);
        // The bottom-most body row should now contain the last logical line ('8').
        // Find which row has '8'.
        let last_row = &frame.body[frame.body.len() - 1];
        assert_eq!(last_row[0], Cell::Char { ch: '8', width: 1, style: crate::ansi::Style::default(), hyperlink: None });
    }

    #[test]
    fn auto_scroll_suppressed_when_scrolled_up() {
        let m = MockSource::new();
        m.append(b"1\n2\n3\n4\n5\n6\n7\n8\n");  // 8 lines
        let mut idx = LineIndex::new();
        let mut v = Viewport::new(10, 5, "f".into());  // body=4
        v.set_follow_mode(true);
        idx.extend_to_end(&m);
        v.goto_bottom(&m, &mut idx);
        // Now scroll up off the bottom.
        v.scroll_lines(-2, &m, &mut idx);
        assert!(!v.is_at_bottom(&m, &idx));
        let frame_before = v.frame(&m, &mut idx);
        let top_first_cell_before = frame_before.body[0][0].clone();
        // Simulate growth.
        m.append(b"9\n10\n");
        simulate_growth_tick(&mut v, &m, &mut idx);
        // Viewport should NOT have moved (auto-scroll suppressed).
        let frame_after = v.frame(&m, &mut idx);
        assert_eq!(frame_after.body[0][0], top_first_cell_before, "viewport moved despite being scrolled up");
    }

    // ----- Search -----

    #[test]
    fn set_search_compiles_regex() {
        let mut v = Viewport::new(10, 5, "f".into());
        assert!(v.set_search("foo".into(), SearchDirection::Forward).is_ok());
        assert!(v.search_active());
    }

    #[test]
    fn set_search_rejects_bad_regex() {
        let mut v = Viewport::new(10, 5, "f".into());
        let err = v.set_search("[".into(), SearchDirection::Forward).unwrap_err();
        assert!(!err.is_empty());
        assert!(!v.search_active(), "no search should be set on error");
    }

    #[test]
    fn search_step_forward_finds_match_after_top() {
        let (m, mut idx) = setup(b"alpha\nbeta\ngamma\ndelta\nepsilon\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_search("gamma".into(), SearchDirection::Forward).unwrap();
        let found = v.search_repeat(&m, &mut idx, false);
        assert!(found);
        // gamma is line 2 (0-indexed)
        assert_eq!(v.top_line, 2);
    }

    #[test]
    fn search_step_backward_finds_match_before_top() {
        let (m, mut idx) = setup(b"alpha\nbeta\ngamma\ndelta\nepsilon\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.scroll_lines(4, &m, &mut idx); // top_line = 4
        v.set_search("alpha".into(), SearchDirection::Backward).unwrap();
        let found = v.search_repeat(&m, &mut idx, false);
        assert!(found);
        assert_eq!(v.top_line, 0);
    }

    #[test]
    fn search_wraps_at_end() {
        let (m, mut idx) = setup(b"alpha\nbeta\ngamma\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.scroll_lines(2, &m, &mut idx); // top_line = 2 (last line)
        v.set_search("alpha".into(), SearchDirection::Forward).unwrap();
        let found = v.search_repeat(&m, &mut idx, false);
        assert!(found, "search should wrap forward past EOF");
        assert_eq!(v.top_line, 0);
    }

    #[test]
    fn search_no_match_returns_false_and_does_not_move() {
        let (m, mut idx) = setup(b"alpha\nbeta\ngamma\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_search("nowhere".into(), SearchDirection::Forward).unwrap();
        let found = v.search_repeat(&m, &mut idx, false);
        assert!(!found);
        assert_eq!(v.top_line, 0);
    }

    #[test]
    fn frame_records_highlight_ranges_for_matches() {
        let (m, mut idx) = setup(b"alpha\nbeta\ngamma\ndelta\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_search("gamma".into(), SearchDirection::Forward).unwrap();
        let frame = v.frame(&m, &mut idx);
        // Body has 4 rows; row 2 is "gamma" (5 chars at columns 0..5).
        assert_eq!(frame.row_styles[0], RowStyle::Normal);
        assert!(frame.highlights[0].is_empty());
        assert!(frame.highlights[1].is_empty());
        assert_eq!(frame.highlights[2], vec![0..5]);
        assert!(frame.highlights[3].is_empty());
    }

    #[test]
    fn frame_highlights_substring_inside_a_row() {
        let (m, mut idx) = setup(b"the alpha and the beta\nfoo\n");
        let mut v = Viewport::new(40, 5, "f".into());
        v.set_search("beta".into(), SearchDirection::Forward).unwrap();
        let frame = v.frame(&m, &mut idx);
        // "beta" starts at column 18 in the first row.
        assert_eq!(frame.highlights[0], vec![18..22]);
        assert!(frame.highlights[1].is_empty());
    }

    #[test]
    fn search_highlight_with_filter_dim_keeps_row_dim() {
        // alpha matches filter → Normal. beta doesn't → Dim. Search for
        // "beta" should leave row style Dim and mark the substring 0..4.
        let (m, mut idx) = setup(b"alpha\nbeta\n");
        let mut v = Viewport::new(20, 5, "f".into());
        let fmt = crate::format::LogFormat::compile(
            "simple",
            r"^(?P<line>.+)$",
        )
        .unwrap();
        let f = crate::filter::CompiledFilter::compile(
            &fmt,
            vec![crate::filter::FilterSpec::parse("line=alpha").unwrap()],
            CaseMode::Sensitive,
        )
        .unwrap();
        v.set_filter(Some(f));
        v.set_dim_mode(true);
        v.set_search("beta".into(), SearchDirection::Forward).unwrap();
        let frame = v.frame(&m, &mut idx);
        assert_eq!(frame.row_styles[0], RowStyle::Normal);
        assert_eq!(frame.row_styles[1], RowStyle::Dim);
        assert_eq!(frame.highlights[1], vec![0..4]);
    }

    #[test]
    fn grep_only_hides_non_matching_lines() {
        use crate::grep::GrepPredicate;
        let src = crate::source::MockSource::new();
        src.append(b"keep this error\n");
        src.append(b"drop this one\n");
        src.append(b"another error line\n");
        src.finish();
        let mut idx = crate::line_index::LineIndex::new();
        idx.extend_to_end(&src);

        let mut v = Viewport::new(40, 5, "test".into());
        v.set_grep(Some(GrepPredicate::compile(&["error".to_string()], crate::viewport::CaseMode::Sensitive).unwrap()));
        v.extend_visible_lines(&idx, &src);

        // Only the two "error" lines should be visible.
        let frame = v.frame(&src, &mut idx);
        let body_text: Vec<String> = frame.body.iter()
            .map(|row| row.iter().filter_map(|c| match c {
                crate::render::Cell::Char { ch, .. } => Some(*ch),
                _ => None,
            }).collect())
            .collect();
        assert!(body_text[0].contains("keep this error"));
        assert!(body_text[1].contains("another error line"));
        assert!(frame.status.contains("[grep]"));
    }

    #[test]
    fn incsearch_preview_anchors_from_origin_not_previous_match() {
        // The valuable invariant: every preview restarts its scan from
        // `origin`, never from where the previous preview landed. We prove
        // this by previewing a far-below match, then previewing a second
        // pattern that has matches BOTH above and below the first match.
        // Anchoring from origin must pick the earlier (above) match; a scan
        // that continued forward from the previous match would pick the
        // later (below) one instead.
        let src = crate::source::MockSource::new();
        src.append(b"zero\n");    // line 0
        src.append(b"one\n");     // line 1
        src.append(b"origin\n");  // line 2 — the search origin (non-(0,0))
        src.append(b"three\n");   // line 3
        src.append(b"mark\n");    // line 4 — second pattern, ABOVE first match
        src.append(b"five\n");    // line 5
        src.append(b"six\n");     // line 6
        src.append(b"seven\n");   // line 7
        src.append(b"target\n");  // line 8 — first pattern's only match (below)
        src.append(b"mark\n");    // line 9 — second pattern, BELOW first match
        src.finish();
        let mut idx = crate::line_index::LineIndex::new();

        let origin = (2usize, 0usize);
        let mut vp = Viewport::new(20, 4, "test".into()); // body = 3
        vp.set_top(origin.0, origin.1);
        assert_eq!(vp.top_line(), 2);

        // Step 1: preview a match well below origin — jumps onto it.
        vp.incsearch_preview(&src, &mut idx, "target", SearchDirection::Forward, origin);
        assert_eq!(vp.top_line(), 8, "should land on the far-below match");
        assert_eq!(vp.top_row(), 0);

        // Step 2: from the SAME origin, preview a pattern whose matches are at
        // line 4 (above the first match) and line 9 (below it). Because the
        // preview re-anchors at origin (line 2) before scanning forward, it
        // must land on line 4 — not line 9, which is what a scan continuing
        // forward from the previous match (line 8) would have found first.
        vp.incsearch_preview(&src, &mut idx, "mark", SearchDirection::Forward, origin);
        assert_eq!(
            vp.top_line(), 4,
            "preview must reset to origin before scanning, landing on the match \
             after origin rather than continuing forward from the previous match"
        );
        assert_eq!(vp.top_row(), 0);
    }

    #[test]
    fn incsearch_preview_empty_or_invalid_is_noop() {
        let (src, mut idx) = setup(b"alpha\nbeta\n[unbalanced\n");
        let mut vp = Viewport::new(20, 4, "test".into());
        vp.set_top(1, 0);
        // Empty pattern: no-op, position unchanged.
        vp.incsearch_preview(&src, &mut idx, "", SearchDirection::Forward, (0, 0));
        assert_eq!(vp.top_line(), 1);
        // Invalid regex: silent, position reset to origin but no jump/panic.
        vp.incsearch_preview(&src, &mut idx, "(", SearchDirection::Forward, (0, 0));
        assert_eq!(vp.top_line(), 0);
    }

    #[test]
    fn filter_and_grep_combine_with_and() {
        use crate::grep::GrepPredicate;
        let fmt = crate::format::LogFormat::compile(
            "simple",
            r"^(?P<level>\w+) (?P<msg>.+)$",
        ).unwrap();
        let f = crate::filter::CompiledFilter::compile(
            &fmt,
            vec![crate::filter::FilterSpec::parse("level=ERROR").unwrap()],
            CaseMode::Sensitive,
        ).unwrap();
        let g = GrepPredicate::compile(&["timeout".to_string()], crate::viewport::CaseMode::Sensitive).unwrap();

        let src = crate::source::MockSource::new();
        src.append(b"ERROR timeout connecting\n");      // matches both → keep
        src.append(b"ERROR file not found\n");          // matches filter only → drop
        src.append(b"WARN timeout retrying\n");         // matches grep only → drop
        src.append(b"INFO all good\n");                 // matches neither → drop
        src.finish();
        let mut idx = crate::line_index::LineIndex::new();
        idx.extend_to_end(&src);

        let mut v = Viewport::new(80, 5, "test".into());
        v.set_filter(Some(f));
        v.set_grep(Some(g));
        v.extend_visible_lines(&idx, &src);
        assert_eq!(v.visible_lines(), &[0usize]);
    }

    #[test]
    fn search_status_shows_pattern() {
        let (m, mut idx) = setup(b"x\n");
        let mut v = Viewport::new(20, 5, "f".into());
        v.set_search("foo".into(), SearchDirection::Forward).unwrap();
        let frame = v.frame(&m, &mut idx);
        assert!(frame.status.contains("[/foo]"), "status: {}", frame.status);
    }

    #[test]
    fn repeat_search_after_first_match_advances() {
        let (m, mut idx) = setup(b"alpha\nfoo one\nbeta\nfoo two\ngamma\nfoo three\n");
        let mut v = Viewport::new(40, 5, "f".into());
        v.set_search("foo".into(), SearchDirection::Forward).unwrap();
        assert!(v.search_repeat(&m, &mut idx, false));
        assert_eq!(v.top_line, 1, "first foo");
        v.set_search("foo".into(), SearchDirection::Forward).unwrap();
        assert!(v.search_repeat(&m, &mut idx, false), "second search should still match");
        assert_eq!(v.top_line, 3, "should advance to next foo");
    }

    #[test]
    fn auto_scroll_paused_when_follow_off() {
        let m = MockSource::new();
        m.append(b"1\n2\n3\n4\n");
        let mut idx = LineIndex::new();
        let mut v = Viewport::new(10, 5, "f".into());
        // Follow is off; viewport at top.
        idx.extend_to_end(&m);
        let frame_before = v.frame(&m, &mut idx);
        let top_first_cell = frame_before.body[0][0].clone();
        m.append(b"5\n6\n7\n8\n");
        simulate_growth_tick(&mut v, &m, &mut idx);
        let frame_after = v.frame(&m, &mut idx);
        assert_eq!(frame_after.body[0][0], top_first_cell, "auto-scroll fired despite follow off");
    }

    // ----- Records-mode search -----

    #[test]
    fn search_jumps_to_next_matching_record() {
        let m = MockSource::new();
        m.append(b"[1] alpha\n  cont\n[2] bravo\n[3] charlie\n  cont\n[4] delta\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_search("charlie".into(), SearchDirection::Forward).unwrap();
        let hit = v.search_repeat(&m, &mut idx, false);
        assert!(hit, "should find 'charlie' in record 2");
        assert_eq!(v.top_line(), 3);  // record 2 starts at line 3 ("[3] charlie")
    }

    #[test]
    fn search_finds_cross_line_match_in_record_with_s_flag() {
        let m = MockSource::new();
        m.append(b"[1] head\n  Renderer.php(214)\n[2] other line\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_search(r"(?s)head.*Renderer".into(), SearchDirection::Forward).unwrap();
        let hit = v.search_repeat(&m, &mut idx, false);
        assert!(hit, "should match across \\n inside record 0 with (?s)");
        assert_eq!(v.top_line(), 0);
    }

    #[test]
    fn search_repeat_with_no_match_returns_false() {
        let m = MockSource::new();
        m.append(b"[1] alpha\n[2] bravo\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_search("nonexistent".into(), SearchDirection::Forward).unwrap();
        let hit = v.search_repeat(&m, &mut idx, false);
        assert!(!hit);
    }

    // ----- Records-mode filter/grep -----

    #[test]
    fn filter_hide_mode_drops_all_lines_of_nonmatching_record() {
        // Record 0: "[1] head\n  cont a" — grep matches "cont a" → visible.
        // Record 1: "[2] head\n  cont b" — grep does NOT match → hidden.
        let m = MockSource::new();
        m.append(b"[1] head\n  cont a\n[2] head\n  cont b\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let grep = GrepPredicate::compile(&["cont a".to_string()], crate::viewport::CaseMode::Sensitive).unwrap();
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_grep(Some(grep));
        v.extend_visible_lines(&idx, &m);
        // Record 0 ([1] head + cont a) matches; lines 0 and 1 visible.
        // Record 1 ([2] head + cont b) does not match; lines 2 and 3 hidden.
        assert_eq!(v.visible_lines(), &[0usize, 1]);
    }

    #[test]
    fn filter_in_records_mode_keeps_whole_record_when_header_matches() {
        // The format regex is designed for the header line (it ends with `$`).
        // Applied to the full multi-line record bytes it would never match
        // because `$` doesn't match before a non-final `\n`. Records-mode
        // filter must evaluate against the first line of the record, then
        // include all of the record's lines when it matches.
        let m = MockSource::new();
        m.append(
            b"[1] kind=category\n  body a\n  body a2\n[2] kind=rule\n  body b\n",
        );
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let fmt = crate::format::LogFormat::compile(
            "rec",
            r"^\[(?P<id>\d+)\] kind=(?P<kind>.+)$",
        )
        .unwrap();
        let f = crate::filter::CompiledFilter::compile(
            &fmt,
            vec![crate::filter::FilterSpec::parse("kind~category").unwrap()],
            CaseMode::Sensitive,
        )
        .unwrap();
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_filter(Some(f));
        v.extend_visible_lines(&idx, &m);
        // Record 0 (lines 0, 1, 2) matches; record 1 (lines 3, 4) does not.
        assert_eq!(v.visible_lines(), &[0usize, 1, 2]);
    }

    #[test]
    fn grep_matches_across_record_newlines_in_records_mode() {
        // Pattern spans the record-header and a continuation line (needs (?s) for .).
        let m = MockSource::new();
        m.append(b"[1] head\n  Renderer.php\n[2] other\n  body\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let grep = GrepPredicate::compile(&[r"(?s)head.*Renderer".to_string()], crate::viewport::CaseMode::Sensitive).unwrap();
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_grep(Some(grep));
        v.extend_visible_lines(&idx, &m);
        // Record 0 matches (cross-line); record 1 does not.
        assert_eq!(v.visible_lines(), &[0usize, 1]);
    }

    #[test]
    fn dim_mode_keeps_all_lines_visible_dims_nonmatching_records() {
        // All 4 lines stay in visible_lines (dim mode = no hiding).
        // Record 0 matches grep → Normal; record 1 does not → Dim.
        let m = MockSource::new();
        m.append(b"[1] head\n  cont\n[2] other\n  cont\n");
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let grep = GrepPredicate::compile(&[r"\[1\]".to_string()], CaseMode::Sensitive).unwrap();
        let mut v = Viewport::new(40, 10, "f".into());
        v.set_grep(Some(grep));
        v.set_dim_mode(true);
        v.extend_visible_lines(&idx, &m);
        // Dim mode: visible_lines stays empty (hide_mode() is false).
        assert_eq!(v.visible_lines(), &[] as &[usize]);
        // Dim decision is per record: lines 0 and 1 belong to matching record → Normal.
        assert!(!v.should_dim_line(0, &idx, &m));
        assert!(!v.should_dim_line(1, &idx, &m));
        // Lines 2 and 3 belong to non-matching record → Dim.
        assert!(v.should_dim_line(2, &idx, &m));
        assert!(v.should_dim_line(3, &idx, &m));
    }

    #[test]
    fn status_unchanged_when_records_inactive() {
        let (m, mut idx) = setup(b"a\nb\nc\n");
        let mut v = Viewport::new(20, 5, "f".into());
        let frame = v.frame(&m, &mut idx);
        let status = &frame.status;
        // Default format: <label>  <top>-<bot>/<total>  <pct>%
        assert!(status.contains("1-3/3"), "got: {status}");
        assert!(!status.contains("L1"), "no L block in line-mode: {status}");
        assert!(!status.contains("R1"), "no R block in line-mode: {status}");
    }

    #[test]
    fn status_r_block_uses_real_lines_in_hide_mode() {
        // Regression: in hide mode `bottom` is a position in visible_lines
        // (i.e. a count of *visible* matches), not a logical line index.
        // The R-block was passing that position into `line_to_record`, which
        // resolved to whatever record contained logical line `bottom-1` —
        // typically a very early record, producing nonsense like `R290-8`
        // where the bottom record is *before* the top record on screen.
        // Build a scenario: many records, only the last few match the filter,
        // and the viewport is scrolled to the matching tail.
        let m = MockSource::new();
        // 10 records, two physical lines each. Record N's header has `kind=A`
        // for N < 8 and `kind=B` for N >= 8 (so only records 8 and 9 match).
        let mut buf = Vec::new();
        for n in 0..10 {
            let kind = if n >= 8 { "B" } else { "A" };
            buf.extend_from_slice(format!("[{}] kind={}\n  body {}\n", n, kind, n).as_bytes());
        }
        m.append(&buf);
        m.finish();

        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);

        let fmt = crate::format::LogFormat::compile(
            "rec",
            r"^\[(?P<id>\d+)\] kind=(?P<kind>.+)$",
        )
        .unwrap();
        let f = crate::filter::CompiledFilter::compile(
            &fmt,
            vec![crate::filter::FilterSpec::parse("kind=B").unwrap()],
            CaseMode::Sensitive,
        )
        .unwrap();

        // 5-row terminal: 4 body rows + 1 status row. With 4 visible-matches
        // rows of body and 4 visible lines, the whole filtered set fits.
        let mut v = Viewport::new(80, 5, "f".into());
        v.set_filter(Some(f));
        v.extend_visible_lines(&idx, &m);

        // Jump to the first matching record (record 8, 0-indexed).
        v.goto_record(8, &m, &mut idx);

        let frame = v.frame(&m, &mut idx);
        // Records 8 (rec_top=9) and 9 (rec_bottom=10) are on screen.
        assert!(
            frame.status.contains("R9-10/10"),
            "expected R9-10/10 in status, got: {}",
            frame.status,
        );
    }

    #[test]
    fn status_dual_readout_when_records_active() {
        let m = MockSource::new();
        m.append(b"[1] a\n  cont\n[2] b\n");
        m.finish();
        let mut idx = LineIndex::new();
        idx.set_record_start(regex::bytes::Regex::new(r"^\[").unwrap());
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        let frame = v.frame(&m, &mut idx);
        let status = &frame.status;
        assert!(status.contains("L1-3/3"), "lines block missing or wrong: {status}");
        assert!(status.contains("R1-2/2"), "records block missing or wrong: {status}");
    }

    #[test]
    fn format_status_uses_custom_template_when_set() {
        let m = MockSource::new();
        m.append(b"a\nb\nc\n");
        m.finish();
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(20, 5, "f".into());
        let prompt = crate::prompt::ParsedPrompt::parse("<label> <pct>%").unwrap();
        v.set_prompt(Some(prompt));
        let frame = v.frame(&m, &mut idx);
        assert_eq!(frame.status, "f 100%");
    }

    #[test]
    fn status_shows_preprocess_failed_tag_when_set() {
        let m = MockSource::new();
        m.append(b"a\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(40, 5, "f".into());
        v.set_preprocess_failure(Some("pdftotext: not found".to_string()));
        let frame = v.frame(&m, &mut idx);
        assert!(frame.status.contains("[preprocess-failed: pdftotext: not found]"),
                "got: {}", frame.status);
    }

    #[test]
    fn default_status_includes_help_hint() {
        let (m, mut idx) = setup(b"a\nb\nc\n");
        let mut v = Viewport::new(80, 5, "f".into());
        let frame = v.frame(&m, &mut idx);
        assert!(frame.status.ends_with(":help"), "got: {:?}", frame.status);
    }

    #[test]
    fn custom_prompt_does_not_get_help_hint() {
        let (m, mut idx) = setup(b"a\nb\nc\n");
        let mut v = Viewport::new(80, 5, "f".into());
        v.set_prompt(Some(crate::prompt::ParsedPrompt::parse("<label>").unwrap()));
        let frame = v.frame(&m, &mut idx);
        assert!(!frame.status.contains(":help"), "got: {:?}", frame.status);
    }

    #[test]
    fn status_shows_file_index_when_multifile() {
        let m = MockSource::new();
        m.append(b"a\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(60, 5, "f.log".into());
        v.set_file_index(0, 3);
        let frame = v.frame(&m, &mut idx);
        assert!(frame.status.contains("f.log  [1/3]"), "got: {}", frame.status);
    }

    #[test]
    fn status_omits_file_index_when_single_file() {
        let m = MockSource::new();
        m.append(b"a\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(60, 5, "f.log".into());
        v.set_file_index(0, 1);
        let frame = v.frame(&m, &mut idx);
        assert!(!frame.status.contains('['), "should not show [1/1] for single-file: {}", frame.status);
    }

    #[test]
    fn status_shows_tag_active_when_multimatch() {
        let m = MockSource::new();
        m.append(b"a\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(80, 5, "f.log".into());
        v.set_tag_active(Some(("foo".into(), 2, 3)));
        let frame = v.frame(&m, &mut idx);
        assert!(
            frame.status.contains("[tag: foo (2/3)]"),
            "got: {}",
            frame.status
        );
    }

    #[test]
    fn status_omits_tag_active_when_single_match() {
        let m = MockSource::new();
        m.append(b"a\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let mut v = Viewport::new(80, 5, "f.log".into());
        v.set_tag_active(Some(("foo".into(), 1, 1)));
        let frame = v.frame(&m, &mut idx);
        assert!(
            !frame.status.contains("[tag:"),
            "should not show indicator for single match: {}",
            frame.status
        );
    }

    #[test]
    fn hscroll_noop_when_wrapping() {
        let mut v = Viewport::new(80, 24, "t".into());
        // default is wrap ON → hscroll inactive
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 0);
    }

    #[test]
    fn hscroll_active_in_chop_and_clamps_at_zero() {
        let mut v = Viewport::new(80, 24, "t".into());
        v.toggle_chop(); // turn chop ON (wrap off)
        assert!(v.hscroll_active());
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 8);
        v.hscroll_right_half();
        assert_eq!(v.left_col(), 8 + 40); // cols/2 = 40
        v.hscroll_left_half();
        assert_eq!(v.left_col(), 8);
        v.hscroll_left_half();
        assert_eq!(v.left_col(), 0); // clamps at 0
    }

    #[test]
    fn hscroll_by_explicit_cols_moves_left_col() {
        // `--shift N` path: scroll right/left by an explicit column count.
        let mut v = Viewport::new(80, 24, "t".into());
        v.toggle_chop(); // chop on so hscroll is active
        v.hscroll_right_cols(12);
        assert_eq!(v.left_col(), 12);
        v.hscroll_right_cols(12);
        assert_eq!(v.left_col(), 24);
        v.hscroll_left_cols(12);
        assert_eq!(v.left_col(), 12);
        v.hscroll_left_cols(99);
        assert_eq!(v.left_col(), 0); // clamps at 0
    }

    #[test]
    fn hscroll_resets_to_zero_when_wrap_turned_on() {
        let mut v = Viewport::new(80, 24, "t".into());
        v.toggle_chop();             // chop on
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 8);
        v.toggle_chop();             // wrap back on → reset
        assert_eq!(v.left_col(), 0);
    }

    #[test]
    fn reset_hscroll_zeroes_left_col() {
        // The new-file path (app::switch_file) calls this after goto_top.
        let mut v = Viewport::new(80, 24, "t".into());
        v.toggle_chop();
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 8);
        v.reset_hscroll();
        assert_eq!(v.left_col(), 0);
    }

    // ----- SGR state reconstruction tests -----

    #[test]
    fn reconstruct_picks_up_state_from_prior_lines() {
        let m = MockSource::new();
        m.append(b"\x1b[31mline 1\n");
        m.append(b"line 2 (still red, no reset)\n");
        m.append(b"line 3\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let state = reconstruct_render_state(&m, &idx, 2);
        assert_eq!(
            state.style.fg,
            Some(crate::ansi::Color::Ansi(1)),
            "red SGR from line 0 should persist to line 2"
        );
    }

    #[test]
    fn reconstruct_respects_reset_between_lines() {
        let m = MockSource::new();
        m.append(b"\x1b[31mline 1\x1b[0m\n");
        m.append(b"line 2 (default)\n");
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        let state = reconstruct_render_state(&m, &idx, 1);
        assert_eq!(state.style.fg, None);
    }

    #[test]
    fn reconstruct_caps_walkback_at_max_lines() {
        let m = MockSource::new();
        m.append(b"\x1b[31mvery early\n");
        for _ in 0..300 {
            m.append(b"line\n");
        }
        let mut idx = LineIndex::new();
        idx.extend_to_end(&m);
        // Line 290 is 290 lines past the red SGR. We cap at 256, so the
        // anchor we'd pick is line 34 (290 - 256), which is past the red.
        let state = reconstruct_render_state(&m, &idx, 290);
        assert_eq!(state.style.fg, None);
    }

    #[test]
    fn or_groups_narrow_within_required_line_mode() {
        let mut raw = crate::or::OrSpecRaw::new();
        raw.add_grep(crate::or::DEFAULT_GROUP, "failed".into());
        raw.add_grep(crate::or::DEFAULT_GROUP, "denied".into());
        let og = crate::or::OrGroups::compile(&raw, None, crate::viewport::CaseMode::Sensitive).unwrap();
        let mut v = Viewport::new(80, 24, "t".into());
        v.set_or_groups(og);
        assert!(v.or_active());
        assert!(v.line_passes(b"login failed"));
        assert!(v.line_passes(b"access denied"));
        assert!(!v.line_passes(b"login ok"));
    }

    #[test]
    fn status_shows_or_indicator_when_active() {
        let mut raw = crate::or::OrSpecRaw::new();
        raw.add_grep(crate::or::DEFAULT_GROUP, "x".into());
        let og = crate::or::OrGroups::compile(&raw, None, crate::viewport::CaseMode::Sensitive).unwrap();
        let (m, mut idx) = setup(b"x\ny\nx\n");
        idx.extend_to_end(&m);
        let mut v = Viewport::new(80, 5, "f".into());
        v.set_or_groups(og);
        v.extend_visible_lines(&idx, &m);
        let status = v.format_status(&idx, &m);
        assert!(status.contains("[or]"), "expected [or] in status: {status}");
        assert!(status.contains("[hide]"), "expected [hide] in status: {status}");
    }

    #[test]
    fn status_shows_col_offset_when_scrolled() {
        // Long single line wider than the viewport; chop mode + scroll right.
        let content = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\n";
        let (m, mut idx) = setup(content);
        let mut v = Viewport::new(10, 3, "t".into());
        v.toggle_chop();          // chop mode (wrap off) — hscroll active
        v.hscroll_right_step();   // left_col = HSCROLL_STEP (8)
        let f = v.frame(&m, &mut idx);
        assert!(
            f.status.contains('\u{00bb}'),
            "expected » in status after hscroll_right_step, got: {}",
            f.status
        );
    }

    #[test]
    fn frame_text_horizontal_scroll_shifts_and_marks_left_edge() {
        // A single long line "ABCDEFGHIJKLMNOPQRSTUVWXYZ..." wider than cols,
        // in chop mode with a small viewport. Tests:
        //   1) At left_col==0: first body cell is 'A', no '<' marker.
        //   2) After hscroll_right_step(): first text-region cell is '<' (left
        //      marker), and a subsequent cell shows a char that was off-screen
        //      at offset 0 (proves the content shifted).
        // HSCROLL_STEP = 8, so after one step left_col == 8. Cell 0 becomes '<'
        // and cell 1 should be 'J' (0-indexed display column 9: A=0 … I=8, J=9).
        let content = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n";
        let (m, mut idx) = setup(content);

        // 10 cols wide, 3 rows (body = 2). Default is wrap=true, so toggle chop.
        let mut v = Viewport::new(10, 3, "t".into());
        v.toggle_chop(); // chop mode = !wrap

        // ---- pass 1: no horizontal scroll ----
        let frame0 = v.frame(&m, &mut idx);
        assert_eq!(
            frame0.body[0][0],
            Cell::Char { ch: 'A', width: 1, style: crate::ansi::Style::default(), hyperlink: None },
            "at left_col=0 first cell should be 'A'"
        );
        // No '<' marker at all
        assert!(
            !frame0.body[0].iter().any(|c| matches!(c, Cell::Char { ch: '<', .. })),
            "no left marker expected at left_col=0"
        );

        // ---- pass 2: scroll right by one step (HSCROLL_STEP=8 columns) ----
        v.hscroll_right_step();
        assert_eq!(v.left_col(), 8, "left_col should be 8 after one right step");

        let frame1 = v.frame(&m, &mut idx);
        // First content cell (col 0, no gutter) should be the '<' marker.
        assert_eq!(
            frame1.body[0][0],
            Cell::Char { ch: '<', width: 1, style: crate::ansi::Style { dim: true, ..Default::default() }, hyperlink: None },
            "after scrolling right, first cell should be the '<' left marker"
        );
        // The cell at index 1 (display col 1 of the content region) was at
        // absolute column 9 = left_col(8) + 1. In "ABCDEFGHIJKL..." the char
        // at display column 9 (0-indexed) is 'J'. Verify content shifted.
        assert_eq!(
            frame1.body[0][1],
            Cell::Char { ch: 'J', width: 1, style: crate::ansi::Style::default(), hyperlink: None },
            "second cell should be 'J' (display column left_col+1 = 9)"
        );
    }

    #[test]
    fn top_line_accessor_reflects_goto() {
        let (src, mut idx) = setup(b"line0\nline1\nline2\nline3\nline4\n");
        let mut vp = Viewport::new(40, 6, "f".into());
        vp.goto_line(3, &src, &mut idx);
        assert_eq!(vp.top_line(), 3);
    }

    #[test]
    fn scroll_lock_badge_in_status() {
        let (src, mut idx) = setup(b"line0\nline1\nline2\n");
        let mut vp = Viewport::new(40, 5, "f".into());
        vp.set_scroll_lock(true);
        let frame = vp.frame(&src, &mut idx);
        assert!(frame.status.contains("[lock]"), "status was: {}", frame.status);
        vp.set_scroll_lock(false);
        let frame = vp.frame(&src, &mut idx);
        assert!(!frame.status.contains("[lock]"));
    }

    #[test]
    fn nomouse_badge_in_status() {
        let (src, mut idx) = setup(b"line one\nline two\n");
        let mut vp = Viewport::new(80, 24, "x".into());
        vp.set_mouse_off(true);
        let frame = vp.frame(&src, &mut idx);
        assert!(frame.status.contains("[nomouse]"), "status was: {}", frame.status);
        vp.set_mouse_off(false);
        let frame = vp.frame(&src, &mut idx);
        assert!(!frame.status.contains("[nomouse]"));
    }

    #[test]
    fn search_finds_decoded_latin1_line() {
        // lines: "alpha", "café" (latin1: 63 61 66 E9), "gamma"
        let data = [b"alpha\n".as_ref(), &[0x63, 0x61, 0x66, 0xE9, 0x0a], b"gamma\n"].concat();
        let (m, mut idx) = setup(&data);
        let mut vp = Viewport::new(20, 5, "f".into());
        vp.opts.encoding = crate::charset::parse_label("iso-8859-1").unwrap();
        vp.set_search("caf\u{e9}".into(), SearchDirection::Forward).unwrap();
        let found = vp.search_repeat(&m, &mut idx, false);
        assert!(found, "search should find latin-1 encoded 'café' on line 1");
        assert_eq!(vp.top_line, 1, "viewport should have scrolled to line 1");
    }
}
