zenthra-widgets 0.2.2

Immediate-mode UI widgets (buttons, text fields, lists) for the Zenthra UI framework
Documentation
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use crate::ui::{Ui, DrawCommand, OverlayRectDraw};
use crate::text::TextBuilder;
use zenthra_core::{Color, EdgeInsets, Id, Rect};
use zenthra_platform::event::PlatformEvent;
use zenthra_text::prelude::{TextOptions, CosmicFontProvider, Padding};
// use zenthra_text::traits::FontProvider;

pub struct TextAreaBuilder<'u, 'a, 'b> {
    ui: &'u mut Ui<'a>,
    buffer: &'b mut String,
    id: Id,
    x: f32,
    y: f32,
    font_size: f32,
    color: Color,
    bg: Option<Color>,
    text_bg: Option<Color>,
    highlight: Option<Color>,
    padding: EdgeInsets,
    text_padding: EdgeInsets,
    line_height: f32,
    width: f32,
    height: Option<f32>,
    scrollable: bool,
    overflow_hidden: bool,
    text_bg_fill_x: bool,
    fill_x: bool,
    wrap: zenthra_text::prelude::TextWrap,
    radius: [f32; 4],
    border_color: Option<Color>,
    border_width: f32,
    shadow_color: Option<Color>,
    shadow_offset: [f32; 2],
    shadow_blur: f32,
    shadow_opacity: f32,
    opacity: f32,
    render_mode: Option<zenthra_core::RenderMode>,
}

impl<'u, 'a, 'b> TextAreaBuilder<'u, 'a, 'b> {
    pub fn new(ui: &'u mut Ui<'a>, buffer: &'b mut String) -> Self {
        let id = ui.id();
        let x = ui.cursor_x;
        let y = ui.cursor_y;
        Self {
            ui,
            buffer,
            id,
            x,
            y,
            font_size: 18.0,
            color: Color::WHITE,
            bg: Some(Color::rgb(0.2, 0.2, 0.2)),
            text_bg: None,
            padding: EdgeInsets::ZERO,
            text_padding: EdgeInsets::ZERO,
            line_height: 1.2,
            width: 300.0,
            height: None,
            scrollable: false,
            overflow_hidden: false,
            text_bg_fill_x: false,
            fill_x: false,
            highlight: None,
            wrap: zenthra_text::prelude::TextWrap::Word,
            radius: [4.0; 4],
            border_color: None,
            border_width: 0.0,
            shadow_color: None,
            shadow_offset: [0.0; 2],
            shadow_blur: 0.0,
            shadow_opacity: 1.0,
            opacity: 1.0,
            render_mode: None,
        }
    }

    pub fn id(mut self, id: impl std::hash::Hash) -> Self {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        use std::hash::Hasher;
        id.hash(&mut hasher);
        self.id = Id::from_u64(hasher.finish());
        self
    }

    pub fn scrollable(mut self, enabled: bool) -> Self {
        self.scrollable = enabled;
        if enabled {
            self.overflow_hidden = true;
        }
        self
    }

    pub fn overflow_hidden(mut self, enabled: bool) -> Self {
        self.overflow_hidden = enabled;
        self
    }

    pub fn size(mut self, size: f32) -> Self {
        self.font_size = size;
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn bg(mut self, bg: Color) -> Self {
        self.bg = Some(bg);
        self
    }

    pub fn text_bg(mut self, bg: Color) -> Self {
        self.text_bg = Some(bg);
        self
    }

    pub fn highlight(mut self, color: Color) -> Self {
        self.highlight = Some(color);
        self
    }

    pub fn padding(mut self, t: f32, r: f32, b: f32, l: f32) -> Self {
        self.padding = EdgeInsets { top: t, right: r, bottom: b, left: l };
        self
    }
    pub fn padding_x(mut self, x: f32) -> Self {
        self.padding.left = x;
        self.padding.right = x;
        self
    }
    pub fn padding_y(mut self, y: f32) -> Self {
        self.padding.top = y;
        self.padding.bottom = y;
        self
    }
    pub fn padding_top(mut self, t: f32) -> Self {
        self.padding.top = t;
        self
    }
    pub fn padding_bottom(mut self, b: f32) -> Self {
        self.padding.bottom = b;
        self
    }
    pub fn padding_left(mut self, l: f32) -> Self {
        self.padding.left = l;
        self
    }
    pub fn padding_right(mut self, r: f32) -> Self {
        self.padding.right = r;
        self
    }

    pub fn text_padding(mut self, t: f32, r: f32, b: f32, l: f32) -> Self {
        self.text_padding = EdgeInsets { top: t, right: r, bottom: b, left: l };
        self
    }
    pub fn text_padding_x(mut self, x: f32) -> Self {
        self.text_padding.left = x;
        self.text_padding.right = x;
        self
    }
    pub fn text_padding_y(mut self, y: f32) -> Self {
        self.text_padding.top = y;
        self.text_padding.bottom = y;
        self
    }
    pub fn text_padding_top(mut self, t: f32) -> Self {
        self.text_padding.top = t;
        self
    }
    pub fn text_padding_bottom(mut self, b: f32) -> Self {
        self.text_padding.bottom = b;
        self
    }
    pub fn text_padding_left(mut self, l: f32) -> Self {
        self.text_padding.left = l;
        self
    }
    pub fn text_padding_right(mut self, r: f32) -> Self {
        self.text_padding.right = r;
        self
    }

    pub fn line_height(mut self, lh: f32) -> Self {
        self.line_height = lh;
        self
    }

    pub fn width(mut self, w: f32) -> Self {
        self.width = w;
        self
    }

    pub fn fill_x(mut self) -> Self {
        self.fill_x = true;
        self
    }

    pub fn radius(mut self, tl: f32, tr: f32, br: f32, bl: f32) -> Self {
        self.radius = [tl, tr, br, bl];
        self
    }

    pub fn radius_all(mut self, r: f32) -> Self {
        self.radius = [r; 4];
        self
    }

    pub fn radius_top(mut self, r: f32) -> Self {
        self.radius[0] = r;
        self.radius[1] = r;
        self
    }

    pub fn radius_bottom(mut self, r: f32) -> Self {
        self.radius[2] = r;
        self.radius[3] = r;
        self
    }

    pub fn radius_top_left(mut self, r: f32) -> Self {
        self.radius[0] = r;
        self
    }

    pub fn radius_top_right(mut self, r: f32) -> Self {
        self.radius[1] = r;
        self
    }

    pub fn radius_bottom_right(mut self, r: f32) -> Self {
        self.radius[2] = r;
        self
    }

    pub fn radius_bottom_left(mut self, r: f32) -> Self {
        self.radius[3] = r;
        self
    }

    pub fn radius_left(mut self, r: f32) -> Self {
        self.radius[0] = r;
        self.radius[3] = r;
        self
    }

    pub fn radius_right(mut self, r: f32) -> Self {
        self.radius[1] = r;
        self.radius[2] = r;
        self
    }

    pub fn border(mut self, color: Color, width: f32) -> Self {
        self.border_color = Some(color);
        self.border_width = width;
        self
    }

    pub fn shadow(mut self, color: Color, ox: f32, oy: f32, blur: f32) -> Self {
        self.shadow_color = Some(color);
        self.shadow_offset = [ox, oy];
        self.shadow_blur = blur;
        self
    }

    pub fn opacity(mut self, o: f32) -> Self {
        self.opacity = o;
        self
    }

    pub fn text_bg_fill_x(mut self, enabled: bool) -> Self {
        self.text_bg_fill_x = enabled;
        self
    }

    pub fn height(mut self, h: f32) -> Self {
        self.height = Some(h);
        self
    }

    pub fn wrap(mut self, strategy: zenthra_text::prelude::TextWrap) -> Self {
        self.wrap = strategy;
        self
    }

    pub fn render_mode(mut self, mode: zenthra_core::RenderMode) -> Self {
        self.render_mode = Some(mode);
        self
    }

    pub fn show(self) -> zenthra_core::Response {
        if let Some(mode) = self.render_mode {
            self.ui.render_mode_stack.push(mode);
        }
        let is_focused = self.ui.focused_id == Some(self.id);
        
        // --- 1. Handle Scroll State ---
        let (scroll_x, mut scroll_y) = if self.scrollable {
            *self.ui.scroll_state.get(&self.id).unwrap_or(&(0.0, 0.0))
        } else {
            (0.0, 0.0)
        };

        // --- 2. Initial Measure (to get content height) ---
        let actual_width = if self.fill_x {
            (self.ui.max_x - self.x).max(self.width)
        } else {
            self.width
        };

        let (_content_w, mut h_content, mut shaped_buffer) = if let Some(fs) = self.ui.font_system.as_ref() {
            let mut adapter = CosmicFontProvider::new_with_system(fs.clone());
            let t_padding = Padding::from(self.text_padding);
            let layout_width = actual_width - self.padding.horizontal() - t_padding.horizontal();
            adapter.set_layout_size(layout_width, 10000.0);
            
            let options = TextOptions::new()
                .font_size(self.font_size)
                .line_height(self.line_height)
                .wrap(self.wrap)
                .max_width(layout_width);
            
            let buffer = adapter.shape(&self.buffer, &options);
            let (_, ch) = buffer.content_size();
            (actual_width, ch + t_padding.vertical(), Some(buffer))
        } else {
            (actual_width, 20.0, None)
        };

        let mut h_box = if self.scrollable {
            self.height.unwrap_or(200.0)
        } else {
            h_content + self.padding.vertical()
        };
        
        if self.scrollable && self.height.unwrap_or(0.0) == 0.0 {
            h_box = 200.0;
        }

        // --- 3. Handle Events ---
        let mut cursor_index = *self.ui.cursor_state.get(&self.id).unwrap_or(&self.buffer.len());
        cursor_index = cursor_index.min(self.buffer.len());
        if !self.buffer.is_char_boundary(cursor_index) {
            cursor_index = self.buffer.len(); // Safety
        }

        let (actual_x, actual_y) = if let Some((rect, _)) = self.ui.get_recorded_layout(self.id) {
            (rect.origin.x + self.ui.offset_x, rect.origin.y + self.ui.offset_y)
        } else {
            (self.x + self.ui.offset_x, self.y + self.ui.offset_y)
        };
        let is_hovered = self.ui.is_hovered(self.id, actual_x, actual_y, actual_width, h_box);

        if is_focused || is_hovered {
            let events = std::mem::take(&mut self.ui.input_events);
            let mut changed = false;
            for event in &events {
                match event {
                    PlatformEvent::CharTyped(c) if is_focused => {
                        if *c != '\r' && *c != '\n' {
                             self.buffer.insert(cursor_index, *c);
                             cursor_index += c.len_utf8();
                             changed = true;
                             self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                        }
                    }
                    PlatformEvent::KeyDown { key } if is_focused => {
                        match key {
                            winit::keyboard::KeyCode::Backspace => {
                                if cursor_index > 0 {
                                    let mut chars = self.buffer[..cursor_index].chars();
                                    if let Some(c) = chars.next_back() {
                                        let len = c.len_utf8();
                                        self.buffer.remove(cursor_index - len);
                                        cursor_index -= len;
                                        changed = true;
                                        self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                                    }
                                }
                            }
                            winit::keyboard::KeyCode::ArrowLeft => {
                                if cursor_index > 0 {
                                    let mut chars = self.buffer[..cursor_index].chars();
                                    if let Some(c) = chars.next_back() {
                                        cursor_index -= c.len_utf8();
                                        self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                                        self.ui.needs_redraw = true;
                                    }
                                }
                            }
                            winit::keyboard::KeyCode::ArrowRight => {
                                if cursor_index < self.buffer.len() {
                                    let mut chars = self.buffer[cursor_index..].chars();
                                    if let Some(c) = chars.next() {
                                        cursor_index += c.len_utf8();
                                        self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                                        self.ui.needs_redraw = true;
                                    }
                                }
                            }
                            winit::keyboard::KeyCode::ArrowUp => {
                                if let Some(sb) = &shaped_buffer {
                                    self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                                    self.ui.needs_redraw = true;
                                    let row_threshold = (self.font_size * self.line_height) * 0.5;

                                    // 1. Find EXACTLY which line index the cursor is on
                                    let mut current_line_idx = 0;
                                    for (i, line) in sb.lines().iter().enumerate() {
                                        if line.start_cluster <= cursor_index {
                                            current_line_idx = i;
                                        } else {
                                            break;
                                        }
                                    }

                                    if current_line_idx > 0 {
                                        // 2. Identify target line and target X
                                        let target_line_idx = current_line_idx - 1;
                                        let target_line = &sb.lines()[target_line_idx];
                                        
                                        // Find where we are horizontally on the current line to try and match it
                                        let mut target_x = 0.0;
                                        if let Some(current_line) = sb.lines().get(current_line_idx) {
                                            for g in sb.glyphs() {
                                                if (g.y - current_line.y).abs() < row_threshold {
                                                    if g.cluster < cursor_index {
                                                        target_x = g.x + g.width;
                                                    } else if g.cluster == cursor_index {
                                                        target_x = g.x;
                                                        break;
                                                    }
                                                }
                                            }
                                        }

                                        // 3. Find closest character on target line
                                        let mut best_idx = None;
                                        let mut best_dist = f32::INFINITY;
                                        for g in sb.glyphs() {
                                            if (g.y - target_line.y).abs() < row_threshold {
                                                let dist = (g.x - target_x).abs();
                                                if dist < best_dist {
                                                    best_dist = dist;
                                                    best_idx = Some(g.cluster);
                                                }
                                            }
                                        }

                                        if let Some(idx) = best_idx {
                                            cursor_index = idx;
                                        } else {
                                            // Fallback for empty target line
                                            cursor_index = target_line.start_cluster;
                                        }
                                    }
                                }
                            }
                            winit::keyboard::KeyCode::ArrowDown => {
                                if let Some(sb) = &shaped_buffer {
                                    self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                                    self.ui.needs_redraw = true;
                                    let row_threshold = (self.font_size * self.line_height) * 0.5;

                                    // 1. Find EXACTLY which line index the cursor is on
                                    let mut current_line_idx = 0;
                                    for (i, line) in sb.lines().iter().enumerate() {
                                        if line.start_cluster <= cursor_index {
                                            current_line_idx = i;
                                        } else {
                                            break;
                                        }
                                    }

                                    if current_line_idx < sb.lines().len() - 1 {
                                        // 2. Identify target line and target X
                                        let target_line_idx = current_line_idx + 1;
                                        let target_line = &sb.lines()[target_line_idx];
                                        
                                        // Find where we are horizontally on current line
                                        let mut target_x = 0.0;
                                        if let Some(current_line) = sb.lines().get(current_line_idx) {
                                            for g in sb.glyphs() {
                                                if (g.y - current_line.y).abs() < row_threshold {
                                                    if g.cluster < cursor_index {
                                                        target_x = g.x + g.width;
                                                    } else if g.cluster == cursor_index {
                                                        target_x = g.x;
                                                        break;
                                                    }
                                                }
                                            }
                                        }

                                        // 3. Find closest character on target line
                                        let mut best_idx = None;
                                        let mut best_dist = f32::INFINITY;
                                        for g in sb.glyphs() {
                                            if (g.y - target_line.y).abs() < row_threshold {
                                                let dist = (g.x - target_x).abs();
                                                if dist < best_dist {
                                                    best_dist = dist;
                                                    best_idx = Some(g.cluster);
                                                }
                                            }
                                        }

                                        if let Some(idx) = best_idx {
                                            cursor_index = idx;
                                        } else {
                                            // Fallback for empty target line
                                            cursor_index = target_line.start_cluster;
                                        }
                                    }
                                }
                            }
                            winit::keyboard::KeyCode::Enter | winit::keyboard::KeyCode::NumpadEnter => {
                                self.buffer.insert(cursor_index, '\n');
                                cursor_index += 1;
                                changed = true;
                                self.ui.interaction_state.insert(self.id, self.ui.elapsed_time);
                            }
                            _ => {}
                        }
                    }
                    PlatformEvent::MouseWheel { delta_x, delta_y } if self.scrollable && is_hovered => {
                        let total_delta = *delta_x + *delta_y;
                        scroll_y -= total_delta * 30.0; 
                    }
                    _ => {}
                }
            }

                    if changed {
                        // RE-SHAPE after buffer modification
                        if let Some(fs) = self.ui.font_system.as_ref() {
                            let mut adapter = CosmicFontProvider::new_with_system(fs.clone());
                            let t_padding = Padding::from(self.text_padding);
                            let layout_width = actual_width - self.padding.horizontal() - t_padding.horizontal();
                            adapter.set_layout_size(layout_width, 10000.0);
                            
                            let options = TextOptions::new().font_size(self.font_size).line_height(self.line_height).wrap(self.wrap).max_width(layout_width);
                            let buffer = adapter.shape(&self.buffer, &options);
                            let (_cw, ch) = buffer.content_size();
                            h_content = ch + t_padding.vertical();
                            shaped_buffer = Some(buffer);
                            
                            // Re-calculate h_box immediately if not fixed
                            if !self.scrollable {
                                h_box = h_content + self.padding.vertical();
                            }
                        }
                        
                        self.ui.cursor_state.insert(self.id, cursor_index);
                    }
                    
                    if self.scrollable {
                        let usable_h = h_box - self.padding.vertical();
                        let max_scroll = (h_content - usable_h).max(0.0);
                        
                        // Vertical Auto-scroll
                        if let Some(sb) = &shaped_buffer {
                            let mut ly = 0.0;
                            let mut found = false;
                            for line in sb.lines() {
                                if line.start_cluster <= cursor_index {
                                    ly = line.y;
                                    found = true;
                                } else { break; }
                            }
                            if found {
                                let line_h = self.font_size * self.line_height;
                                let cursor_y_v = ly + self.text_padding.top;
                                
                                if cursor_y_v > scroll_y + usable_h - line_h {
                                    scroll_y = cursor_y_v - usable_h + line_h;
                                } else if cursor_y_v < scroll_y {
                                    scroll_y = cursor_y_v;
                                }
                            }
                        }

                        scroll_y = scroll_y.clamp(0.0, max_scroll);
                    }
                    self.ui.input_events = events;
                    self.ui.cursor_state.insert(self.id, cursor_index);
                    self.ui.scroll_state.insert(self.id, (scroll_x, scroll_y));
                }

        // --- 4. Render Background (FIXED) ---
        let start_draw = self.ui.draws.len();
        if let Some(bg) = self.bg {
            use crate::ui::RectDraw;
            use zenthra_render::RectInstance;
            self.ui.draws.push(DrawCommand::Rect(RectDraw {
                instance: RectInstance {
                    pos: [self.x, self.y],
                    size: [actual_width, h_box],
                    color: bg.to_array(),
                    radius: self.radius,
                    border_width: self.border_width.max(if is_focused { 1.0 } else { 0.0 }),
                    border_color: self.border_color.unwrap_or(Color::rgba(1.0, 1.0, 1.0, 0.4)).to_array(),
                    shadow_color: self.shadow_color.map(|c| {
                        let mut a = c.to_array();
                        a[3] *= self.shadow_opacity;
                        a
                    }).unwrap_or([0.0, 0.0, 0.0, 0.0]),
                    shadow_offset: self.shadow_offset,
                    shadow_blur: self.shadow_blur,
                    clip_rect: [0.0, 0.0, 9999.0, 9999.0],
                    grayscale: 0.0,
                    brightness: 1.0,
                    opacity: self.opacity,
                    ..Default::default()
                }
            }));
        }

        // --- 5. Render Text (CLIPPED if overflow_hidden) ---
        let pos_y = self.y + self.padding.top - scroll_y;
        let mut text_builder = TextBuilder::new(self.ui, &self.buffer)
            .size(self.font_size)
            .line_height(self.line_height)
            .color(self.color)
            .fill_x(false)
            .padding(self.text_padding.top, self.text_padding.right, self.text_padding.bottom, self.text_padding.left)
            .wrap(self.wrap)
            .max_width(actual_width - self.padding.horizontal() - self.text_padding.horizontal())
            .pos(self.x + self.padding.left, pos_y);

        if self.text_bg_fill_x {
            text_builder = text_builder.min_width(actual_width - self.padding.horizontal());
        }

        if let Some(tbg) = self.text_bg {
            text_builder = text_builder.bg(tbg).fill_x(false);
        }

        if let Some(h) = self.highlight {
            text_builder = text_builder.highlight(h);
        }

        if self.overflow_hidden {
            // Reverted to full-box clipping so content can merge with edges during scroll
            text_builder = text_builder.clip_rect(self.x, self.y, actual_width, h_box);
        }
        
        // Final draw
        text_builder.draw_and_measure();

        // Update persistent scroll state
        if self.scrollable {
            self.ui.scroll_state.insert(self.id, (scroll_x, scroll_y));

            // --- 5.5 Render Scroll Bar ---
            if h_content > h_box - self.padding.vertical() {
                let usable_h = h_box - self.padding.vertical();
                let scroll_bar_w = 4.0;
                let scroll_bar_x = self.x + actual_width - scroll_bar_w - 4.0;
                
                let thumb_h = (usable_h / h_content) * usable_h;
                let thumb_h = thumb_h.clamp(20.0, usable_h);
                
                let max_scroll = (h_content - usable_h).max(1.0);
                let scroll_percent = scroll_y / max_scroll;
                let thumb_y = self.y + self.padding.top + scroll_percent * (usable_h - thumb_h);

                self.ui.draws.push(DrawCommand::OverlayRect(OverlayRectDraw {
                    x: scroll_bar_x,
                    y: thumb_y,
                    width: scroll_bar_w,
                    height: thumb_h,
                    color: Color::rgba(1.0, 1.0, 1.0, 0.4),
                    clip: [self.x, self.y, actual_width, h_box], 
                }));
            }
        }

        // --- 6. Handle Focus ---
        if self.ui.mouse_down {
            if is_hovered {
                self.ui.focused_id = Some(self.id);
            }
        }

        // --- 7. Cursor Rendering ---
        if is_focused {
            let font_size = self.font_size;
            let lh = self.line_height;
            let visual_ascent = font_size * (0.8 + (lh - 1.0) / 2.0);
            let cursor_height = font_size * lh;

            if let Some(sb) = shaped_buffer {
                let first_line_y = sb.lines().first().map(|l| l.y).unwrap_or(visual_ascent);
                let v_shift = visual_ascent - first_line_y;

                let _final_border_w = self.border_width;
                let _final_border_c = self.border_color.unwrap_or(Color::rgba(1.0, 1.0, 1.0, 0.4));
                let mut lx = 0.0;
                let mut ly = first_line_y;
                let mut found = false;

                for g in sb.glyphs() {
                    if g.cluster == cursor_index {
                        lx = g.x;
                        ly = g.y;
                        found = true;
                        break;
                    }
                }

                if !found {
                    let mut best_line = None;
                    for line in sb.lines() {
                        if line.start_cluster <= cursor_index {
                            best_line = Some(line);
                        } else {
                            break;
                        }
                    }

                    if let Some(line) = best_line {
                        ly = line.y;
                        // If we are past the start of the line and not found in glyphs,
                        // we're likely at a newline or trailing space.
                        if cursor_index > line.start_cluster {
                            lx = line.width;
                        } else {
                            lx = 0.0;
                        }
                    }
                    
                    if cursor_index == self.buffer.len() {
                        if let Some(lg) = sb.glyphs().last() {
                            if (lg.y - ly).abs() < 2.0 {
                                lx = lg.x + lg.width;
                            } else {
                                // Last line might be empty
                                if let Some(last_line) = sb.lines().last() {
                                    ly = last_line.y;
                                    lx = 0.0;
                                }
                            }
                        }
                    }
                }
                
                let cx = lx + self.x + self.padding.left + self.text_padding.left;
                let cy = ly + self.y + self.padding.top + self.text_padding.top + v_shift - visual_ascent - scroll_y;
                
                 // Smart Blink: Solid while typing, blink when idle
                 let last_activity = *self.ui.interaction_state.get(&self.id).unwrap_or(&0.0);
                 let time_since_activity = self.ui.elapsed_time - last_activity;
                 
                 let is_blink_visible = if time_since_activity < 0.5 {
                     true // Solid during and just after activity
                 } else {
                     // Start blinking after 500ms of idle. 
                     // Offset by last_activity so the cycle always starts "ON" when you stop.
                     (self.ui.elapsed_time - last_activity).fract() < 0.5
                 };
                 
                 // Only draw cursor if it's within the viewport and in the visible blink phase
                 if cy >= self.y - 2.0 && cy + cursor_height <= self.y + h_box + 2.0 && is_blink_visible {
                    self.ui.draws.push(DrawCommand::OverlayRect(OverlayRectDraw {
                        x: cx,
                        y: cy,
                        width: 2.0,
                        height: cursor_height,
                        color: Color::WHITE,
                        clip: [self.x, self.y, actual_width, h_box],
                    }));
                }
            }
        }

        // --- 8. Advance UI ---
        self.ui.record_layout(self.id, Rect::new(self.x, self.y, actual_width, h_box));
        self.ui.advance(actual_width, h_box, start_draw);

        if self.render_mode.is_some() {
            self.ui.render_mode_stack.pop();
        }

        zenthra_core::Response {
            clicked: self.ui.clicked && is_hovered,
            hovered: is_hovered,
            pressed: is_hovered && self.ui.mouse_down,
        }
    }
}