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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Chrome render entry point and 16-step draw pipeline.
//!
//! # API
//!
//! - `register_input_coordinator_chrome` — registers the composite + all child
//!   hit-rects with an `InputCoordinator`.  **No drawing.**
//! - `register_context_manager_chrome`   — convenience wrapper: registers and
//!   draws in one call via a `ContextManager`.
//!
//! # Draw order (non-Custom kinds)
//!
//! 1.  Background strip
//! 2.  Tab bodies (hover/active accent 2 px bottom line + label)
//! 3.  Tab close-X icons
//! 4.  New-tab "+" button
//! 5.  New-window icon button
//! 6.  Menu / gear icon button
//! 7.  Group divider (left of min/max/close)
//! 8.  Close-window icon button
//! 9.  Group divider (between close-window and minimize group)
//! 10. Minimize button
//! 11. Maximize / restore button
//! 12. Close-app button (red hover BG)
//! 13. Active tab bottom accent indicator
//! 14. Bottom separator line
//! 15. Context menu (if open)
//! 16. Tooltip overlay (if visible)

use crate::app_context::ContextManager;
use crate::input::core::coordinator::LayerId;
use crate::input::{InputCoordinator, Sense, WidgetKind};
use crate::core::render::draw_svg_icon;
use crate::render::{RenderContext, TextAlign, TextBaseline};
use crate::ui::assets::icons::ui::{ICON_CLOSE, ICON_NEW_WINDOW};
use crate::types::{Rect, WidgetId, CompositeId};

use super::settings::ChromeSettings;
use super::state::ChromeState;
use super::types::{ChromeRenderKind, ChromeTabConfig, ChromeView};

// ---------------------------------------------------------------------------
// Layout constants (mirrors chrome-deep.md §2)
// ---------------------------------------------------------------------------

const TAB_LEFT_MARGIN: f64 = 0.0;
const NEW_TAB_BTN_WIDTH: f64 = 28.0;
const BUTTON_WIDTH: f64 = 46.0;
const CLOSE_WINDOW_BTN_WIDTH: f64 = 36.0;
const MENU_BTN_WIDTH: f64 = 36.0;
const NEW_WINDOW_BTN_WIDTH: f64 = 36.0;

// ---------------------------------------------------------------------------
// ButtonPositions helper
// ---------------------------------------------------------------------------

struct ButtonPositions {
    close_x: f64,
    maximize_x: f64,
    minimize_x: f64,
    /// Pre-divider button column starts here (rightmost of the optional
    /// button group: new_window / menu / close_window).  `None` means no
    /// optional button is enabled and there is no left-group divider.
    group_right: Option<f64>,
    /// Compact left edges, `None` when the corresponding button is disabled.
    close_window_left: Option<f64>,
    menu_left:         Option<f64>,
    new_window_left:   Option<f64>,
}

impl ButtonPositions {
    /// Compute compact positions: each optional button reserves its column
    /// only when enabled.  Disabled buttons leave no gap — the next-left
    /// button slides right against the previous.
    fn compute(width: f64, view: &super::types::ChromeView<'_>) -> Self {
        let close_x    = width - BUTTON_WIDTH;
        let maximize_x = width - BUTTON_WIDTH * 2.0;
        let minimize_x = width - BUTTON_WIDTH * 3.0;

        // Walk right-to-left through the optional group, pushing each
        // enabled button against the previous one.
        let mut cursor = minimize_x;          // right edge of the group
        let mut close_window_left: Option<f64> = None;
        let mut menu_left:         Option<f64> = None;
        let mut new_window_left:   Option<f64> = None;

        // Pair rule: enabling new_window pulls in close_window so users
        // always have a way to close the spawned window even if they only
        // flipped one flag.
        let effective_close_window =
            view.show_close_window_btn || view.show_new_window_btn;
        if effective_close_window {
            cursor -= CLOSE_WINDOW_BTN_WIDTH;
            close_window_left = Some(cursor);
        }
        if view.show_menu_btn {
            cursor -= MENU_BTN_WIDTH;
            menu_left = Some(cursor);
        }
        if view.show_new_window_btn {
            cursor -= NEW_WINDOW_BTN_WIDTH;
            new_window_left = Some(cursor);
        }
        let any_enabled = close_window_left.is_some()
            || menu_left.is_some()
            || new_window_left.is_some();
        let group_right = if any_enabled { Some(minimize_x) } else { None };

        Self {
            close_x,
            maximize_x,
            minimize_x,
            group_right,
            close_window_left,
            menu_left,
            new_window_left,
        }
    }
}

// ---------------------------------------------------------------------------
// Public API — InputCoordinator
// ---------------------------------------------------------------------------

/// Register the Chrome composite and all child hit-rects with the coordinator.
///
/// **No drawing happens here.**
///
/// Returns the [`CompositeId`] assigned to the composite.
pub fn register_input_coordinator_chrome(
    coord:    &mut InputCoordinator,
    id:       impl Into<WidgetId>,
    rect:     Rect,
    state:    &ChromeState,
    view:     &ChromeView<'_>,
    settings: &ChromeSettings,
    kind:     &ChromeRenderKind,
    layer:    &LayerId,
) -> CompositeId {
    let chrome_id = coord.register_composite(
        id,
        WidgetKind::Chrome,
        rect,
        Sense::NONE,
        layer,
    );

    if matches!(kind, ChromeRenderKind::Custom(_)) {
        return chrome_id;
    }

    let style = settings.style.as_ref();
    let bp    = ButtonPositions::compute(rect.width, view);
    let h     = style.chrome_height();

    // --- Tabs ---
    let show_tabs = !matches!(kind, ChromeRenderKind::WindowControlsOnly);
    if show_tabs {
        let uniform_w = uniform_tab_width(view.tabs, style.tab_padding_h(), style.tab_close_size());
        let mut x = rect.x + TAB_LEFT_MARGIN;
        for (i, tab) in view.tabs.iter().enumerate() {
            let cached = tab_width(tab, state, i, style.tab_padding_h(), style.tab_close_size());
            let tab_w = if cached > 0.0 { cached } else { uniform_w };
            let tab_rect = Rect::new(x, rect.y, tab_w, h);

            // Tab body
            coord.register_child(
                &chrome_id,
                format!("{}:tab:{}", chrome_id.0.0, i),
                WidgetKind::Button,
                tab_rect,
                Sense::CLICK | Sense::HOVER,
            );

            // Tab close-X
            if tab.closable {
                let close_w = style.tab_close_size();
                let close_x = x + tab_w - close_w - style.tab_padding_h() / 2.0;
                let close_y = rect.y + (h - close_w) / 2.0;
                coord.register_child(
                    &chrome_id,
                    format!("{}:tab_close:{}", chrome_id.0.0, i),
                    WidgetKind::Button,
                    Rect::new(close_x, close_y, close_w, close_w),
                    Sense::CLICK | Sense::HOVER,
                );
            }

            x += tab_w + style.tab_gap();
        }

        // New-tab "+" button
        if view.show_new_tab_btn {
            coord.register_child(
                &chrome_id,
                format!("{}:new_tab", chrome_id.0.0),
                WidgetKind::Button,
                Rect::new(x, rect.y, NEW_TAB_BTN_WIDTH, h),
                Sense::CLICK | Sense::HOVER,
            );
            x += NEW_TAB_BTN_WIDTH;
        }

        // Caption / drag zone — extends up to the leftmost enabled
        // optional button (or to Min when none are enabled).
        let group_left = bp.new_window_left
            .or(bp.menu_left)
            .or(bp.close_window_left)
            .unwrap_or(bp.minimize_x);
        let drag_right = rect.x + group_left;
        let drag_w = (drag_right - x).max(0.0);
        if drag_w > 0.0 {
            coord.register_child(
                &chrome_id,
                format!("{}:drag", chrome_id.0.0),
                WidgetKind::DragHandle,
                Rect::new(x, rect.y, drag_w, h),
                Sense::DRAG,
            );
        }
    } else {
        // WindowControlsOnly: drag zone fills the full width except button column
        let drag_end = rect.x + bp.minimize_x;
        let drag_w   = drag_end - rect.x;
        if drag_w > 0.0 {
            coord.register_child(
                &chrome_id,
                format!("{}:drag", chrome_id.0.0),
                WidgetKind::DragHandle,
                Rect::new(rect.x, rect.y, drag_w, h),
                Sense::DRAG,
            );
        }
    }

    // --- Action buttons (right side) ---
    let show_window_controls = !matches!(kind, ChromeRenderKind::Minimal);

    if show_window_controls {
        let optional_visible = !matches!(kind, ChromeRenderKind::WindowControlsOnly);

        // New-window button
        if optional_visible {
            if let Some(left) = bp.new_window_left {
                coord.register_child(
                    &chrome_id,
                    format!("{}:new_win", chrome_id.0.0),
                    WidgetKind::Button,
                    Rect::new(rect.x + left, rect.y, NEW_WINDOW_BTN_WIDTH, h),
                    Sense::CLICK | Sense::HOVER,
                );
            }
            if let Some(left) = bp.menu_left {
                coord.register_child(
                    &chrome_id,
                    format!("{}:menu", chrome_id.0.0),
                    WidgetKind::Button,
                    Rect::new(rect.x + left, rect.y, MENU_BTN_WIDTH, h),
                    Sense::CLICK | Sense::HOVER,
                );
            }
            if let Some(left) = bp.close_window_left {
                coord.register_child(
                    &chrome_id,
                    format!("{}:close_win", chrome_id.0.0),
                    WidgetKind::Button,
                    Rect::new(rect.x + left, rect.y, CLOSE_WINDOW_BTN_WIDTH, h),
                    Sense::CLICK | Sense::HOVER,
                );
            }
        }

        // Minimize
        coord.register_child(
            &chrome_id,
            format!("{}:min", chrome_id.0.0),
            WidgetKind::Button,
            Rect::new(rect.x + bp.minimize_x, rect.y, BUTTON_WIDTH, h),
            Sense::CLICK | Sense::HOVER,
        );

        // Maximize / restore
        coord.register_child(
            &chrome_id,
            format!("{}:max", chrome_id.0.0),
            WidgetKind::Button,
            Rect::new(rect.x + bp.maximize_x, rect.y, BUTTON_WIDTH, h),
            Sense::CLICK | Sense::HOVER,
        );

        // Close app
        coord.register_child(
            &chrome_id,
            format!("{}:close", chrome_id.0.0),
            WidgetKind::Button,
            Rect::new(rect.x + bp.close_x, rect.y, BUTTON_WIDTH, h),
            Sense::CLICK | Sense::HOVER,
        );
    }

    chrome_id
}

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

/// Register + draw the Chrome composite in one call using a `ContextManager`.
///
/// Returns the [`CompositeId`] assigned to the composite.
pub fn register_context_manager_chrome(
    ctx_mgr:  &mut ContextManager,
    render:   &mut dyn RenderContext,
    id:       impl Into<WidgetId>,
    rect:     Rect,
    state:    &mut ChromeState,
    view:     &ChromeView<'_>,
    settings: &ChromeSettings,
    kind:     &ChromeRenderKind,
    layer:    &LayerId,
) -> CompositeId {
    let coord = &mut ctx_mgr.input;
    let chrome_id =
        register_input_coordinator_chrome(coord, id, rect, state, view, settings, kind, layer);
    draw_chrome(render, rect, state, view, settings, kind);
    chrome_id
}

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

/// Pure paint — `uzor::l0::chrome::draw_chrome`.
///
/// Renders the entire chrome strip into `ctx` based on the given
/// state + view + settings.  Self-contained: no L1 / L2 / L3 / WM
/// dependency.  Promoted from a private `draw_chrome_internal` so
/// embedders can drive their own input pipeline without touching
/// `LayoutManager` or `InputCoordinator`.
pub fn draw_chrome(
    ctx:      &mut dyn RenderContext,
    rect:     Rect,
    state:    &ChromeState,
    view:     &ChromeView<'_>,
    settings: &ChromeSettings,
    kind:     &ChromeRenderKind,
) {
    match kind {
        ChromeRenderKind::Custom(f) => {
            f(ctx, rect, view, settings);
            return;
        }
        _ => {}
    }

    let theme = settings.theme.as_ref();
    let style = settings.style.as_ref();
    let h     = style.chrome_height();
    let w     = rect.width;
    let bp    = ButtonPositions::compute(w, view);

    // --- 1. Background strip ---
    ctx.set_fill_color(theme.background());
    ctx.fill_rect(rect.x, rect.y, w, h);

    let show_tabs     = !matches!(kind, ChromeRenderKind::WindowControlsOnly);
    let show_controls = !matches!(kind, ChromeRenderKind::Minimal);

    // --- 2–3. Tab bodies + close-X icons ---
    if show_tabs {
        let uniform_w = uniform_tab_width(view.tabs, style.tab_padding_h(), style.tab_close_size());
        let mut x = rect.x + TAB_LEFT_MARGIN;
        for (i, tab) in view.tabs.iter().enumerate() {
            let cached = tab_width(tab, state, i, style.tab_padding_h(), style.tab_close_size());
            let tw = if cached > 0.0 { cached } else { uniform_w };
            let tab_rect = Rect::new(x, rect.y, tw, h);

            let ts = state.tabs_state.get(i);
            let hovered      = ts.map(|s| s.hovered).unwrap_or(false);
            let close_hovered = ts.map(|s| s.close_hovered).unwrap_or(false);
            let active = view.active_tab_id.map(|id| id == tab.id).unwrap_or(false);

            // Tab background
            let bg_color = if active {
                theme.tab_bg_active()
            } else if hovered || close_hovered {
                theme.tab_bg_hover()
            } else {
                theme.tab_bg_normal()
            };
            if bg_color != "transparent" {
                ctx.set_fill_color(bg_color);
                ctx.fill_rect(tab_rect.x, tab_rect.y, tab_rect.width, tab_rect.height);
            }

            // Label text
            let text_color = if active {
                theme.tab_text_active()
            } else if hovered {
                theme.tab_text_hover()
            } else {
                theme.tab_text_normal()
            };
            ctx.set_fill_color(text_color);
            ctx.set_font("12px sans-serif");
            ctx.set_text_align(TextAlign::Left);
            ctx.set_text_baseline(TextBaseline::Middle);
            ctx.fill_text(
                tab.label,
                tab_rect.x + style.tab_padding_h(),
                tab_rect.y + h / 2.0,
            );

            // Tab close-X icon (step 3)
            if tab.closable {
                let icon_sz  = style.tab_close_icon_size();
                let close_bw = style.tab_close_size();
                let cx = x + tw - close_bw + (close_bw - icon_sz) / 2.0;
                let cy = rect.y + (h - icon_sz) / 2.0;
                let icon_color = if close_hovered {
                    theme.close_hover()
                } else {
                    theme.icon_normal()
                };
                draw_cross(ctx, cx, cy, icon_sz, icon_color, 1.0);
            }

            x += tw + style.tab_gap();
        }

        // --- 4. New-tab "+" button ---
        if view.show_new_tab_btn {
            let nt_x = rect.x
                + TAB_LEFT_MARGIN
                + tab_total_width(view.tabs, state, style.tab_padding_h(),
                                   style.tab_close_size(), style.tab_gap());
            // 1 px separator before "+"
            ctx.set_fill_color(theme.separator());
            ctx.fill_rect(nt_x, rect.y + 4.0, 1.0, h - 8.0);
            // Cross strokes
            let cx = nt_x + NEW_TAB_BTN_WIDTH / 2.0;
            let cy = rect.y + h / 2.0;
            let arm = 5.0_f64;
            ctx.set_stroke_color(theme.icon_normal());
            ctx.set_stroke_width(1.5);
            ctx.set_line_dash(&[]);
            // horizontal
            ctx.move_to(cx - arm, cy);
            ctx.line_to(cx + arm, cy);
            ctx.stroke();
            // vertical
            ctx.move_to(cx, cy - arm);
            ctx.line_to(cx, cy + arm);
            ctx.stroke();
        }
    }

    // --- Right-side action buttons ---
    if show_controls {
        use super::types::ChromeHit;
        let icon_sz = style.action_icon_size();
        let hover_bg     = theme.tab_bg_hover();
        let icon_normal  = theme.icon_normal();
        let icon_hover   = theme.tab_text_hover();

        // --- 5. New-window icon (uzor SVG ICON_NEW_WINDOW) ---
        if show_tabs {
            if let Some(left) = bp.new_window_left {
                let bx = rect.x + left;
                let by = rect.y;
                let hovered = state.hovered == ChromeHit::NewWindowBtn;
                if hovered {
                    ctx.set_fill_color(hover_bg);
                    ctx.fill_rect(bx, by, NEW_WINDOW_BTN_WIDTH, h);
                }
                let color = if hovered { icon_hover } else { icon_normal };
                let s = icon_sz + 2.0;
                let ix = bx + (NEW_WINDOW_BTN_WIDTH - s) / 2.0;
                let iy = by + (h - s) / 2.0;
                draw_svg_icon(ctx, ICON_NEW_WINDOW, ix, iy, s, s, color);
            }
        }

        // --- 6. Menu icon ---
        if show_tabs {
            if let Some(left) = bp.menu_left {
                let menu_cx = rect.x + left + MENU_BTN_WIDTH / 2.0;
                let menu_cy = rect.y + h / 2.0;
                let line_w  = icon_sz;
                ctx.set_fill_color(theme.icon_normal());
                for i in 0_i32..3_i32 {
                    let ly = menu_cy - 3.0 + i as f64 * 3.0;
                    ctx.fill_rect(menu_cx - line_w / 2.0, ly - 0.75, line_w, 1.5);
                }
            }
        }

        // --- 7. Divider between optional group and min/max/close ---
        if bp.group_right.is_some() {
            ctx.set_fill_color(theme.separator());
            ctx.fill_rect(rect.x + bp.minimize_x - 1.0, rect.y + 6.0, 1.0, h - 12.0);
        }

        // --- 8. Close-window icon (uzor SVG ICON_CLOSE) ---
        if show_tabs {
            if let Some(left) = bp.close_window_left {
                let bx = rect.x + left;
                let by = rect.y;
                let hovered = state.hovered == ChromeHit::CloseWindowBtn;
                if hovered {
                    ctx.set_fill_color(hover_bg);
                    ctx.fill_rect(bx, by, CLOSE_WINDOW_BTN_WIDTH, h);
                }
                let color = if hovered { icon_hover } else { icon_normal };
                let s = icon_sz;
                let ix = bx + (CLOSE_WINDOW_BTN_WIDTH - s) / 2.0;
                let iy = by + (h - s) / 2.0;
                draw_svg_icon(ctx, ICON_CLOSE, ix, iy, s, s, color);
            }
        }

        // --- 10. Minimize icon (10×1 filled rect) ---
        {
            let btn_rect = Rect::new(rect.x + bp.minimize_x, rect.y, BUTTON_WIDTH, h);
            if state.hovered == super::types::ChromeHit::MinBtn {
                ctx.set_fill_color(theme.button_hover());
                ctx.fill_rect(btn_rect.x, btn_rect.y, btn_rect.width, btn_rect.height);
            }
            let mid_x = rect.x + bp.minimize_x + BUTTON_WIDTH / 2.0;
            let mid_y = rect.y + h / 2.0;
            ctx.set_fill_color(theme.icon_normal());
            ctx.fill_rect(mid_x - 5.0, mid_y - 0.5, 10.0, 1.0);
        }

        // --- 11. Maximize / restore icon ---
        {
            let btn_rect = Rect::new(rect.x + bp.maximize_x, rect.y, BUTTON_WIDTH, h);
            if state.hovered == super::types::ChromeHit::MaxBtn {
                ctx.set_fill_color(theme.button_hover());
                ctx.fill_rect(btn_rect.x, btn_rect.y, btn_rect.width, btn_rect.height);
            }
            let mid_x = rect.x + bp.maximize_x + BUTTON_WIDTH / 2.0;
            let mid_y = rect.y + h / 2.0;
            ctx.set_stroke_color(theme.icon_normal());
            ctx.set_stroke_width(1.0);
            ctx.set_line_dash(&[]);
            if view.is_maximized {
                // Restore: two overlapping rects
                ctx.stroke_rect(mid_x - 3.0, mid_y - 5.0, 8.0, 8.0);
                ctx.stroke_rect(mid_x - 5.0, mid_y - 3.0, 8.0, 8.0);
            } else {
                ctx.stroke_rect(mid_x - 5.0, mid_y - 5.0, 10.0, 10.0);
            }
        }

        // --- 12. Close-app button (hover = red BG) ---
        {
            let close_rect = Rect::new(rect.x + bp.close_x, rect.y, BUTTON_WIDTH, h);
            // Hover background
            if state.hovered == super::types::ChromeHit::CloseBtn {
                ctx.set_fill_color(theme.close_hover());
                ctx.fill_rect(close_rect.x, close_rect.y, close_rect.width, close_rect.height);
            }
            let cx  = rect.x + bp.close_x + BUTTON_WIDTH / 2.0;
            let cy  = rect.y + h / 2.0;
            let arm = 5.0_f64;
            draw_cross(ctx, cx - arm, cy - arm, arm * 2.0, theme.icon_normal(), 1.5);
        }
    }

    // --- 13. Active tab bottom accent indicator ---
    if show_tabs {
        let uniform_w = uniform_tab_width(view.tabs, style.tab_padding_h(), style.tab_close_size());
        let mut x = rect.x + TAB_LEFT_MARGIN;
        for (i, tab) in view.tabs.iter().enumerate() {
            let cached = tab_width(tab, state, i, style.tab_padding_h(), style.tab_close_size());
            let tw = if cached > 0.0 { cached } else { uniform_w };
            let active = view.active_tab_id.map(|id| id == tab.id).unwrap_or(false);
            let ts = state.tabs_state.get(i);
            let hovered = ts.map(|s| s.hovered).unwrap_or(false);
            if active || hovered {
                let accent_color = if active {
                    theme.tab_accent()
                } else {
                    theme.button_hover()
                };
                ctx.set_fill_color(accent_color);
                ctx.fill_rect(
                    x,
                    rect.y + h - style.tab_accent_height(),
                    tw,
                    style.tab_accent_height(),
                );
            }
            x += tw + style.tab_gap();
        }
    }

    // --- 14. Bottom separator line (controlled by style.show_bottom_border) ---
    if style.show_bottom_border() {
        ctx.set_fill_color(theme.separator());
        ctx.fill_rect(rect.x, rect.y + h - 1.0, w, 1.0);
    }

    // --- 15. Context menu (if open) ---
    // Context menu rendering is delegated to the composite::context_menu widget.
    // The chrome state holds a `ContextMenuState`; callers drive rendering
    // via the context_menu composite after this call.

    // --- 16. Tooltip overlay ---
    // Tooltip rendering is also deferred to the caller via `state.tooltip`.
}

// ---------------------------------------------------------------------------
// Internal draw helpers
// ---------------------------------------------------------------------------

/// Draw an × cross centred at `(x, y)` (top-left origin) with `size` and `stroke_w`.
fn draw_cross(
    ctx:      &mut dyn RenderContext,
    x:        f64,
    y:        f64,
    size:     f64,
    color:    &str,
    stroke_w: f64,
) {
    ctx.set_stroke_color(color);
    ctx.set_stroke_width(stroke_w);
    ctx.set_line_dash(&[]);
    ctx.begin_path();
    ctx.move_to(x, y);
    ctx.line_to(x + size, y + size);
    ctx.stroke();
    ctx.begin_path();
    ctx.move_to(x + size, y);
    ctx.line_to(x, y + size);
    ctx.stroke();
}

// ---------------------------------------------------------------------------
// Tab width helpers
// ---------------------------------------------------------------------------

/// Measure natural width of the chrome bar for the given tabs and render kind.
///
/// Width = `tab_left_margin + tab_total_width + (new_tab_btn if enabled)
///         + drag_zone_min_width + window-controls width(kind, view)`.
/// Height is always `style.chrome_height()`.
///
/// Use this when you need a content-driven chrome rect instead of stretching to
/// the full viewport width.
pub fn measure(
    view:     &ChromeView<'_>,
    state:    &ChromeState,
    settings: &ChromeSettings,
    kind:     &ChromeRenderKind,
) -> (f64, f64) {
    let style = settings.style.as_ref();

    let pad_h     = style.tab_padding_h();
    let close_sz  = style.tab_close_size();
    let gap       = style.tab_gap();
    let left_mrg  = style.tab_left_margin();

    let tabs_w   = tab_total_width(view.tabs, state, pad_h, close_sz, gap);
    let new_tab  = if view.show_new_tab_btn { style.new_tab_btn_width() } else { 0.0 };
    let drag_w   = style.drag_zone_min_width();

    // Window-controls column varies per kind.
    let controls_w: f64 = match kind {
        ChromeRenderKind::Minimal => 0.0,
        ChromeRenderKind::WindowControlsOnly | ChromeRenderKind::Default | ChromeRenderKind::Custom(_) => {
            let mut w = 0.0;
            if view.show_menu_btn         { w += style.button_size_max();   }
            if view.show_new_window_btn   { w += style.button_size_max();   }
            // min/max/close-app: a standard window controls trio (3 × button_size_min).
            w += style.button_size_min() * 3.0;
            if view.show_close_window_btn || view.show_new_window_btn {
                w += style.button_size_close();
            }
            w
        }
    };

    let total_w = left_mrg + tabs_w + new_tab + drag_w + controls_w;
    let total_h = style.chrome_height();
    (total_w, total_h)
}

/// Pixel width for tab `i`, using cached `tab_widths` if available.
///
/// All tabs share a uniform width = max(label) across the tab set, so the
/// strip looks consistent (chrome-style). The cache in `ChromeState.tab_widths`
/// is honoured if populated by the caller (advanced layout overrides).
fn tab_width(
    _tab:        &ChromeTabConfig<'_>,
    state:       &ChromeState,
    i:           usize,
    _padding_h:  f64,
    _close_size: f64,
) -> f64 {
    // Cache override (caller-supplied per-tab widths).
    if let Some(&w) = state.tab_widths.get(i) {
        return w;
    }
    // Without cached widths the renderer can't know the full tab set here,
    // so fall back to a fixed sentinel — `tab_total_width` recomputes the
    // uniform width from the full slice and overrides this.
    0.0
}

/// Uniform width applied to every tab in the set: the longest label drives
/// the width so all tabs render identically.
fn uniform_tab_width(
    tabs:       &[ChromeTabConfig<'_>],
    padding_h:  f64,
    close_size: f64,
) -> f64 {
    let max_label = tabs.iter().map(|t| t.label.len()).max().unwrap_or(0) as f64;
    let text_w = max_label * 7.0;
    padding_h + text_w + close_size + padding_h
}

/// Total pixel width consumed by all tabs + gaps. Uses cached state widths
/// if every entry is populated, otherwise falls back to uniform width.
fn tab_total_width(
    tabs:       &[ChromeTabConfig<'_>],
    state:      &ChromeState,
    padding_h:  f64,
    close_size: f64,
    gap:        f64,
) -> f64 {
    if !tabs.is_empty() && state.tab_widths.len() == tabs.len() {
        // All cached — sum cached widths + gaps.
        let mut total = 0.0_f64;
        for (i, _) in tabs.iter().enumerate() {
            total += state.tab_widths[i];
            if i + 1 < tabs.len() {
                total += gap;
            }
        }
        return total;
    }
    let uw = uniform_tab_width(tabs, padding_h, close_size);
    let n = tabs.len() as f64;
    if n == 0.0 { 0.0 } else { uw * n + gap * (n - 1.0) }
}