blinc_cn 0.5.0

Blinc Component Library - shadcn-style themed components built on blinc_layout primitives
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! Tabs component for tabbed navigation
//!
//! A themed tabbed interface component using state-driven reactivity.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! fn build_ui(ctx: &WindowedContext) -> impl ElementBuilder {
//!     let active_tab = ctx.use_state_keyed("active_tab", || "account".to_string());
//!
//!     // Simple text labels
//!     cn::tabs(&active_tab)
//!         .tab("account", "Account", || {
//!             div().child(text("Account settings here"))
//!         })
//!         .tab("password", "Password", || {
//!             div().child(text("Password settings here"))
//!         })
//!         .tab("notifications", "Notifications", || {
//!             div().child(text("Notification preferences here"))
//!         })
//! }
//!
//! // Using TabMenuItem for custom tab triggers with icons
//! cn::tabs(&active_tab)
//!     .tab_item(
//!         cn::tab_item("account")
//!             .icon(account_icon_svg)
//!             .label("Account"),
//!         || div().child(text("Account settings"))
//!     )
//!     .tab_item(
//!         cn::tab_item("settings")
//!             .icon(settings_icon_svg)
//!             .label("Settings")
//!             .badge("3"),  // Show notification badge
//!         || div().child(text("Settings panel"))
//!     )
//!
//! // Disabled tabs
//! cn::tabs(&active_tab)
//!     .tab_item(
//!         cn::tab_item("active").label("Active Tab"),
//!         || div()
//!     )
//!     .tab_item(
//!         cn::tab_item("disabled").label("Disabled").disabled(),
//!         || div()
//!     )
//!
//! // With size variant
//! cn::tabs(&active_tab)
//!     .size(TabsSize::Large)
//!     .tab("tab1", "Tab 1", || div())
//!
//! // With default tab
//! cn::tabs(&active_tab)
//!     .default_value("password")
//!     .tab("account", "Account", || div())
//!     .tab("password", "Password", || div())
//! ```

use std::cell::OnceCell;
use std::sync::Arc;

use blinc_animation::{AnimationPreset, MultiKeyframeAnimation};
use blinc_core::{Color, State};
use blinc_layout::div::ElementTypeId;
// For query_motion to trigger suspended animations
use blinc_layout::element::{CursorStyle, RenderProps};
use blinc_layout::motion::motion_derived;
use blinc_layout::prelude::*;
use blinc_layout::stateful::{stateful_with_key, ButtonState, NoState};
use blinc_layout::tree::{LayoutNodeId, LayoutTree};
use blinc_theme::{ColorScheme, ColorToken, RadiusToken, ThemeState};

use blinc_layout::selector::query_motion;
use blinc_layout::stateful::request_redraw;
use blinc_layout::InstanceKey;

// =============================================================================
// Tab Transition Tracking (simple cross-fade)
// =============================================================================

/// Tracks exiting tabs for cross-fade transitions
#[derive(Clone, Debug, Default)]
struct TabTransitionState {
    /// Currently active tab
    current_tab: String,
    /// Tab that's exiting (if any)
    exiting_tab: Option<String>,
}

/// Get the tab transition store
fn tab_transitions_store() -> &'static blinc_core::Store<TabTransitionState> {
    blinc_core::create_store::<TabTransitionState>("tab-transitions")
}

/// Update transition state when tab changes - starts exit animation on old tab
fn update_tab_transition(tabs_id: &str, new_tab: &str, motion_base_key: &str) {
    tab_transitions_store().update(tabs_id, |state| {
        if state.current_tab != new_tab && !state.current_tab.is_empty() {
            // Tab changed - start exit animation on old tab
            let old_tab = state.current_tab.clone();
            let exit_motion_key = format!("motion:{}:{}:child:0", motion_base_key, old_tab);
            query_motion(&exit_motion_key).exit();
            state.exiting_tab = Some(old_tab);
        }
        state.current_tab = new_tab.to_string();
    });
}

/// Check if exiting tab's animation is complete and clear if so
fn check_and_clear_exiting_tab(tabs_id: &str, motion_base_key: &str) -> Option<String> {
    tab_transitions_store().update_with(tabs_id, |state| {
        if let Some(ref exiting) = state.exiting_tab {
            let exit_motion_key = format!("motion:{}:{}:child:0", motion_base_key, exiting);
            let motion = query_motion(&exit_motion_key);

            if !motion.is_animating() {
                // Exit complete - clear exiting tab
                state.exiting_tab = None;
                return None;
            }
            // Still animating - keep rendering exiting tab
            request_redraw();
            return Some(exiting.clone());
        }
        None
    })
}

/// Tabs size variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabsSize {
    /// Small tabs (height: 32px, text: 13px)
    Small,
    /// Medium tabs (height: 40px, text: 14px)
    #[default]
    Medium,
    /// Large tabs (height: 48px, text: 16px)
    Large,
}

impl TabsSize {
    /// Get the height for the tab list
    fn height(&self) -> f32 {
        match self {
            TabsSize::Small => 32.0,
            TabsSize::Medium => 40.0,
            TabsSize::Large => 48.0,
        }
    }

    /// Get the font size
    fn font_size(&self) -> f32 {
        match self {
            TabsSize::Small => 13.0,
            TabsSize::Medium => 14.0,
            TabsSize::Large => 16.0,
        }
    }

    /// Get the horizontal padding
    fn padding_x(&self) -> f32 {
        match self {
            TabsSize::Small => 12.0,
            TabsSize::Medium => 16.0,
            TabsSize::Large => 20.0,
        }
    }

    /// Get icon size
    fn icon_size(&self) -> f32 {
        match self {
            TabsSize::Small => 14.0,
            TabsSize::Medium => 16.0,
            TabsSize::Large => 18.0,
        }
    }

    /// Get badge font size
    fn badge_font_size(&self) -> f32 {
        match self {
            TabsSize::Small => 10.0,
            TabsSize::Medium => 11.0,
            TabsSize::Large => 12.0,
        }
    }
}

/// Builder for customizing individual tab triggers
///
/// Allows setting icons, badges, custom content, and disabled state for tabs.
#[derive(Clone)]
pub struct TabMenuItem {
    /// The value (stored in state when selected)
    value: String,
    /// Optional text label
    label: Option<String>,
    /// Optional icon SVG string
    icon: Option<String>,
    /// Optional badge text (e.g., notification count)
    badge: Option<String>,
    /// Whether this tab is disabled
    disabled: bool,
    /// Custom content builder (overrides label/icon if set)
    custom_content: Option<Arc<dyn Fn(bool) -> Div + Send + Sync>>,
}

impl std::fmt::Debug for TabMenuItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabMenuItem")
            .field("value", &self.value)
            .field("label", &self.label)
            .field("icon", &self.icon.is_some())
            .field("badge", &self.badge)
            .field("disabled", &self.disabled)
            .field("custom_content", &self.custom_content.is_some())
            .finish()
    }
}

impl TabMenuItem {
    /// Create a new tab menu item with a value
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: None,
            icon: None,
            badge: None,
            disabled: false,
            custom_content: None,
        }
    }

    /// Set the text label
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set an icon (SVG string)
    pub fn icon(mut self, svg: impl Into<String>) -> Self {
        self.icon = Some(svg.into());
        self
    }

    /// Set a badge (e.g., notification count)
    pub fn badge(mut self, badge: impl Into<String>) -> Self {
        self.badge = Some(badge.into());
        self
    }

    /// Mark this tab as disabled
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }

    /// Set custom content builder
    ///
    /// The callback receives a boolean indicating if the tab is active.
    /// This overrides the default label/icon rendering.
    pub fn content<F>(mut self, builder: F) -> Self
    where
        F: Fn(bool) -> Div + Send + Sync + 'static,
    {
        self.custom_content = Some(Arc::new(builder));
        self
    }

    /// Get the value
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Check if disabled
    pub fn is_disabled(&self) -> bool {
        self.disabled
    }
}

/// Create a new tab menu item builder
///
/// # Example
///
/// ```ignore
/// cn::tab_item("settings")
///     .icon(settings_icon)
///     .label("Settings")
///     .badge("2")
/// ```
pub fn tab_item(value: impl Into<String>) -> TabMenuItem {
    TabMenuItem::new(value)
}

/// Content builder for tab panels
pub type TabContentFn = Arc<dyn Fn() -> Div + Send + Sync>;

/// A single tab item (internal representation)
#[derive(Clone)]
struct TabItem {
    /// The tab menu item configuration
    menu_item: TabMenuItem,
    /// Content builder for the tab panel
    content: TabContentFn,
}

impl std::fmt::Debug for TabItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabItem")
            .field("menu_item", &self.menu_item)
            .finish()
    }
}

/// Content transition preset for tab switching
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabsTransition {
    /// No animation
    None,
    /// Fade in/out (default)
    #[default]
    Fade,
    /// Slide from left
    SlideLeft,
    /// Slide from right
    SlideRight,
    /// Slide up
    SlideUp,
    /// Slide down
    SlideDown,
}

impl TabsTransition {
    /// Get enter animation for this transition
    fn enter_animation(&self) -> Option<MultiKeyframeAnimation> {
        match self {
            TabsTransition::None => None,
            TabsTransition::Fade => Some(AnimationPreset::fade_in(250)),
            TabsTransition::SlideLeft => Some(AnimationPreset::slide_in_left(250, 20.0)),
            TabsTransition::SlideRight => Some(AnimationPreset::slide_in_right(250, 50.0)),
            TabsTransition::SlideUp => Some(AnimationPreset::slide_in_top(250, 20.0)),
            TabsTransition::SlideDown => Some(AnimationPreset::slide_in_bottom(250, 20.0)),
        }
    }

    /// Get exit animation for this transition
    fn exit_animation(&self) -> Option<MultiKeyframeAnimation> {
        match self {
            TabsTransition::None => None,
            TabsTransition::Fade => Some(AnimationPreset::fade_out(200)),
            TabsTransition::SlideLeft => Some(AnimationPreset::slide_out_left(200, 20.0)),
            TabsTransition::SlideRight => Some(AnimationPreset::slide_out_right(200, 25.0)),
            TabsTransition::SlideUp => Some(AnimationPreset::slide_out_top(200, 20.0)),
            TabsTransition::SlideDown => Some(AnimationPreset::slide_out_bottom(200, 20.0)),
        }
    }
}

/// Configuration for the tabs component
#[derive(Clone)]
#[allow(clippy::type_complexity)]
struct TabsConfig {
    state: State<String>,
    tabs: Vec<TabItem>,
    size: TabsSize,
    default_value: Option<String>,
    on_change: Option<Arc<dyn Fn(&str) + Send + Sync>>,
    transition: TabsTransition,
}

impl std::fmt::Debug for TabsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabsConfig")
            .field("tabs", &self.tabs)
            .field("size", &self.size)
            .field("default_value", &self.default_value)
            .finish()
    }
}

/// The built tabs component
pub struct Tabs {
    inner: Div,
}

impl std::fmt::Debug for Tabs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Tabs").finish()
    }
}

/// Builder for tabs component
pub struct TabsBuilder {
    key: InstanceKey,
    config: TabsConfig,
    /// User-added CSS classes
    classes: Vec<String>,
    /// User-set element ID
    user_id: Option<String>,
    built: OnceCell<Tabs>,
}

impl std::fmt::Debug for TabsBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabsBuilder")
            .field("config", &self.config)
            .finish()
    }
}

impl TabsBuilder {
    /// Create a new tabs builder with state
    #[track_caller]
    pub fn new(state: &State<String>) -> Self {
        Self {
            key: InstanceKey::new("tabs"),
            config: TabsConfig {
                state: state.clone(),
                tabs: Vec::new(),
                size: TabsSize::default(),
                default_value: None,
                on_change: None,
                transition: TabsTransition::default(),
            },
            classes: Vec::new(),
            user_id: None,
            built: OnceCell::new(),
        }
    }

    /// Create a tabs builder with an explicit key
    pub fn with_key(key: impl Into<String>, state: &State<String>) -> Self {
        Self {
            key: InstanceKey::explicit(key),
            config: TabsConfig {
                state: state.clone(),
                tabs: Vec::new(),
                size: TabsSize::default(),
                default_value: None,
                on_change: None,
                transition: TabsTransition::default(),
            },
            classes: Vec::new(),
            user_id: None,
            built: OnceCell::new(),
        }
    }

    /// Add a tab with value, label, and content (simple API)
    pub fn tab<F>(mut self, value: impl Into<String>, label: impl Into<String>, content: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        let value_str = value.into();
        let label_str = label.into();
        self.config.tabs.push(TabItem {
            menu_item: TabMenuItem::new(value_str).label(label_str),
            content: Arc::new(content),
        });
        self
    }

    /// Add a tab with a TabMenuItem for custom configuration
    ///
    /// # Example
    ///
    /// ```ignore
    /// cn::tabs(&state)
    ///     .tab_item(
    ///         cn::tab_item("settings")
    ///             .icon(settings_svg)
    ///             .label("Settings")
    ///             .badge("3"),
    ///         || div().child(text("Settings content"))
    ///     )
    /// ```
    pub fn tab_item<F>(mut self, item: TabMenuItem, content: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        self.config.tabs.push(TabItem {
            menu_item: item,
            content: Arc::new(content),
        });
        self
    }

    /// Add a disabled tab (simple API)
    pub fn tab_disabled<F>(
        mut self,
        value: impl Into<String>,
        label: impl Into<String>,
        content: F,
    ) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        let value_str = value.into();
        let label_str = label.into();
        self.config.tabs.push(TabItem {
            menu_item: TabMenuItem::new(value_str).label(label_str).disabled(),
            content: Arc::new(content),
        });
        self
    }

    /// Set the tabs size
    pub fn size(mut self, size: TabsSize) -> Self {
        self.config.size = size;
        self
    }

    /// Set the default value (will be set on first render if state is empty)
    pub fn default_value(mut self, value: impl Into<String>) -> Self {
        self.config.default_value = Some(value.into());
        self
    }

    /// Set the change callback
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        self.config.on_change = Some(Arc::new(callback));
        self
    }

    /// Set the content transition animation
    ///
    /// # Example
    ///
    /// ```ignore
    /// cn::tabs(&state)
    ///     .transition(TabsTransition::SlideLeft)
    ///     .tab("a", "Tab A", || div())
    /// ```
    pub fn transition(mut self, transition: TabsTransition) -> Self {
        self.config.transition = transition;
        self
    }

    /// Add a CSS class for selector matching
    pub fn class(mut self, name: impl Into<String>) -> Self {
        self.classes.push(name.into());
        self
    }

    /// Set the element ID for CSS selector matching
    pub fn id(mut self, id: &str) -> Self {
        self.user_id = Some(id.to_string());
        self
    }

    /// Get or build the component
    fn get_or_build(&self) -> &Tabs {
        self.built.get_or_init(|| self.build_component())
    }

    /// Build the tabs component
    fn build_component(&self) -> Tabs {
        let theme = ThemeState::get();
        let config = &self.config;

        // Get current value from state - use State<T>::get() directly
        let current_value = config.state.get();

        // If current value is empty and we have a default, use it
        if current_value.is_empty() {
            if let Some(ref default) = config.default_value {
                config.state.set(default.clone());
            } else if let Some(first_tab) = config.tabs.first() {
                let first_enabled = config
                    .tabs
                    .iter()
                    .find(|t| !t.menu_item.is_disabled())
                    .map(|t| t.menu_item.value().to_string())
                    .unwrap_or_else(|| first_tab.menu_item.value().to_string());
                config.state.set(first_enabled);
            }
        }

        // Theme colors - use SecondaryHover for better contrast with text
        let tab_list_bg = theme.color(ColorToken::SurfaceOverlay);
        let radius = theme.radius(RadiusToken::Md);
        let content_margin = theme.spacing().space_1;
        let size = config.size;

        let border = if matches!(theme.scheme(), ColorScheme::Dark) {
            theme.color(ColorToken::Surface)
        } else {
            Color::TRANSPARENT
        };

        // ========================================
        // Container 1: Tab Button Area
        // ========================================
        let tabs_for_buttons = config.tabs.clone();
        let state_for_buttons = config.state.clone();
        let on_change = config.on_change.clone();
        let transition = config.transition;

        let trigger_key = self.key.derive("tab_triggers");
        // Create motion base key for triggering animations from tab buttons (already a String)
        let motion_base_key_str = self.key.derive("motion");
        let button_area_key = self.key.derive("button_area");

        let tab_button_area = stateful_with_key::<NoState>(&button_area_key)
            .deps([config.state.signal_id()])
            .on_state(move |_ctx| {
                let active_value = state_for_buttons.get();

                let mut buttons = div()
                    .class("cn-tabs-list")
                    .h(size.height())
                    .w_full()
                    .bg(tab_list_bg)
                    .rounded_md()
                    .padding(Length::Px(6.0))
                    .flex_row()
                    .items_center()
                    .border(1.0, border)
                    .gap(4.0);

                for tab in tabs_for_buttons.iter() {
                    let is_active = tab.menu_item.value() == active_value;
                    let value = tab.menu_item.value();

                    // Build motion key for this tab's content
                    let tab_motion_key = if transition != TabsTransition::None {
                        Some(format!("{}:{}", motion_base_key_str, value))
                    } else {
                        None
                    };

                    let tab_trigger = build_tab_trigger(
                        &trigger_key,
                        &tab.menu_item,
                        is_active,
                        size,
                        state_for_buttons.clone(),
                        on_change.clone(),
                        tab_motion_key,
                    );

                    buttons = buttons.child(tab_trigger);
                }

                buttons
            });

        // ========================================
        // Container 2: Tab Content Area
        // ========================================
        let tabs_for_content = config.tabs.clone();
        let state_for_content = config.state.clone();
        let transition = config.transition;
        // Clone the base key for deriving motion keys inside on_state
        let motion_base_key = self.key.derive("motion");
        let tabs_id = self.key.get().to_string();
        let content_area_key = self.key.derive("content_area");

        let tab_content_area = stateful_with_key::<NoState>(&content_area_key)
            .deps([config.state.signal_id()])
            .on_state(move |ctx| {
                let active_value = state_for_content.get();

                // Update transition tracking (triggers exit animation if tab changed)
                update_tab_transition(&tabs_id, &active_value, &motion_base_key);

                // Check for exiting tab (clear if animation complete)
                let exiting_tab = check_and_clear_exiting_tab(&tabs_id, &motion_base_key);

                // Helper to build content for a specific tab
                // Note: We use motion_derived with explicit key rather than ctx.motion()
                // because build_tab_trigger queries motion using motion_base_key from outside
                // this stateful context, and the keys must match.
                let build_tab_content = |tab_value: &str, is_exiting: bool| -> Option<Div> {
                    tabs_for_content
                        .iter()
                        .find(|t| t.menu_item.value() == tab_value)
                        .map(|tab| {
                            let content = (tab.content)();
                            if transition != TabsTransition::None {
                                // Use explicit key that matches query in build_tab_trigger
                                let tab_motion_key = format!("{}:{}", motion_base_key, tab_value);
                                let mut m = motion_derived(&tab_motion_key);

                                // Enter animation for non-exiting tabs
                                if !is_exiting {
                                    if let Some(enter) = transition.enter_animation() {
                                        m = m.enter_animation(enter);
                                    }
                                }
                                // Exit animation always configured
                                if let Some(exit) = transition.exit_animation() {
                                    m = m.exit_animation(exit);
                                }

                                div()
                                    .w_full()
                                    .flex_grow()
                                    .absolute()
                                    .left(0.0)
                                    .top(0.0)
                                    .right(0.0)
                                    .bottom(0.0)
                                    .child(m.child(content))
                            } else {
                                div().w_full().flex_grow().child(content)
                            }
                        })
                };

                // Cross-fade: render both exiting and current tabs in a stack
                if let Some(ref exiting) = exiting_tab {
                    use blinc_layout::stack::stack;
                    let mut content_stack = stack().w_full().flex_grow();

                    // Add exiting tab content (underneath, fading out)
                    if let Some(exiting_content) = build_tab_content(exiting, true) {
                        content_stack = content_stack.child(exiting_content);
                    }

                    // Add current tab content (on top, fading in)
                    if let Some(current_content) = build_tab_content(&active_value, false) {
                        content_stack = content_stack.child(current_content);
                    }

                    div()
                        .w_full()
                        .mt(content_margin)
                        .flex_grow()
                        .relative()
                        .child(content_stack)
                } else {
                    // No transition - just render current tab
                    if let Some(current_content) = build_tab_content(&active_value, false) {
                        div()
                            .w_full()
                            .mt(content_margin)
                            .flex_grow()
                            .child(current_content)
                    } else {
                        div().w_full().flex_grow()
                    }
                }
            });

        // Combine both containers
        let mut container = div()
            .w_full()
            .flex_grow()
            .flex_col()
            .child(tab_button_area)
            .child(tab_content_area);

        // Apply user classes and id
        for c in &self.classes {
            container = container.class(c);
        }
        if let Some(ref id) = self.user_id {
            container = container.id(id);
        }

        Tabs { inner: container }
    }
}

/// Build a simple tab trigger without nested Stateful (no hover effects)
#[allow(clippy::type_complexity)]
fn build_tab_trigger(
    trigger_key: &str,
    menu_item: &TabMenuItem,
    is_active: bool,
    size: TabsSize,
    tab_state: State<String>,
    on_change: Option<Arc<dyn Fn(&str) + Send + Sync>>,
    motion_key: Option<String>,
) -> impl ElementBuilder {
    let theme = ThemeState::get();
    let text_primary = theme.color(ColorToken::TextPrimary);
    let text_secondary = theme.color(ColorToken::TextSecondary);
    let surface = theme.color(ColorToken::SurfaceElevated);
    let radius = theme.radius(RadiusToken::Md);

    let value = menu_item.value.clone();
    let disabled = menu_item.disabled;

    // Calculate inner height (tab list height minus padding)
    let inner_height = size.height() - 16.0;

    // Clone menu_item data for closure
    let icon_svg = menu_item.icon.clone();
    let label_text = menu_item.label.clone();
    let badge_text = menu_item.badge.clone();
    let trigger_state_key = format!("{}:{}", trigger_key, value);

    let mut trigger = stateful_with_key::<ButtonState>(&trigger_state_key).on_state(move |ctx| {
        let state = ctx.state();
        let theme = ThemeState::get();

        // Determine colors based on active and hover state
        let is_hovered = matches!(state, ButtonState::Hovered | ButtonState::Pressed);

        let text_color = if disabled {
            text_secondary.with_alpha(0.5)
        } else if is_active {
            text_primary
        } else if is_hovered {
            text_primary.with_alpha(0.8)
        } else {
            text_secondary
        };

        let bg = if is_active && !disabled {
            surface
        } else if is_hovered && !disabled {
            surface.with_alpha(0.5)
        } else {
            Color::TRANSPARENT
        };

        // Build content
        let mut content = div().flex_row().items_center().gap(theme.spacing().space_2);

        // Add icon if present
        if let Some(ref icon) = icon_svg {
            content = content.child(
                svg(icon)
                    .size(size.icon_size(), size.icon_size())
                    .color(text_color),
            );
        }

        // Add label if present
        if let Some(ref label) = label_text {
            content = content.child(
                text(label)
                    .size(size.font_size())
                    .color(text_color)
                    .weight(if is_active {
                        FontWeight::Medium
                    } else {
                        FontWeight::Normal
                    })
                    .no_cursor(),
            );
        }

        // Add badge if present
        if let Some(ref badge) = badge_text {
            let primary = theme.color(ColorToken::Primary);
            content = content.child(
                div()
                    .px(theme.spacing().space_1_5)
                    .py(1.0)
                    .bg(primary)
                    .rounded(theme.radius(RadiusToken::Full))
                    .child(
                        text(badge)
                            .size(size.badge_font_size())
                            .color(theme.color(ColorToken::PrimaryActive))
                            .medium()
                            .no_cursor(),
                    ),
            );
        }

        // Determine size CSS class for trigger
        let trigger_size_class = match size {
            TabsSize::Small => "cn-tabs-trigger--sm",
            TabsSize::Medium => "cn-tabs-trigger--md",
            TabsSize::Large => "cn-tabs-trigger--lg",
        };

        let mut trigger_div = div()
            .class("cn-tabs-trigger")
            .class(trigger_size_class)
            .h(inner_height)
            .padding_x(Length::Px(size.padding_x()))
            .padding_y(Length::Px(
                size.padding_x() / if size != TabsSize::Small { 2.0 } else { 1.0 },
            ))
            .flex_row()
            .items_center()
            .justify_center()
            .when(size == TabsSize::Small, |d| d.rounded_sm())
            .when(size != TabsSize::Small, |d| d.rounded_md())
            .bg(bg)
            .cursor(if disabled {
                CursorStyle::Default
            } else {
                CursorStyle::Pointer
            })
            .child(content);

        // Add active class for active tab
        if is_active && !disabled {
            trigger_div = trigger_div.class("cn-tabs-trigger--active").shadow_sm();
        }

        // Add disabled class
        if disabled {
            trigger_div = trigger_div.class("cn-tabs-trigger--disabled");
        }

        trigger_div
    });

    // Add click handler if not disabled and not active
    if !disabled && !is_active {
        let value_for_click = value.clone();
        trigger = trigger.on_click(move |_| {
            // Start the motion animation for the new tab content
            if let Some(ref mk) = motion_key {
                let full_motion_key = format!("motion:{}:child:0", mk);
                query_motion(&full_motion_key).start();
            }

            tab_state.set(value_for_click.clone());
            if let Some(ref cb) = on_change {
                cb(&value_for_click);
            }
        });
    }

    trigger
}

impl ElementBuilder for TabsBuilder {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        self.get_or_build().inner.build(tree)
    }

    fn render_props(&self) -> RenderProps {
        self.get_or_build().inner.render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.get_or_build().inner.children_builders()
    }

    fn element_type_id(&self) -> ElementTypeId {
        self.get_or_build().inner.element_type_id()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.get_or_build().inner.layout_style()
    }

    fn element_classes(&self) -> &[String] {
        self.get_or_build().inner.element_classes()
    }

    fn element_id(&self) -> Option<&str> {
        self.get_or_build().inner.element_id()
    }
}

impl std::ops::Deref for TabsBuilder {
    type Target = Div;

    fn deref(&self) -> &Self::Target {
        &self.get_or_build().inner
    }
}

/// Create a new tabs component
///
/// # Example
///
/// ```ignore
/// let tab_state = ctx.use_state_keyed("tabs", || "tab1".to_string());
///
/// cn::tabs(&tab_state)
///     .tab("tab1", "First Tab", || div().child(text("Content 1")))
///     .tab("tab2", "Second Tab", || div().child(text("Content 2")))
/// ```
#[track_caller]
pub fn tabs(state: &State<String>) -> TabsBuilder {
    TabsBuilder::new(state)
}

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

    #[test]
    fn test_tabs_size() {
        assert_eq!(TabsSize::Small.height(), 32.0);
        assert_eq!(TabsSize::Medium.height(), 40.0);
        assert_eq!(TabsSize::Large.height(), 48.0);
    }
}