uzor 1.3.0

Core UI engine — geometry, interaction, input state
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Panel render entry point and per-kind layout pipelines.
//!
//! # API convention
//!
//! - `register_input_coordinator_panel` — registers the composite + all child
//!   hit-rects with an `InputCoordinator`.  **No drawing.**
//! - `register_context_manager_panel`   — convenience wrapper: takes a
//!   `ContextManager`, registers, and draws in one call.
//!
//! # Draw order (non-Custom kinds)
//!
//! 1. Background fill
//! 2. Header strip (title + action buttons) — optional
//! 3. Header bottom divider
//! 4. Column-header row — optional (WithHeaderColumns / WithHeaderColumnsFooter)
//! 5. Column-header bottom divider
//! 6. Body closure
//! 7. Footer top divider + footer closure — optional
//! 8. Scrollbar — optional

use crate::input::core::coordinator::LayerId;
use crate::input::{InputCoordinator, Sense, WidgetKind};
use crate::render::{RenderContext, TextAlign, TextBaseline};
use crate::types::{Rect, WidgetId, CompositeId};
use crate::ui::widgets::atomic::scrollbar::render::{
    draw_scrollbar_standard, ScrollbarVisualState,
};

use super::settings::PanelSettings;
use super::state::PanelState;
use super::style::BackgroundFill;
use super::types::{PanelRenderKind, PanelView};

// ---------------------------------------------------------------------------
// Internal layout struct
// ---------------------------------------------------------------------------

struct PanelLayout {
    /// Full frame rect (same as outer `rect`).
    frame: Rect,
    /// Header strip; zero height when not rendered.
    header: Rect,
    /// Column-header row; zero height when not rendered.
    col_header: Rect,
    /// Body area available to the body closure.
    body: Rect,
    /// Footer strip; zero height when not rendered.
    footer: Rect,
    /// Scrollbar column; zero width when not rendered.
    scrollbar: Rect,
}

/// Compute the body rect for a panel given its outer frame, view,
/// settings, and render kind.  Public so the L4 `lm::panel(...).body(...)`
/// builder can clip + scroll/compress the caller-supplied body
/// closure to the right area without duplicating the layout maths.
pub fn body_rect(
    rect:     Rect,
    view:     &PanelView<'_>,
    settings: &PanelSettings,
    kind:     &PanelRenderKind,
) -> Rect {
    compute_layout(rect, view, settings, kind).body
}

// ---------------------------------------------------------------------------
// Public API — register (InputCoordinator)
// ---------------------------------------------------------------------------

/// Register the panel composite and all its child hit-rects.
///
/// **No drawing happens here.**  Use when you need explicit z-order control.
///
/// Returns the [`CompositeId`] assigned to the panel composite.
pub fn register_input_coordinator_panel(
    coord:    &mut InputCoordinator,
    id:       impl Into<WidgetId>,
    rect:     Rect,
    state:    &mut PanelState,
    view:     &PanelView<'_>,
    settings: &PanelSettings,
    kind:     &PanelRenderKind,
    layer:    &LayerId,
) -> CompositeId {
    let panel_id = coord.register_composite(id, WidgetKind::Panel, rect, Sense::CLICK, layer);

    if let PanelRenderKind::Custom(_) = kind {
        return panel_id;
    }

    let layout = compute_layout(rect, view, settings, kind);

    // --- Header action buttons ---
    if let Some(hdr) = &view.header {
        let btn_size  = 20.0_f64;
        let btn_gap   = 4.0_f64;
        let pad_right = 6.0_f64;

        for (i, action) in hdr.actions.iter().enumerate() {
            let btn_x = layout.header.x + layout.header.width
                - pad_right
                - btn_size * (i + 1) as f64
                - btn_gap * i as f64;
            let btn_y = layout.header.y + (layout.header.height - btn_size) / 2.0;
            coord.register_child(
                &panel_id,
                format!("{}:action:{}", panel_id.0.0, action.id),
                WidgetKind::Button,
                Rect::new(btn_x, btn_y, btn_size, btn_size),
                Sense::CLICK | Sense::HOVER,
            );
        }
    }

    // --- Column-header cells (sortable) + draggable separators between cols ---
    if layout.col_header.height > 0.0 && !view.columns.is_empty() {
        let available_w = layout.col_header.width;
        let mut cursor_x = layout.col_header.x;
        let n = view.columns.len();

        for (i, col) in view.columns.iter().enumerate() {
            let col_w = available_w * col.width;
            let col_rect = Rect::new(cursor_x, layout.col_header.y, col_w, layout.col_header.height);
            if col.sortable {
                coord.register_child(
                    &panel_id,
                    format!("{}:col:{}", panel_id.0.0, col.id),
                    WidgetKind::Button,
                    col_rect,
                    Sense::CLICK | Sense::HOVER,
                );
            }
            cursor_x += col_w;

            // Draggable separator on the right edge of this column (except last)
            if i + 1 < n {
                let sep_w = 6.0;
                let sep_rect = Rect::new(
                    cursor_x - sep_w / 2.0,
                    layout.col_header.y,
                    sep_w,
                    layout.body.y + layout.body.height - layout.col_header.y,
                );
                coord.register_child(
                    &panel_id,
                    format!("{}:colsep:{}", panel_id.0.0, i),
                    WidgetKind::Separator,
                    sep_rect,
                    Sense::DRAG | Sense::HOVER,
                );
            }
        }
    }

    // --- Viewport scroll zone ---
    coord.register_child(
        &panel_id,
        format!("{}:viewport", panel_id.0.0),
        WidgetKind::Custom,
        layout.body,
        Sense::SCROLL | Sense::HOVER,
    );

    // --- Body overflow handling (chevrons / scrollbar via shared helpers) ---
    {
        let scroll = crate::ui::widgets::composite::overflow::BodyScrollState {
            offset_x:  0.0,
            offset_y:  state.scroll.offset,
            content_w: view.content_width,
            content_h: view.content_height,
        };
        // Reset compress factor each frame; only Compress mode writes a
        // sub-1.0 value into it.
        state.body_compress_factor = crate::ui::widgets::composite::overflow::CompressFactor::one();
        let overflowing = scroll.overflows(layout.body.width, layout.body.height).any();
        let effective = match view.overflow {
            crate::types::OverflowMode::Scrollbar => crate::types::OverflowMode::Scrollbar,
            crate::types::OverflowMode::Chevrons  => crate::types::OverflowMode::Chevrons,
            crate::types::OverflowMode::Compress  => {
                state.body_compress_factor =
                    crate::ui::widgets::composite::overflow::compute_compress_factor(
                        view.content_width, view.content_height, layout.body, 0.4,
                    );
                crate::types::OverflowMode::Compress
            }
            // Clip + content overflows → fall back to chevrons so the user
            // can still page through hidden rows after a parent resize.
            _ if overflowing => crate::types::OverflowMode::Chevrons,
            other             => other,
        };
        if matches!(effective, crate::types::OverflowMode::Chevrons) {
            crate::ui::widgets::composite::overflow::register_chevrons_helper(
                coord, &panel_id, layout.body, &scroll, layer,
            );
        }
    }

    // --- Legacy explicit scrollbar handle + track (kept for show_scrollbar callers) ---
    if view.show_scrollbar && layout.scrollbar.width > 0.0 {
        let scroll_offset  = state.scroll.offset;
        let viewport_h     = layout.body.height;
        let content_h      = view.content_height;

        if content_h > viewport_h {
            let visible_ratio = (viewport_h / content_h).clamp(0.0, 1.0);
            let max_scroll    = (content_h - viewport_h).max(0.0);
            let scroll_ratio  = if max_scroll > 0.0 { (scroll_offset / max_scroll).clamp(0.0, 1.0) } else { 0.0 };
            let thumb_len     = (layout.scrollbar.height * visible_ratio).max(24.0).min(layout.scrollbar.height);
            let available     = (layout.scrollbar.height - thumb_len).max(0.0);
            let thumb_y       = layout.scrollbar.y + scroll_ratio * available;
            let thumb_rect    = Rect::new(layout.scrollbar.x, thumb_y, layout.scrollbar.width, thumb_len);
            let inflated      = Rect::new(
                thumb_rect.x - 5.0,
                thumb_rect.y,
                thumb_rect.width + 10.0,
                thumb_rect.height,
            );

            coord.register_child(
                &panel_id,
                format!("{}:scrollbar_handle", panel_id.0.0),
                WidgetKind::ScrollbarHandle,
                inflated,
                Sense::DRAG,
            );
            coord.register_child(
                &panel_id,
                format!("{}:scrollbar_track", panel_id.0.0),
                WidgetKind::ScrollbarTrack,
                layout.scrollbar,
                Sense::CLICK,
            );
        }
    }

    // --- Edge resize handles -------------------------------------------------
    // Each enabled side gets a thin `Sense::DRAG` rect on the panel's outer
    // edge.  The handles are the panel's own resize affordance — independent
    // of any visual border stroke (`PanelStyle::borders()`).  The composite
    // does not move the panel itself; it dispatches drag events through
    // `EventBuilder::ResizeHandle` and lets the layout owner update the
    // panel rect (or, for free-floating panels, the panel's own rect).
    {
        let style       = settings.style.as_ref();
        let handles     = style.edge_handles();
        let handle_w    = style.edge_handle_width();
        let half        = handle_w / 2.0;
        let f           = layout.frame;

        let mut emit = |suffix: &str, r: Rect| {
            if r.width > 0.0 && r.height > 0.0 {
                coord.register_child(
                    &panel_id,
                    format!("{}:{}", panel_id.0.0, suffix),
                    WidgetKind::Separator,
                    r,
                    Sense::DRAG | Sense::HOVER,
                );
            }
        };

        if handles.top {
            emit("edge_top",
                 Rect::new(f.x, f.y - half, f.width, handle_w));
        }
        if handles.bottom {
            emit("edge_bottom",
                 Rect::new(f.x, f.y + f.height - half, f.width, handle_w));
        }
        if handles.left {
            emit("edge_left",
                 Rect::new(f.x - half, f.y, handle_w, f.height));
        }
        if handles.right {
            emit("edge_right",
                 Rect::new(f.x + f.width - half, f.y, handle_w, f.height));
        }
    }

    panel_id
}

// ---------------------------------------------------------------------------
// Public API — convenience wrapper (ContextManager)
// ---------------------------------------------------------------------------

/// Register + draw a panel in one call using a `ContextManager`.
///
/// Returns the [`CompositeId`] assigned to the panel composite.
pub fn register_context_manager_panel(
    ctx_mgr:  &mut crate::app_context::ContextManager,
    render:   &mut dyn RenderContext,
    id:       impl Into<WidgetId>,
    rect:     Rect,
    state:    &mut PanelState,
    view:     &mut PanelView<'_>,
    settings: &PanelSettings,
    kind:     &PanelRenderKind,
    layer:    &LayerId,
) -> CompositeId {
    let coord = &mut ctx_mgr.input;
    let panel_id =
        register_input_coordinator_panel(coord, id, rect, state, view, settings, kind, layer);
    draw_panel_with_coord(render, rect, coord, &panel_id, state, view, settings, kind);
    panel_id
}

// ---------------------------------------------------------------------------
// Internal draw pipeline
// ---------------------------------------------------------------------------

fn draw_panel_with_coord(
    ctx:      &mut dyn RenderContext,
    rect:     Rect,
    coord:    &mut InputCoordinator,
    panel_id: &CompositeId,
    state:    &mut PanelState,
    view:     &mut PanelView<'_>,
    settings: &PanelSettings,
    kind:     &PanelRenderKind,
) {
    if let PanelRenderKind::Custom(f) = kind {
        f(ctx, rect, view, settings);
        return;
    }

    let theme  = settings.theme.as_ref();
    let style  = settings.style.as_ref();
    let layout = compute_layout(rect, view, settings, kind);

    // --- 1. Background -------------------------------------------------------
    match style.background_fill() {
        BackgroundFill::Solid => {
            ctx.set_fill_color(theme.bg());
            ctx.fill_rect(layout.frame.x, layout.frame.y, layout.frame.width, layout.frame.height);
        }
        BackgroundFill::Glass { blur_radius: _ } => {
            ctx.draw_blur_background(layout.frame.x, layout.frame.y, layout.frame.width, layout.frame.height);
            ctx.set_fill_color(theme.bg());
            ctx.fill_rect(layout.frame.x, layout.frame.y, layout.frame.width, layout.frame.height);
        }
    }

    // --- 1b. Frame borders ---------------------------------------------------
    // Optional per-side strokes.  Default `BorderConfig::none()` → no draws.
    {
        let borders = style.borders();
        let f       = layout.frame;
        let theme_border = theme.border();
        let mut stroke = |x: f64, y: f64, w: f64, h: f64, s: super::style::BorderStroke| {
            if w <= 0.0 || h <= 0.0 || s.width <= 0.0 || s.opacity <= 0.0 {
                return;
            }
            ctx.save();
            ctx.set_global_alpha(s.opacity);
            ctx.set_fill_color(theme_border);
            ctx.fill_rect(x, y, w, h);
            ctx.restore();
        };
        if let Some(s) = borders.top    { stroke(f.x, f.y,                       f.width, s.width, s); }
        if let Some(s) = borders.bottom { stroke(f.x, f.y + f.height - s.width,  f.width, s.width, s); }
        if let Some(s) = borders.left   { stroke(f.x, f.y, s.width, f.height, s); }
        if let Some(s) = borders.right  { stroke(f.x + f.width - s.width, f.y, s.width, f.height, s); }
    }

    // --- 2. Header strip -----------------------------------------------------
    let has_header = matches!(
        kind,
        PanelRenderKind::WithHeader
            | PanelRenderKind::WithHeaderColumns
            | PanelRenderKind::WithFooter
            | PanelRenderKind::WithHeaderColumnsFooter
    );

    if has_header && layout.header.height > 0.0 {
        ctx.set_fill_color(theme.header_bg());
        ctx.fill_rect(layout.header.x, layout.header.y, layout.header.width, layout.header.height);

        if let Some(hdr) = &view.header {
            let pad = style.padding();

            // Title
            ctx.set_fill_color(theme.header_text());
            ctx.set_font("11px sans-serif");
            ctx.set_text_align(TextAlign::Left);
            ctx.set_text_baseline(TextBaseline::Middle);
            ctx.fill_text(
                hdr.title,
                layout.header.x + pad,
                layout.header.y + layout.header.height / 2.0,
            );

            // Action buttons (right-to-left)
            let btn_size  = 20.0_f64;
            let btn_gap   = 4.0_f64;
            let pad_right = 6.0_f64;
            for (i, action) in hdr.actions.iter().enumerate() {
                let btn_x = layout.header.x + layout.header.width
                    - pad_right
                    - btn_size * (i + 1) as f64
                    - btn_gap * i as f64;
                let btn_y = layout.header.y + (layout.header.height - btn_size) / 2.0;

                let is_hovered = state.hovered_action.as_deref() == Some(action.id)
                    || action.hovered;
                if is_hovered {
                    ctx.set_fill_color("rgba(255,255,255,0.08)");
                    ctx.fill_rounded_rect(btn_x, btn_y, btn_size, btn_size, 3.0);
                }

                let icon_color = if is_hovered {
                    theme.action_icon_hover()
                } else {
                    theme.action_icon_normal()
                };
                ctx.set_fill_color(icon_color);
                // Icon draw point reserved — actual SVG render by caller.
                let _ = (btn_x, btn_y);
            }
        }

        // Header bottom divider
        ctx.set_fill_color(theme.divider());
        ctx.fill_rect(
            layout.header.x,
            layout.header.y + layout.header.height - 1.0,
            layout.header.width,
            1.0,
        );
    }

    // --- 3. Column-header row ------------------------------------------------
    let has_col_header = matches!(
        kind,
        PanelRenderKind::WithHeaderColumns | PanelRenderKind::WithHeaderColumnsFooter
    );

    if has_col_header && layout.col_header.height > 0.0 {
        ctx.set_fill_color(theme.column_header_bg());
        ctx.fill_rect(
            layout.col_header.x,
            layout.col_header.y,
            layout.col_header.width,
            layout.col_header.height,
        );

        let available_w = layout.col_header.width;
        let mut cursor_x = layout.col_header.x;

        for col in view.columns {
            let col_w    = available_w * col.width;
            let label_x  = cursor_x + style.padding();
            let label_y  = layout.col_header.y + layout.col_header.height / 2.0;

            let is_sort_col = state.sort_column.as_deref() == Some(col.id);
            let is_hovered  = state.hovered_column.as_deref() == Some(col.id);

            let label_color = if is_hovered {
                theme.header_text()
            } else {
                theme.column_header_text()
            };

            ctx.set_fill_color(label_color);
            ctx.set_font("10px sans-serif");
            ctx.set_text_align(TextAlign::Left);
            ctx.set_text_baseline(TextBaseline::Middle);
            ctx.fill_text(col.label, label_x, label_y);

            // Sort arrow (small caret after label)
            if is_sort_col {
                draw_sort_arrow(ctx, cursor_x + col_w - 12.0, label_y, state.sort_ascending, theme.sort_arrow_color());
            }

            cursor_x += col_w;
        }

        // Vertical separator lines between columns (drawn over body too)
        let mut sep_x = layout.col_header.x;
        let body_bottom = layout.body.y + layout.body.height;
        for (i, col) in view.columns.iter().enumerate() {
            sep_x += available_w * col.width;
            if i + 1 < view.columns.len() {
                ctx.set_fill_color(theme.divider());
                ctx.fill_rect(sep_x - 0.5, layout.col_header.y, 1.0, body_bottom - layout.col_header.y);
            }
        }

        // Column-header bottom divider
        ctx.set_fill_color(theme.divider());
        ctx.fill_rect(
            layout.col_header.x,
            layout.col_header.y + layout.col_header.height - 1.0,
            layout.col_header.width,
            1.0,
        );
    }

    // --- 4. (body drawn by caller after composite call) ----------------------

    // --- 5. Footer -----------------------------------------------------------
    let has_footer = matches!(
        kind,
        PanelRenderKind::WithFooter | PanelRenderKind::WithHeaderColumnsFooter
    );

    if has_footer && layout.footer.height > 0.0 {
        // Footer top divider
        ctx.set_fill_color(theme.divider());
        ctx.fill_rect(
            layout.footer.x,
            layout.footer.y,
            layout.footer.width,
            1.0,
        );

        // Footer background
        ctx.set_fill_color(theme.footer_bg());
        ctx.fill_rect(
            layout.footer.x,
            layout.footer.y + 1.0,
            layout.footer.width,
            layout.footer.height - 1.0,
        );
        // (footer drawn by caller after composite call)
    }

    // --- 6. Scrollbar --------------------------------------------------------
    if view.show_scrollbar && layout.scrollbar.width > 0.0 {
        let scb_state = if state.scroll.is_dragging {
            ScrollbarVisualState::Dragging
        } else {
            ScrollbarVisualState::Active
        };
        draw_scrollbar_standard(
            ctx,
            layout.scrollbar,
            view.content_height,
            layout.body.height,
            state.scroll.offset,
            scb_state,
            None,
        );
    }

    // --- 7. Body overflow guard — exactly one of Chevrons / Scrollbar /
    //         Compress is active. Scrollbar already painted via the legacy
    //         show_scrollbar branch (step 6); Compress applied factor in
    //         input registration. Chevrons paint here, with Clip falling
    //         back to Chevrons only when content actually overflows.
    {
        let scroll = crate::ui::widgets::composite::overflow::BodyScrollState {
            offset_x:  0.0,
            offset_y:  state.scroll.offset,
            content_w: view.content_width,
            content_h: view.content_height,
        };
        let overflowing = scroll.overflows(layout.body.width, layout.body.height).any();
        let want_chevrons = match view.overflow {
            crate::types::OverflowMode::Chevrons             => true,
            crate::types::OverflowMode::Clip if overflowing  => true,
            _ => false,
        };
        if want_chevrons {
            crate::ui::widgets::composite::overflow::draw_chevrons_helper(
                ctx, layout.body, &scroll, theme.bg(), theme.bg(),
            );
        }
    }

    // --- 8. Edge resize handles (visual highlight on hover / drag) ---------
    // The hit zones themselves are registered in
    // `register_input_coordinator_panel`; here we draw a highlight strip
    // on top of the panel's edge **only while the matching child is
    // hovered or pressed**.  The strip uses an accent-leaning colour so
    // it stands out against the panel border at rest.
    {
        let handles = style.edge_handles();
        if handles.top || handles.bottom || handles.left || handles.right {
            let f       = layout.frame;
            let strip_t = 3.0_f64; // visible thickness when hovered / pressed
            // Pick a foreground-ish colour: theme.divider() is too quiet,
            // theme.border() blends with panel chrome; reuse the column
            // header text colour as a high-contrast accent that already
            // lives in the PanelTheme contract.
            let active_color = theme.column_header_text();

            let mut maybe_strip = |suffix: &str, on: bool, x: f64, y: f64, w: f64, h: f64| {
                if !on { return; }
                let id = WidgetId::new(format!("{}:{}", panel_id.0.0, suffix));
                let st = coord.widget_state(&id);
                if !(st.is_hovered() || st.is_pressed()) { return; }
                ctx.set_fill_color(active_color);
                ctx.fill_rect(x, y, w, h);
            };

            // Top strip — sits on the inside of the top edge.
            maybe_strip("edge_top", handles.top,
                f.x, f.y, f.width, strip_t);
            // Bottom strip — inside of bottom edge.
            maybe_strip("edge_bottom", handles.bottom,
                f.x, f.y + f.height - strip_t, f.width, strip_t);
            // Left strip — inside of left edge.
            maybe_strip("edge_left", handles.left,
                f.x, f.y, strip_t, f.height);
            // Right strip — inside of right edge.
            maybe_strip("edge_right", handles.right,
                f.x + f.width - strip_t, f.y, strip_t, f.height);
        }
    }
}

// ---------------------------------------------------------------------------
// Sort arrow helper
// ---------------------------------------------------------------------------

fn draw_sort_arrow(ctx: &mut dyn RenderContext, x: f64, y: f64, ascending: bool, color: &str) {
    // Draw a small upward (ascending) or downward (descending) caret (4×4 px).
    ctx.set_fill_color(color);
    if ascending {
        // Upward triangle: top point at (x+2, y-3), base at (x, y+1) and (x+4, y+1).
        ctx.fill_rect(x + 1.0, y - 2.0, 2.0, 1.0);
        ctx.fill_rect(x,       y - 1.0, 4.0, 1.0);
        ctx.fill_rect(x,       y,       4.0, 1.0);
    } else {
        // Downward triangle.
        ctx.fill_rect(x,       y - 1.0, 4.0, 1.0);
        ctx.fill_rect(x,       y,       4.0, 1.0);
        ctx.fill_rect(x + 1.0, y + 1.0, 2.0, 1.0);
    }
}

// ---------------------------------------------------------------------------
// Layout computation
// ---------------------------------------------------------------------------

fn compute_layout(
    rect:     Rect,
    view:     &PanelView<'_>,
    settings: &PanelSettings,
    kind:     &PanelRenderKind,
) -> PanelLayout {
    let style = settings.style.as_ref();

    let has_header = matches!(
        kind,
        PanelRenderKind::WithHeader
            | PanelRenderKind::WithHeaderColumns
            | PanelRenderKind::WithFooter
            | PanelRenderKind::WithHeaderColumnsFooter
    );
    let has_col_header = matches!(
        kind,
        PanelRenderKind::WithHeaderColumns | PanelRenderKind::WithHeaderColumnsFooter
    );
    let has_footer = matches!(
        kind,
        PanelRenderKind::WithFooter | PanelRenderKind::WithHeaderColumnsFooter
    );

    let header_h     = if has_header     { style.header_height()        } else { 0.0 };
    let col_header_h = if has_col_header { style.column_header_height() } else { 0.0 };
    let footer_h     = if has_footer { style.footer_height() } else { 0.0 };
    let scrollbar_w  = if view.show_scrollbar { style.scrollbar_width() } else { 0.0 };

    let frame = rect;

    let header = Rect::new(frame.x, frame.y, frame.width, header_h);

    let col_header = if col_header_h > 0.0 {
        Rect::new(frame.x, frame.y + header_h, frame.width, col_header_h)
    } else {
        Rect::default()
    };

    let body_y = frame.y + header_h + col_header_h;
    let body_h = (frame.height - header_h - col_header_h - footer_h).max(0.0);
    let body_w = frame.width - scrollbar_w;
    let body   = Rect::new(frame.x, body_y, body_w, body_h);

    let scrollbar = if scrollbar_w > 0.0 {
        Rect::new(
            frame.x + frame.width - scrollbar_w,
            body_y,
            scrollbar_w,
            body_h,
        )
    } else {
        Rect::default()
    };

    let footer = if footer_h > 0.0 {
        Rect::new(
            frame.x,
            frame.y + frame.height - footer_h,
            frame.width,
            footer_h,
        )
    } else {
        Rect::default()
    };

    PanelLayout {
        frame,
        header,
        col_header,
        body,
        footer,
        scrollbar,
    }
}