leptos-store 0.11.0

Enterprise-grade, type-enforced state management for Leptos
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
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 nyvorin

//! Store composition patterns.
//!
//! This module provides patterns for composing multiple stores together:
//!
//! - **Aggregation**: Combine multiple stores into a root store
//! - **Dependencies**: Allow stores to depend on other stores
//! - **Derived Views**: Create read-only views combining multiple stores
//!
//! # Example
//!
//! ```rust
//! # use leptos::prelude::{RwSignal, ReadSignal};
//! # use leptos_store::store::Store;
//! # use leptos_store::composition::{RootStore, CompositeStore};
//! # #[derive(Clone, Debug, Default)]
//! # struct AuthState;
//! # #[derive(Clone)]
//! # struct AuthStore { state: RwSignal<AuthState> }
//! # impl AuthStore { fn new() -> Self { Self { state: RwSignal::new(AuthState) } } }
//! # impl Store for AuthStore {
//! #     type State = AuthState;
//! #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
//! # }
//! # #[derive(Clone, Debug, Default)]
//! # struct CartState;
//! # #[derive(Clone)]
//! # struct CartStore { state: RwSignal<CartState> }
//! # impl CartStore { fn new() -> Self { Self { state: RwSignal::new(CartState) } } }
//! # impl Store for CartStore {
//! #     type State = CartState;
//! #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
//! # }
//! # #[derive(Clone, Debug, Default)]
//! # struct UiState;
//! # #[derive(Clone)]
//! # struct UiStore { state: RwSignal<UiState> }
//! # impl UiStore { fn new() -> Self { Self { state: RwSignal::new(UiState) } } }
//! # impl Store for UiStore {
//! #     type State = UiState;
//! #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
//! # }
//! // Create a root store aggregating multiple domain stores
//! let root = RootStore::builder()
//!     .with_store(AuthStore::new())
//!     .with_store(CartStore::new())
//!     .with_store(UiStore::new())
//!     .build();
//!
//! // Access individual stores
//! let auth = root.get::<AuthStore>().unwrap();
//! ```

use crate::store::{Store, StoreError, StoreId};
use leptos::prelude::*;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

// ============================================================================
// Type-erased Store
// ============================================================================

/// Trait for type-erased store access.
///
/// This allows storing heterogeneous stores in collections.
pub trait AnyStore: Send + Sync {
    /// Get the store ID.
    fn id(&self) -> StoreId;

    /// Get the store name.
    fn name(&self) -> &'static str;

    /// Get the store as Any for downcasting.
    fn as_any(&self) -> &dyn Any;

    /// Get the store's type ID.
    fn type_id(&self) -> TypeId;
}

impl<S: Store + 'static> AnyStore for S {
    fn id(&self) -> StoreId {
        Store::id(self)
    }

    fn name(&self) -> &'static str {
        Store::name(self)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<S>()
    }
}

// ============================================================================
// Composite Store
// ============================================================================

/// Trait for stores that aggregate multiple child stores.
///
/// Composite stores provide a unified interface for managing multiple
/// domain stores while maintaining type safety.
pub trait CompositeStore: Send + Sync {
    /// Get all child stores.
    fn stores(&self) -> Vec<&dyn AnyStore>;

    /// Get a store by type.
    fn get<S: Store + 'static>(&self) -> Option<&S>;

    /// Check if a store type is present.
    fn contains<S: Store + 'static>(&self) -> bool {
        self.get::<S>().is_some()
    }

    /// Get the number of stores.
    fn len(&self) -> usize {
        self.stores().len()
    }

    /// Check if empty.
    fn is_empty(&self) -> bool {
        self.stores().is_empty()
    }
}

// ============================================================================
// Root Store
// ============================================================================

/// A root store that aggregates multiple domain stores.
///
/// The root store provides a central access point for all stores
/// in an application, enabling dependency injection and unified
/// state management.
///
/// # Example
///
/// ```rust
/// # use leptos::prelude::{RwSignal, ReadSignal};
/// # use leptos_store::store::Store;
/// # use leptos_store::composition::{RootStore, CompositeStore};
/// # #[derive(Clone, Debug, Default)]
/// # struct AuthState;
/// # #[derive(Clone)]
/// # struct AuthStore { state: RwSignal<AuthState> }
/// # impl AuthStore { fn new() -> Self { Self { state: RwSignal::new(AuthState) } } }
/// # impl Store for AuthStore {
/// #     type State = AuthState;
/// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
/// # }
/// # #[derive(Clone, Debug, Default)]
/// # struct CartState;
/// # #[derive(Clone)]
/// # struct CartStore { state: RwSignal<CartState> }
/// # impl CartStore { fn new() -> Self { Self { state: RwSignal::new(CartState) } } }
/// # impl Store for CartStore {
/// #     type State = CartState;
/// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
/// # }
/// let root = RootStore::builder()
///     .with_store(AuthStore::new())
///     .with_store(CartStore::new())
///     .build();
///
/// // Access a specific store
/// let auth = root.get::<AuthStore>().unwrap();
/// ```
#[derive(Clone)]
pub struct RootStore {
    stores: Arc<HashMap<TypeId, Arc<dyn AnyStore>>>,
}

impl Default for RootStore {
    fn default() -> Self {
        Self::new()
    }
}

impl RootStore {
    /// Create a new empty root store.
    pub fn new() -> Self {
        Self {
            stores: Arc::new(HashMap::new()),
        }
    }

    /// Create a builder for constructing a root store.
    pub fn builder() -> RootStoreBuilder {
        RootStoreBuilder::new()
    }

    /// Get a store by type.
    pub fn get<S: Store + 'static>(&self) -> Option<&S> {
        self.stores
            .get(&TypeId::of::<S>())
            .and_then(|s| s.as_any().downcast_ref::<S>())
    }

    /// Get a store by type, or panic with a helpful error.
    pub fn expect<S: Store + 'static>(&self) -> &S {
        self.get::<S>().unwrap_or_else(|| {
            panic!(
                "Store {} not found in RootStore. Did you forget to add it?",
                std::any::type_name::<S>()
            )
        })
    }

    /// Check if a store type is registered.
    pub fn contains<S: Store + 'static>(&self) -> bool {
        self.stores.contains_key(&TypeId::of::<S>())
    }

    /// Get the number of registered stores.
    pub fn len(&self) -> usize {
        self.stores.len()
    }

    /// Check if the root store is empty.
    pub fn is_empty(&self) -> bool {
        self.stores.is_empty()
    }

    /// Get all store type IDs.
    pub fn store_types(&self) -> Vec<TypeId> {
        self.stores.keys().copied().collect()
    }

    /// Get all store names.
    pub fn store_names(&self) -> Vec<&'static str> {
        self.stores.values().map(|s| s.name()).collect()
    }
}

impl CompositeStore for RootStore {
    fn stores(&self) -> Vec<&dyn AnyStore> {
        self.stores.values().map(|s| s.as_ref()).collect()
    }

    fn get<S: Store + 'static>(&self) -> Option<&S> {
        RootStore::get(self)
    }
}

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

// ============================================================================
// Root Store Builder
// ============================================================================

/// Builder for constructing root stores.
///
/// Stores can optionally declare initialization ordering constraints
/// via [`with_store_after`](Self::with_store_after). This records which
/// store should be initialized after another, enabling correct hydration
/// ordering for dependent stores.
pub struct RootStoreBuilder {
    stores: HashMap<TypeId, Arc<dyn AnyStore>>,
    initialization_order: Vec<TypeId>,
}

impl Default for RootStoreBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RootStoreBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            stores: HashMap::new(),
            initialization_order: Vec::new(),
        }
    }

    /// Add a store to the root.
    pub fn with_store<S: Store + 'static>(mut self, store: S) -> Self {
        self.stores.insert(TypeId::of::<S>(), Arc::new(store));
        self
    }

    /// Add a store and record that it should initialize **after** `Dep`.
    ///
    /// This is an ordering hint for hydration: stores declared with
    /// `with_store_after` should be hydrated after their dependency.
    /// The builder records the constraint but does not enforce ordering
    /// at runtime — component render order controls actual hydration
    /// timing in Leptos.
    ///
    /// Query the declared order with [`initialization_order()`](Self::initialization_order).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use leptos::prelude::{RwSignal, ReadSignal};
    /// # use leptos_store::store::Store;
    /// # use leptos_store::composition::RootStore;
    /// # #[derive(Clone, Debug, Default)]
    /// # struct AuthState;
    /// # #[derive(Clone)]
    /// # struct AuthStore { state: RwSignal<AuthState> }
    /// # impl AuthStore { fn new() -> Self { Self { state: RwSignal::new(AuthState) } } }
    /// # impl Store for AuthStore {
    /// #     type State = AuthState;
    /// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
    /// # }
    /// # #[derive(Clone, Debug, Default)]
    /// # struct CartState;
    /// # #[derive(Clone)]
    /// # struct CartStore { state: RwSignal<CartState> }
    /// # impl CartStore { fn new() -> Self { Self { state: RwSignal::new(CartState) } } }
    /// # impl Store for CartStore {
    /// #     type State = CartState;
    /// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
    /// # }
    /// let root = RootStore::builder()
    ///     .with_store(AuthStore::new())
    ///     .with_store_after::<_, AuthStore>(CartStore::new())  // cart after auth
    ///     .build();
    /// ```
    pub fn with_store_after<S: Store + 'static, Dep: Store + 'static>(mut self, store: S) -> Self {
        let store_type = TypeId::of::<S>();
        let dep_type = TypeId::of::<Dep>();

        self.stores.insert(store_type, Arc::new(store));

        // Record ordering: dep should come before store
        // Ensure dep is in the order list first
        if !self.initialization_order.contains(&dep_type) {
            self.initialization_order.push(dep_type);
        }
        if !self.initialization_order.contains(&store_type) {
            self.initialization_order.push(store_type);
        }

        self
    }

    /// Add a store wrapped in Arc.
    pub fn with_arc_store<S: Store + 'static>(mut self, store: Arc<S>) -> Self {
        self.stores.insert(TypeId::of::<S>(), store);
        self
    }

    /// Get the declared initialization order.
    ///
    /// Returns `TypeId`s in the order they should be initialized
    /// (dependencies first). Only includes stores added via
    /// [`with_store_after`](Self::with_store_after).
    pub fn initialization_order(&self) -> &[TypeId] {
        &self.initialization_order
    }

    /// Build the root store.
    pub fn build(self) -> RootStore {
        RootStore {
            stores: Arc::new(self.stores),
        }
    }
}

// ============================================================================
// Store Dependencies
// ============================================================================

/// A store that depends on other stores.
///
/// This pattern allows a store to access other stores' state
/// for cross-domain operations.
///
/// # Example
///
/// ```rust
/// # use leptos::prelude::{RwSignal, ReadSignal};
/// # use leptos_store::store::Store;
/// use leptos_store::composition::StoreDependency;
/// # #[derive(Clone, Debug, Default)]
/// # struct AuthState { authenticated: bool }
/// # #[derive(Clone)]
/// # struct AuthStore { state: RwSignal<AuthState> }
/// # impl AuthStore {
/// #     fn is_authenticated(&self) -> bool { true }
/// # }
/// # impl Store for AuthStore {
/// #     type State = AuthState;
/// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
/// # }
/// # #[derive(Clone, Debug, Default)]
/// # struct CartState;
///
/// struct CartStore {
///     state: RwSignal<CartState>,
///     auth: StoreDependency<AuthStore>,
/// }
///
/// impl CartStore {
///     pub fn checkout(&self) {
///         // Check if user is authenticated
///         if let Some(auth) = self.auth.get() {
///             if auth.is_authenticated() {
///                 // Process checkout
///             }
///         }
///     }
/// }
/// ```
pub struct StoreDependency<S: Store> {
    store: Option<S>,
    _marker: PhantomData<S>,
}

impl<S: Store> Default for StoreDependency<S> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: Store> Clone for StoreDependency<S> {
    fn clone(&self) -> Self {
        Self {
            store: self.store.clone(),
            _marker: PhantomData,
        }
    }
}

impl<S: Store> StoreDependency<S> {
    /// Create an unresolved dependency.
    pub fn new() -> Self {
        Self {
            store: None,
            _marker: PhantomData,
        }
    }

    /// Create a resolved dependency.
    pub fn resolved(store: S) -> Self {
        Self {
            store: Some(store),
            _marker: PhantomData,
        }
    }

    /// Resolve the dependency with a store instance.
    pub fn resolve(&mut self, store: S) {
        self.store = Some(store);
    }

    /// Get the store if resolved.
    pub fn get(&self) -> Option<&S> {
        self.store.as_ref()
    }

    /// Check if the dependency is resolved.
    pub fn is_resolved(&self) -> bool {
        self.store.is_some()
    }

    /// Get the store or panic.
    pub fn expect(&self) -> &S {
        self.store.as_ref().unwrap_or_else(|| {
            panic!(
                "Store dependency {} is not resolved",
                std::any::type_name::<S>()
            )
        })
    }
}

impl<S: Store + fmt::Debug> fmt::Debug for StoreDependency<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoreDependency")
            .field("resolved", &self.is_resolved())
            .field("store", &self.store)
            .finish()
    }
}

// ============================================================================
// Derived Views
// ============================================================================

/// A derived view combining data from multiple stores.
///
/// Derived views are read-only computed values that combine state
/// from multiple stores into a single reactive value.
///
/// # Example
///
/// ```rust,ignore
/// use leptos_store::composition::*;
///
/// let dashboard = DerivedView::new()
///     .with_source(move || auth_store.display_name())
///     .with_source(move || cart_store.item_count())
///     .compute(|(name, count)| {
///         DashboardData { user: name, cart_items: count }
///     });
/// ```
pub struct DerivedView<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    value: Memo<T>,
}

impl<T> Clone for DerivedView<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for DerivedView<T> where T: Clone + Send + Sync + PartialEq + 'static {}

impl<T> DerivedView<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    /// Create a derived view from a computation function.
    pub fn new(f: impl Fn() -> T + Send + Sync + 'static) -> Self {
        Self {
            value: Memo::new(move |_prev| f()),
        }
    }

    /// Get the current value.
    pub fn get(&self) -> T {
        self.value.get()
    }

    /// Access the value with a closure.
    pub fn with<U>(&self, f: impl FnOnce(&T) -> U) -> U {
        self.value.with(f)
    }

    /// Get the underlying memo.
    pub fn memo(&self) -> Memo<T> {
        self.value
    }
}

impl<T> fmt::Debug for DerivedView<T>
where
    T: Clone + Send + Sync + PartialEq + fmt::Debug + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DerivedView")
            .field("value", &self.value.get())
            .finish()
    }
}

// ============================================================================
// Multi-Store Selector
// ============================================================================

/// A selector that combines data from multiple stores.
///
/// Selectors provide a way to efficiently compute derived state
/// from multiple stores with automatic memoization.
pub struct MultiStoreSelector<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    value: Memo<T>,
}

impl<T> Clone for MultiStoreSelector<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for MultiStoreSelector<T> where T: Clone + Send + Sync + PartialEq + 'static {}

impl<T> MultiStoreSelector<T>
where
    T: Clone + Send + Sync + PartialEq + 'static,
{
    /// Create a selector from two stores.
    pub fn from_two<S1, S2, F>(store1: &S1, store2: &S2, selector: F) -> Self
    where
        S1: Store,
        S2: Store,
        F: Fn(&S1::State, &S2::State) -> T + Send + Sync + 'static,
    {
        let s1 = store1.state();
        let s2 = store2.state();

        Self {
            value: Memo::new(move |_prev| {
                let state1 = s1.get();
                let state2 = s2.get();
                selector(&state1, &state2)
            }),
        }
    }

    /// Create a selector from three stores.
    pub fn from_three<S1, S2, S3, F>(store1: &S1, store2: &S2, store3: &S3, selector: F) -> Self
    where
        S1: Store,
        S2: Store,
        S3: Store,
        F: Fn(&S1::State, &S2::State, &S3::State) -> T + Send + Sync + 'static,
    {
        let s1 = store1.state();
        let s2 = store2.state();
        let s3 = store3.state();

        Self {
            value: Memo::new(move |_prev| {
                let state1 = s1.get();
                let state2 = s2.get();
                let state3 = s3.get();
                selector(&state1, &state2, &state3)
            }),
        }
    }

    /// Get the current value.
    pub fn get(&self) -> T {
        self.value.get()
    }

    /// Access the value with a closure.
    pub fn with<U>(&self, f: impl FnOnce(&T) -> U) -> U {
        self.value.with(f)
    }
}

// ============================================================================
// Store Group
// ============================================================================

/// A group of related stores.
///
/// Store groups provide a way to organize stores by domain or feature
/// while maintaining type-safe access.
pub struct StoreGroup {
    name: &'static str,
    stores: HashMap<TypeId, Arc<dyn AnyStore>>,
}

impl StoreGroup {
    /// Create a new store group.
    pub fn new(name: &'static str) -> Self {
        Self {
            name,
            stores: HashMap::new(),
        }
    }

    /// Add a store to the group.
    pub fn add<S: Store + 'static>(&mut self, store: S) {
        self.stores.insert(TypeId::of::<S>(), Arc::new(store));
    }

    /// Get a store from the group.
    pub fn get<S: Store + 'static>(&self) -> Option<&S> {
        self.stores
            .get(&TypeId::of::<S>())
            .and_then(|s| s.as_any().downcast_ref::<S>())
    }

    /// Get the group name.
    pub fn name(&self) -> &'static str {
        self.name
    }

    /// Get the number of stores in the group.
    pub fn len(&self) -> usize {
        self.stores.len()
    }

    /// Check if the group is empty.
    pub fn is_empty(&self) -> bool {
        self.stores.is_empty()
    }
}

impl fmt::Debug for StoreGroup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoreGroup")
            .field("name", &self.name)
            .field("count", &self.stores.len())
            .finish()
    }
}

// ============================================================================
// Context Helpers
// ============================================================================

/// Provide a root store to the component tree.
pub fn provide_root_store(root: RootStore) {
    provide_context(root);
}

/// Access the root store from context.
pub fn use_root_store() -> RootStore {
    use_context::<RootStore>().expect("RootStore not found in context")
}

/// Try to access the root store from context.
pub fn try_use_root_store() -> Result<RootStore, StoreError> {
    use_context::<RootStore>()
        .ok_or_else(|| StoreError::ContextNotAvailable("RootStore not found".to_string()))
}

/// Access a specific store from the root store context.
pub fn use_store_from_root<S>() -> S
where
    S: Store + Clone + 'static,
{
    let root = use_root_store();
    root.get::<S>().cloned().unwrap_or_else(|| {
        panic!(
            "Store {} not found in RootStore",
            std::any::type_name::<S>()
        )
    })
}

// ============================================================================
// Tests
// ============================================================================

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

    #[derive(Clone, Debug, Default)]
    struct AuthState {
        user: Option<String>,
    }

    #[derive(Clone)]
    struct AuthStore {
        state: RwSignal<AuthState>,
    }

    impl AuthStore {
        fn new() -> Self {
            Self {
                state: RwSignal::new(AuthState::default()),
            }
        }

        #[allow(dead_code)]
        fn is_authenticated(&self) -> bool {
            self.state.with(|s| s.user.is_some())
        }
    }

    impl Store for AuthStore {
        type State = AuthState;

        fn state(&self) -> ReadSignal<Self::State> {
            self.state.read_only()
        }
    }

    #[derive(Clone, Debug, Default)]
    struct CartState {
        items: Vec<String>,
    }

    #[derive(Clone)]
    struct CartStore {
        state: RwSignal<CartState>,
    }

    impl CartStore {
        fn new() -> Self {
            Self {
                state: RwSignal::new(CartState::default()),
            }
        }

        #[allow(dead_code)]
        fn item_count(&self) -> usize {
            self.state.with(|s| s.items.len())
        }
    }

    impl Store for CartStore {
        type State = CartState;

        fn state(&self) -> ReadSignal<Self::State> {
            self.state.read_only()
        }
    }

    #[test]
    fn test_root_store_builder() {
        let root = RootStore::builder()
            .with_store(AuthStore::new())
            .with_store(CartStore::new())
            .build();

        assert_eq!(root.len(), 2);
        assert!(root.contains::<AuthStore>());
        assert!(root.contains::<CartStore>());
    }

    #[test]
    fn test_root_store_get() {
        let root = RootStore::builder().with_store(AuthStore::new()).build();

        let auth = root.get::<AuthStore>();
        assert!(auth.is_some());

        let cart = root.get::<CartStore>();
        assert!(cart.is_none());
    }

    #[test]
    fn test_root_store_expect() {
        let root = RootStore::builder().with_store(AuthStore::new()).build();

        let _auth = root.expect::<AuthStore>();
        // Should not panic
    }

    #[test]
    #[should_panic(expected = "not found")]
    fn test_root_store_expect_missing() {
        let root = RootStore::new();
        let _auth = root.expect::<AuthStore>();
    }

    #[test]
    fn test_store_dependency() {
        let mut dep: StoreDependency<AuthStore> = StoreDependency::new();
        assert!(!dep.is_resolved());

        dep.resolve(AuthStore::new());
        assert!(dep.is_resolved());
        assert!(dep.get().is_some());
    }

    #[test]
    fn test_store_dependency_resolved() {
        let dep = StoreDependency::resolved(AuthStore::new());
        assert!(dep.is_resolved());
    }

    #[test]
    fn test_derived_view() {
        let view = DerivedView::new(|| 42);
        assert_eq!(view.get(), 42);
    }

    #[test]
    fn test_store_group() {
        let mut group = StoreGroup::new("domain");
        assert!(group.is_empty());

        group.add(AuthStore::new());
        assert_eq!(group.len(), 1);
        assert_eq!(group.name(), "domain");

        let auth = group.get::<AuthStore>();
        assert!(auth.is_some());
    }

    #[test]
    fn test_composite_store_trait() {
        let root = RootStore::builder()
            .with_store(AuthStore::new())
            .with_store(CartStore::new())
            .build();

        let stores = root.stores();
        assert_eq!(stores.len(), 2);

        assert!(root.contains::<AuthStore>());
        assert!(!root.is_empty());
    }

    #[test]
    fn test_root_store_store_names() {
        let root = RootStore::builder().with_store(AuthStore::new()).build();

        let names = root.store_names();
        assert_eq!(names.len(), 1);
        assert!(names[0].contains("AuthStore"));
    }

    #[test]
    fn test_multi_store_selector() {
        let auth = AuthStore::new();
        let cart = CartStore::new();

        let selector = MultiStoreSelector::from_two(&auth, &cart, |auth_state, cart_state| {
            (auth_state.user.is_some(), cart_state.items.len())
        });

        let (is_auth, count) = selector.get();
        assert!(!is_auth);
        assert_eq!(count, 0);
    }

    #[test]
    fn test_with_store_after() {
        let root = RootStore::builder()
            .with_store(AuthStore::new())
            .with_store_after::<_, AuthStore>(CartStore::new())
            .build();

        assert!(root.contains::<AuthStore>());
        assert!(root.contains::<CartStore>());
        assert_eq!(root.len(), 2);
    }

    #[test]
    fn test_initialization_order() {
        let builder = RootStore::builder()
            .with_store(AuthStore::new())
            .with_store_after::<_, AuthStore>(CartStore::new());

        let order = builder.initialization_order();
        assert_eq!(order.len(), 2);

        // AuthStore should come before CartStore
        let auth_pos = order
            .iter()
            .position(|t| *t == TypeId::of::<AuthStore>())
            .unwrap();
        let cart_pos = order
            .iter()
            .position(|t| *t == TypeId::of::<CartStore>())
            .unwrap();
        assert!(auth_pos < cart_pos);
    }

    #[test]
    fn test_initialization_order_empty_without_after() {
        let builder = RootStore::builder()
            .with_store(AuthStore::new())
            .with_store(CartStore::new());

        // No ordering constraints declared
        assert!(builder.initialization_order().is_empty());
    }
}