what-core 1.6.0

Core framework for What - an HTML-first web framework powered by Rust
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
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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! Component registry and rendering system
//!
//! Handles custom component definitions and rendering.
//!
//! ## Component Format
//!
//! Components can be defined in two ways:
//!
//! ### New format (filename-based, recommended):
//! ```html
//! <!-- components/nav.html → <what-nav> -->
//! <what>
//! props = "active, theme"
//! defaults.active = "home"
//! defaults.theme = "light"
//! </what>
//! <nav class="navigation" data-active="#active#">
//!   <slot/>
//! </nav>
//! ```
//!
//! ### Legacy format (with wrapper tag):
//! ```html
//! <component name="card" props="title">
//!   <div class="card"><h2>#title#</h2><slot/></div>
//! </component>
//! ```

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use crate::parser::{parse_attributes, parse_what_file, replace_variables};
use crate::{Error, Result};

/// A custom component definition
#[derive(Debug, Clone)]
pub struct Component {
    /// Component name (e.g., "what-card", "what-modal")
    pub name: String,
    /// Expected props
    pub props: Vec<String>,
    /// Default values for props
    pub defaults: HashMap<String, String>,
    /// Template content
    pub template: String,
}

impl Component {
    /// Load a component from an HTML template file (legacy format with wrapper tag)
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let content = std::fs::read_to_string(&path)?;
        Self::parse(&content)
    }

    /// Load a component from a file, deriving the name from the filename
    ///
    /// This is the new recommended format where:
    /// - Filename becomes the component name: `nav.html` → `nav`
    /// - Props and defaults are defined in a `<what>` block
    /// - Template content is everything outside the `<what>` block
    pub fn from_file_with_name(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path)?;

        // Derive name from filename (without extension)
        let name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| Error::Component("Invalid filename".to_string()))?
            .to_string();

        Self::parse_with_name(&content, name)
    }

    /// Parse component content with a provided name (filename-based)
    ///
    /// Supports both new `<what>` block format and legacy wrapper tag format.
    pub fn parse_with_name(content: &str, name: String) -> Result<Self> {
        // Check for legacy wrapper tag format first
        if content.contains("<component") || content.contains("<tag") {
            let mut component = Self::parse(content)?;
            // Override name with provided filename-based name
            component.name = name;
            return Ok(component);
        }

        // New format: <what> block + template content
        Self::parse_what_format(content, name)
    }

    /// Parse new format with `<what>` block for props/defaults
    fn parse_what_format(content: &str, name: String) -> Result<Self> {
        let mut props = Vec::new();
        let mut defaults = HashMap::new();
        let mut template = content.to_string();

        // Check for <what> block
        if let Some(what_start) = content.find("<what>") {
            if let Some(what_end) = content.find("</what>") {
                let what_content = &content[what_start + 6..what_end];
                template = format!(
                    "{}{}",
                    content[..what_start].trim(),
                    content[what_end + 7..].trim()
                )
                .trim()
                .to_string();

                // Parse the <what> block using the parser
                let config = parse_what_file(what_content);

                // Extract props
                if let Some(props_value) = config.values.get("props") {
                    if let Some(props_str) = props_value.as_str() {
                        props = props_str
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect();
                    }
                }

                // Extract defaults (keys starting with "defaults.")
                for (key, value) in &config.values {
                    if let Some(prop_name) = key.strip_prefix("defaults.") {
                        if let Some(default_value) = value.as_str() {
                            defaults.insert(prop_name.to_string(), default_value.to_string());
                        } else {
                            // Convert other types to string
                            defaults.insert(prop_name.to_string(), value.to_string());
                        }
                    }
                }
            }
        }

        // Also check for self-closing <what ... /> format
        if let Some(what_start) = content.find("<what ") {
            if let Some(what_end) = content[what_start..].find("/>") {
                let what_attrs = &content[what_start + 5..what_start + what_end];
                template = format!(
                    "{}{}",
                    content[..what_start].trim(),
                    content[what_start + what_end + 2..].trim()
                )
                .trim()
                .to_string();

                let attrs = parse_attributes(what_attrs);

                // Extract props from attribute
                if let Some(props_str) = attrs.get("props") {
                    props = props_str
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                }

                // Extract defaults from attribute (format: "prop: value, prop2: value2")
                if let Some(defaults_str) = attrs.get("defaults") {
                    for pair in defaults_str.split(',') {
                        if let Some(colon_idx) = pair.find(':') {
                            let key = pair[..colon_idx].trim().to_string();
                            let value = pair[colon_idx + 1..].trim().to_string();
                            defaults.insert(key, value);
                        }
                    }
                }
            }
        }

        Ok(Self {
            name,
            props,
            defaults,
            template,
        })
    }

    /// Parse a component definition from HTML template content (legacy format)
    ///
    /// Expected format:
    /// ```html
    /// <component name="card" props="title, slug">
    ///   <article class="card">
    ///     <h3>#title#</h3>
    ///     <slot/>
    ///   </article>
    /// </component>
    /// ```
    pub fn parse(content: &str) -> Result<Self> {
        // Support both <component> and legacy <tag> elements
        let (start_tag, end_tag) = if content.contains("<component") {
            ("<component", "</component>")
        } else {
            ("<tag", "</tag>")
        };

        let tag_start = content
            .find(start_tag)
            .ok_or_else(|| Error::Component(format!("Missing {} element", start_tag)))?;
        let tag_end = content[tag_start..]
            .find('>')
            .ok_or_else(|| Error::Component(format!("Malformed {} element", start_tag)))?;

        let tag_attrs = &content[tag_start..tag_start + tag_end + 1];
        let attrs = parse_attributes(tag_attrs);

        let name = attrs
            .get("name")
            .ok_or_else(|| Error::Component(format!("Missing 'name' attribute on {}", start_tag)))?
            .clone();

        let props: Vec<String> = attrs
            .get("props")
            .map(|p| p.split(',').map(|s| s.trim().to_string()).collect())
            .unwrap_or_default();

        // Parse defaults from attribute (format: "prop: value, prop2: value2")
        let mut defaults = HashMap::new();
        if let Some(defaults_str) = attrs.get("defaults") {
            for pair in defaults_str.split(',') {
                if let Some(colon_idx) = pair.find(':') {
                    let key = pair[..colon_idx].trim().to_string();
                    let value = pair[colon_idx + 1..].trim().to_string();
                    defaults.insert(key, value);
                }
            }
        }

        // Extract template content between start and end tags
        let content_start = tag_start + tag_end + 1;
        let content_end = content
            .rfind(end_tag)
            .ok_or_else(|| Error::Component(format!("Missing {}", end_tag)))?;

        let template = content[content_start..content_end].trim().to_string();

        Ok(Self {
            name,
            props,
            defaults,
            template,
        })
    }

    /// Render the component with given props and children
    ///
    /// Priority order (highest to lowest):
    /// 1. Passed props (from usage)
    /// 2. Defaults (from component definition)
    /// 3. Empty string (for undeclared props)
    pub fn render(
        &self,
        props: &HashMap<String, String>,
        children: Option<&str>,
        context: &HashMap<String, serde_json::Value>,
    ) -> String {
        // Build context from props
        let mut render_context = context.clone();

        // Set default empty string for all declared props (lowest priority)
        for prop_name in &self.props {
            if !props.contains_key(prop_name) && !self.defaults.contains_key(prop_name) {
                render_context.insert(prop_name.clone(), serde_json::Value::String(String::new()));
            }
        }

        // Apply defaults (medium priority)
        for (key, value) in &self.defaults {
            if !props.contains_key(key) {
                render_context.insert(key.clone(), serde_json::Value::String(value.clone()));
            }
        }

        // Set provided prop values (highest priority - overrides defaults)
        // JSON array/object props are parsed into serde_json::Value for loop resolution
        for (key, value) in props {
            let trimmed = value.trim();
            if (trimmed.starts_with('[') && trimmed.ends_with(']'))
                || (trimmed.starts_with('{') && trimmed.ends_with('}'))
            {
                // Parse JSON props so engine loops can resolve them
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed) {
                    render_context.insert(key.clone(), parsed);
                } else {
                    render_context.insert(key.clone(), serde_json::Value::String(value.clone()));
                }
                continue;
            }
            render_context.insert(key.clone(), serde_json::Value::String(value.clone()));
        }

        // Process loops in the component template before variable replacement
        // This allows JSON array props to be iterated via <loop data="#var#" as="alias">
        let processed_template = Self::process_component_loops(&self.template, &render_context);

        // Replace variables in template
        let mut output = replace_variables(&processed_template, &render_context);

        // Replace <slot/> with children content
        if let Some(children_content) = children {
            output = output.replace("<slot/>", children_content);
            output = output.replace("<slot />", children_content);
        } else {
            output = output.replace("<slot/>", "");
            output = output.replace("<slot />", "");
        }

        output
    }

    /// Process <loop> tags within a component template using the component's context.
    /// This handles JSON array props that are passed to components.
    fn process_component_loops(
        template: &str,
        context: &HashMap<String, serde_json::Value>,
    ) -> String {
        use regex::Regex;
        use std::sync::LazyLock;

        static LOOP_RE: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new(r#"(?s)<loop\s+data="([^"]+)"\s+as="([^"]+)"\s*>(.*?)</loop>"#).unwrap()
        });

        let mut output = template.to_string();

        // Process all loop tags (iterate because loops may be nested)
        for _ in 0..10 {
            let prev = output.clone();
            output = LOOP_RE
                .replace_all(&output, |caps: &regex::Captures| {
                    let data_expr = &caps[1];
                    let alias = &caps[2];
                    let body = &caps[3];

                    // Extract variable name from #var# syntax
                    let var_name = data_expr.trim_matches('#');
                    let parts: Vec<&str> = var_name.split('.').collect();

                    // Resolve from context
                    let data = if let Some(first) = parts.first() {
                        let mut current = context.get(*first);
                        for part in parts.iter().skip(1) {
                            current = current.and_then(|v| {
                                if let serde_json::Value::Object(obj) = v {
                                    obj.get(*part)
                                } else {
                                    None
                                }
                            });
                        }
                        current
                    } else {
                        None
                    };

                    match data {
                        Some(serde_json::Value::Array(items)) => {
                            items
                                .iter()
                                .enumerate()
                                .map(|(index, item)| {
                                    let mut result = body.to_string();
                                    // Replace #alias.field# patterns
                                    if let serde_json::Value::Object(obj) = item {
                                        for (key, val) in obj {
                                            let pattern = format!("#{}{}{}#", alias, ".", key);
                                            let replacement = match val {
                                                serde_json::Value::String(s) => s.clone(),
                                                serde_json::Value::Number(n) => n.to_string(),
                                                serde_json::Value::Bool(b) => b.to_string(),
                                                other => other.to_string(),
                                            };
                                            result = result.replace(&pattern, &replacement);
                                        }
                                    }
                                    // Replace #alias# with the item itself
                                    let alias_pattern = format!("#{}#", alias);
                                    let alias_val = match item {
                                        serde_json::Value::String(s) => s.clone(),
                                        serde_json::Value::Number(n) => n.to_string(),
                                        serde_json::Value::Bool(b) => b.to_string(),
                                        other => other.to_string(),
                                    };
                                    result = result.replace(&alias_pattern, &alias_val);
                                    // Replace index variables
                                    result = result.replace("#index#", &index.to_string());
                                    result = result.replace("#index1#", &(index + 1).to_string());
                                    result
                                })
                                .collect::<Vec<_>>()
                                .join("\n")
                        }
                        _ => {
                            // Can't resolve — leave the loop tag for the engine to handle
                            caps[0].to_string()
                        }
                    }
                })
                .to_string();

            if output == prev {
                break;
            }
        }

        output
    }
}

/// Registry of all available components
#[derive(Debug, Default, Clone)]
pub struct ComponentRegistry {
    components: HashMap<String, Arc<Component>>,
}

impl ComponentRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a component
    pub fn register(&mut self, component: Component) {
        self.components
            .insert(component.name.clone(), Arc::new(component));
    }

    /// Get a component by name
    pub fn get(&self, name: &str) -> Option<Arc<Component>> {
        self.components.get(name).cloned()
    }

    /// Get all registered component names
    pub fn component_names(&self) -> Vec<String> {
        self.components.keys().cloned().collect()
    }

    /// Load all components from a directory with what- prefix
    ///
    /// Files in /components/card.html become <what-card>
    /// Supports both new format (filename-based) and legacy format (wrapper tag)
    /// Recursively loads from subdirectories (flat namespace - folders for organization only)
    pub fn load_from_directory(&mut self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();
        if !path.exists() {
            return Ok(());
        }

        self.load_from_directory_recursive(path)
    }

    /// Recursively load components from a directory
    fn load_from_directory_recursive(&mut self, path: &Path) -> Result<()> {
        for entry in std::fs::read_dir(path)? {
            let entry = entry?;
            let file_path = entry.path();

            if file_path.is_dir() {
                // Recursively load from subdirectories
                self.load_from_directory_recursive(&file_path)?;
            } else if file_path.extension().map(|e| e == "html").unwrap_or(false) {
                // Use new filename-based loading
                match Component::from_file_with_name(&file_path) {
                    Ok(mut component) => {
                        // Apply what- prefix
                        component.name = format!("what-{}", component.name);
                        tracing::info!("Loaded component: {}", component.name);
                        self.register(component);
                    }
                    Err(e) => {
                        tracing::warn!("Failed to load component from {:?}: {}", file_path, e);
                    }
                }
            }
        }

        Ok(())
    }

    /// Register built-in components
    pub fn register_builtins(&mut self) {
        // <page> component - wraps content with HTML structure (shorthand, no prefix)
        let page_template = r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>#title#</title>
    <link rel="stylesheet" href="/static/what.css">
</head>
<body>
    <slot/>
    <script src="/static/what.js"></script>
</body>
</html>"#
            .to_string();

        // Register as <page> (primary, for user convenience)
        self.register(Component {
            name: "page".to_string(),
            props: vec!["title".to_string()],
            defaults: HashMap::new(),
            template: page_template.clone(),
        });

        // Also register as <what-page> for consistency
        self.register(Component {
            name: "what-page".to_string(),
            props: vec!["title".to_string()],
            defaults: HashMap::new(),
            template: page_template,
        });

        // <what-modal> component - modal dialog with backdrop and close button
        self.register(Component {
            name: "what-modal".to_string(),
            props: vec!["id".to_string(), "title".to_string(), "size".to_string()],
            defaults: {
                let mut d = HashMap::new();
                d.insert("size".to_string(), String::new());
                d
            },
            template: r##"<div id="#id#" class="modal-backdrop">
  <div class="modal #size#">
    <div class="modal-header">
      <h3 class="modal-title">#title#</h3>
      <button type="button" class="modal-close" w-modal-close aria-label="Close">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
    <div class="modal-body">
      <slot/>
    </div>
  </div>
</div>"##.to_string(),
        });

        // <what-drawer> component - slide-in panel with backdrop
        self.register(Component {
            name: "what-drawer".to_string(),
            props: vec!["id".to_string(), "title".to_string(), "position".to_string(), "size".to_string()],
            defaults: {
                let mut d = HashMap::new();
                d.insert("position".to_string(), "right".to_string());
                d
            },
            template: r##"<div id="#id#" class="drawer-backdrop">
  <div class="drawer drawer-#position# #size#">
    <div class="drawer-header">
      <h3 class="drawer-title">#title#</h3>
      <button type="button" class="drawer-close" w-modal-close aria-label="Close">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
    <div class="drawer-body">
      <slot/>
    </div>
  </div>
</div>"##.to_string(),
        });

        // <what-tabs> component - tab container
        self.register(Component {
            name: "what-tabs".to_string(),
            props: vec!["id".to_string(), "style".to_string()],
            defaults: {
                let mut d = HashMap::new();
                d.insert("style".to_string(), String::new());
                d
            },
            template: r##"<div class="tab-list #style#" id="#id#-tabs">
  <slot/>
</div>"##
                .to_string(),
        });

        // <what-accordion> component - native <details>/<summary>, zero JS
        self.register(Component {
            name: "what-accordion".to_string(),
            props: vec![
                "id".to_string(),
                "title".to_string(),
                "expanded".to_string(),
            ],
            defaults: {
                let mut d = HashMap::new();
                d.insert("expanded".to_string(), String::new());
                d
            },
            template: r###"<details id="#id#" class="w-accordion"<if expanded> open</if>>
  <summary class="w-accordion-header">
    <span class="font-semibold">#title#</span>
    <span class="w-accordion-icon">&#9660;</span>
  </summary>
  <div class="w-accordion-content py-3">
    <slot/>
  </div>
</details>"###
                .to_string(),
        });

        // <what-dropdown> component - native details-based dropdown menu
        self.register(Component {
            name: "what-dropdown".to_string(),
            props: vec![
                "label".to_string(),
                "align".to_string(),
                "variant".to_string(),
            ],
            defaults: {
                let mut d = HashMap::new();
                d.insert("label".to_string(), "Menu".to_string());
                d.insert("variant".to_string(), "btn btn-secondary".to_string());
                d.insert("align".to_string(), String::new());
                d
            },
            template: r##"<details class="dropdown #align#">
  <summary class="#variant#">
    #label# <span style="font-size:0.75em">&#9662;</span>
  </summary>
  <div class="dropdown-menu">
    <slot/>
  </div>
</details>"##
                .to_string(),
        });

        // <what-tooltip> component - CSS-positioned hover tooltip
        self.register(Component {
            name: "what-tooltip".to_string(),
            props: vec!["text".to_string(), "position".to_string()],
            defaults: {
                let mut d = HashMap::new();
                d.insert("position".to_string(), "top".to_string());
                d
            },
            template: r##"<span data-tooltip="#text#" data-tooltip-position="#position#" style="cursor:help">
  <slot/>
</span>"##.to_string(),
        });

        // <what-pagination> component - page navigation links
        self.register(Component {
            name: "what-pagination".to_string(),
            props: vec![
                "base_url".to_string(),
                "current".to_string(),
                "total".to_string(),
            ],
            defaults: {
                let mut d = HashMap::new();
                d.insert("current".to_string(), "1".to_string());
                d.insert("total".to_string(), "5".to_string());
                d
            },
            template: r##"<nav class="navigation-pagination">
  <slot/>
</nav>"##
                .to_string(),
        });

        // <what-wire-status> component - wired connection status indicator
        // Shows a green/grey dot and optionally the number of connected users
        self.register(Component {
            name: "what-wire-status".to_string(),
            props: vec!["show-users".to_string()],
            defaults: {
                let mut d = HashMap::new();
                d.insert("show-users".to_string(), "false".to_string());
                d
            },
            template: r##"<span class="w-wire-status" data-show-users="#show-users#"><span class="w-wire-dot"></span><span class="w-wire-users" w-bind="wired._clients"></span></span>"##.to_string(),
        });
    }
}

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

    #[test]
    fn test_parse_component() {
        let content = r##"
<component name="greeting" props="name, title">
    <div class="greeting">
        <h1>#title#</h1>
        <p>Hello, #name#!</p>
        <slot/>
    </div>
</component>
"##;
        let component = Component::parse(content).unwrap();
        assert_eq!(component.name, "greeting");
        assert_eq!(component.props, vec!["name", "title"]);
        assert!(component.template.contains("#title#"));
        assert!(component.defaults.is_empty());
    }

    #[test]
    fn test_parse_legacy_tag() {
        // Still support <tag> for backwards compatibility
        let content = r##"
<tag name="greeting" props="name, title">
    <div class="greeting">
        <h1>#title#</h1>
        <p>Hello, #name#!</p>
        <slot/>
    </div>
</tag>
"##;
        let component = Component::parse(content).unwrap();
        assert_eq!(component.name, "greeting");
    }

    #[test]
    fn test_parse_component_with_defaults() {
        let content = r##"
<component name="nav" props="active, theme" defaults="active: home, theme: light">
    <nav data-active="#active#" data-theme="#theme#"><slot/></nav>
</component>
"##;
        let component = Component::parse(content).unwrap();
        assert_eq!(component.name, "nav");
        assert_eq!(component.props, vec!["active", "theme"]);
        assert_eq!(component.defaults.get("active"), Some(&"home".to_string()));
        assert_eq!(component.defaults.get("theme"), Some(&"light".to_string()));
    }

    #[test]
    fn test_render_component() {
        let component = Component {
            name: "test".to_string(),
            props: vec!["name".to_string()],
            defaults: HashMap::new(),
            template: "<p>Hello #name#!</p><slot/>".to_string(),
        };

        let mut props = HashMap::new();
        props.insert("name".to_string(), "World".to_string());

        let result = component.render(&props, Some("<span>Child</span>"), &HashMap::new());
        assert_eq!(result, "<p>Hello World!</p><span>Child</span>");
    }

    #[test]
    fn test_render_component_with_defaults() {
        let mut defaults = HashMap::new();
        defaults.insert("theme".to_string(), "dark".to_string());
        defaults.insert("size".to_string(), "medium".to_string());

        let component = Component {
            name: "test".to_string(),
            props: vec!["theme".to_string(), "size".to_string()],
            defaults,
            template: "<div class=\"#theme# #size#\"><slot/></div>".to_string(),
        };

        // No props passed - should use defaults
        let result = component.render(&HashMap::new(), Some("Content"), &HashMap::new());
        assert_eq!(result, "<div class=\"dark medium\">Content</div>");

        // Override one default
        let mut props = HashMap::new();
        props.insert("theme".to_string(), "light".to_string());
        let result = component.render(&props, Some("Content"), &HashMap::new());
        assert_eq!(result, "<div class=\"light medium\">Content</div>");

        // Override both defaults
        let mut props = HashMap::new();
        props.insert("theme".to_string(), "blue".to_string());
        props.insert("size".to_string(), "large".to_string());
        let result = component.render(&props, Some("Content"), &HashMap::new());
        assert_eq!(result, "<div class=\"blue large\">Content</div>");
    }

    #[test]
    fn test_parse_what_format() {
        let content = r##"<what>
props = "active, theme"
defaults.active = "home"
defaults.theme = "light"
</what>
<nav data-active="#active#" data-theme="#theme#">
    <slot/>
</nav>"##;

        let component = Component::parse_with_name(content, "nav".to_string()).unwrap();
        assert_eq!(component.name, "nav");
        assert_eq!(component.props, vec!["active", "theme"]);
        assert_eq!(component.defaults.get("active"), Some(&"home".to_string()));
        assert_eq!(component.defaults.get("theme"), Some(&"light".to_string()));
        println!("Template: '{}'", component.template);
        assert!(
            component.template.contains("data-active="),
            "Template should contain data-active=, got: {}",
            component.template
        );
        assert!(!component.template.contains("<what>"));
    }

    #[test]
    fn test_parse_what_format_real_nav() {
        // Test with exact content like the actual nav.html file
        let content = r##"<what>
props = "active"
defaults.active = "home"
</what>
<header class="navigation-top navigation-top-sticky bg-white shadow-sm">
  <a href="/" class="nav-brand">What Framework?</a>
  <nav class="nav-links" data-active="#active#">
    <a href="/" class="nav-link" data-page="home">Home</a>
  </nav>
</header>
"##;

        let component = Component::parse_with_name(content, "nav".to_string()).unwrap();
        println!("Nav component template: '{}'", component.template);
        assert_eq!(component.name, "nav");
        assert_eq!(component.props, vec!["active"]);
        assert_eq!(component.defaults.get("active"), Some(&"home".to_string()));
        assert!(
            component.template.contains("<header"),
            "Template should contain <header>, got: '{}'",
            component.template
        );
        assert!(
            component.template.contains("nav-brand"),
            "Template should contain nav-brand"
        );
        assert!(
            !component.template.contains("<what>"),
            "Template should not contain <what>"
        );
    }

    #[test]
    fn test_load_real_nav_from_file() {
        // Test loading the actual nav.html file from demo directory
        let nav_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap() // crates/
            .parent()
            .unwrap() // root
            .join("examples/demo/components/nav.html");

        println!("Loading nav from: {:?}", nav_path);

        let component = Component::from_file_with_name(&nav_path).expect("Failed to load nav.html");
        println!("Loaded component name: {}", component.name);
        println!("Props: {:?}", component.props);
        println!("Defaults: {:?}", component.defaults);
        println!("Template length: {}", component.template.len());
        println!("Template: '{}'", component.template);

        assert_eq!(component.name, "nav");
        assert_eq!(component.props, vec!["active"]);
        assert!(
            component.template.contains("<header"),
            "Template should contain <header>"
        );
        assert!(
            component.template.len() > 100,
            "Template should have content, got len={}",
            component.template.len()
        );

        // Test render
        let mut props = std::collections::HashMap::new();
        props.insert("active".to_string(), "home".to_string());
        let ctx = std::collections::HashMap::new();

        let rendered = component.render(&props, None, &ctx);
        println!("Rendered: '{}'", rendered);
        assert!(
            rendered.contains("<header"),
            "Rendered should contain <header>"
        );
        assert!(
            rendered.contains("nav-brand"),
            "Rendered should contain nav-brand"
        );
    }

    #[test]
    fn test_parse_what_format_no_defaults() {
        let content = r##"<what>
props = "title"
</what>
<h1>#title#</h1>"##;

        let component = Component::parse_with_name(content, "heading".to_string()).unwrap();
        assert_eq!(component.name, "heading");
        assert_eq!(component.props, vec!["title"]);
        assert!(component.defaults.is_empty());
        assert_eq!(component.template, "<h1>#title#</h1>");
    }

    #[test]
    fn test_parse_what_format_no_what_block() {
        // Component without <what> block - just template content
        let content = r##"<div class="simple">
    <slot/>
</div>"##;

        let component = Component::parse_with_name(content, "simple".to_string()).unwrap();
        assert_eq!(component.name, "simple");
        assert!(component.props.is_empty());
        assert!(component.defaults.is_empty());
        assert!(component.template.contains("simple"));
    }

    #[test]
    fn test_load_components_with_prefix() {
        use std::io::Write;
        let temp_dir = tempfile::tempdir().unwrap();
        let comp_dir = temp_dir.path().join("components");
        std::fs::create_dir(&comp_dir).unwrap();

        // Create a test component file (legacy format)
        let mut file = std::fs::File::create(comp_dir.join("card.html")).unwrap();
        writeln!(
            file,
            r##"<component name="card" props="title">
            <div class="card"><h2>#title#</h2><slot/></div>
        </component>"##
        )
        .unwrap();

        let mut registry = ComponentRegistry::new();
        registry.load_from_directory(&comp_dir).unwrap();

        // Should be registered as what-card (filename-based, not from name attribute)
        assert!(registry.get("what-card").is_some());
        assert!(registry.get("card").is_none());
    }

    #[test]
    fn test_load_components_new_format() {
        use std::io::Write;
        let temp_dir = tempfile::tempdir().unwrap();
        let comp_dir = temp_dir.path().join("components");
        std::fs::create_dir(&comp_dir).unwrap();

        // Create a test component file (new format)
        let mut file = std::fs::File::create(comp_dir.join("nav.html")).unwrap();
        writeln!(
            file,
            r##"<what>
props = "active"
defaults.active = "home"
</what>
<nav data-active="#active#"><slot/></nav>"##
        )
        .unwrap();

        let mut registry = ComponentRegistry::new();
        registry.load_from_directory(&comp_dir).unwrap();

        // Should be registered as what-nav
        let nav = registry.get("what-nav").expect("what-nav should exist");
        assert_eq!(nav.props, vec!["active"]);
        assert_eq!(nav.defaults.get("active"), Some(&"home".to_string()));
    }

    #[test]
    fn test_load_components_recursive() {
        use std::io::Write;
        let temp_dir = tempfile::tempdir().unwrap();
        let comp_dir = temp_dir.path().join("components");
        let sub_dir = comp_dir.join("forms");
        std::fs::create_dir_all(&sub_dir).unwrap();

        // Create component in root
        let mut file = std::fs::File::create(comp_dir.join("card.html")).unwrap();
        writeln!(file, "<div class=\"card\"><slot/></div>").unwrap();

        // Create component in subdirectory
        let mut file = std::fs::File::create(sub_dir.join("input.html")).unwrap();
        writeln!(file, "<input type=\"text\" />").unwrap();

        let mut registry = ComponentRegistry::new();
        registry.load_from_directory(&comp_dir).unwrap();

        // Both should be loaded with flat namespace
        assert!(registry.get("what-card").is_some());
        assert!(registry.get("what-input").is_some());
        // Should NOT be scoped by folder
        assert!(registry.get("what-forms-input").is_none());
    }

    #[test]
    fn test_render_component_json_array_prop() {
        let component = Component {
            name: "groups".to_string(),
            props: vec!["groups".to_string()],
            defaults: HashMap::new(),
            template: "<ul><loop data=\"#groups#\" as=\"g\"><li>#g.name#</li></loop></ul>"
                .to_string(),
        };

        let mut props = HashMap::new();
        props.insert(
            "groups".to_string(),
            r#"[{"id":1,"name":"Admins"},{"id":2,"name":"Editors"}]"#.to_string(),
        );

        let _result = component.render(&props, None, &HashMap::new());

        // The JSON array should be parsed and available in the context
        // (loop processing happens in the engine, not here, but the context should have the array)
        // Verify the prop is inserted as a JSON array, not a string
        let mut ctx = HashMap::new();
        let trimmed = props["groups"].trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(&props["groups"]) {
                ctx.insert("groups".to_string(), json_val);
            }
        }
        assert!(
            ctx["groups"].is_array(),
            "JSON array prop should be parsed as array"
        );
        assert_eq!(ctx["groups"].as_array().unwrap().len(), 2);
    }

    // =========================================================================
    // Built-in Component Tests
    // =========================================================================

    #[test]
    fn builtin_modal_renders() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let modal = registry.get("what-modal").unwrap();
        let mut props = HashMap::new();
        props.insert("id".to_string(), "my-modal".to_string());
        props.insert("title".to_string(), "Confirm".to_string());
        let result = modal.render(&props, Some("<p>Are you sure?</p>"), &HashMap::new());
        assert!(result.contains("id=\"my-modal\""));
        assert!(result.contains("Confirm"));
        assert!(result.contains("Are you sure?"));
        assert!(result.contains("modal-backdrop"));
    }

    #[test]
    fn builtin_drawer_defaults_right() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let drawer = registry.get("what-drawer").unwrap();
        let mut props = HashMap::new();
        props.insert("id".to_string(), "side".to_string());
        props.insert("title".to_string(), "Menu".to_string());
        let result = drawer.render(&props, Some("<ul><li>Home</li></ul>"), &HashMap::new());
        assert!(result.contains("drawer-right"));
        assert!(result.contains("Menu"));
    }

    #[test]
    fn builtin_tabs_renders() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let tabs = registry.get("what-tabs").unwrap();
        let mut props = HashMap::new();
        props.insert("id".to_string(), "main".to_string());
        let result = tabs.render(&props, Some("<button>Tab 1</button>"), &HashMap::new());
        assert!(result.contains("id=\"main-tabs\""));
        assert!(result.contains("tab-list"));
        assert!(result.contains("Tab 1"));
    }

    #[test]
    fn builtin_accordion_renders() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let acc = registry.get("what-accordion").unwrap();
        let mut props = HashMap::new();
        props.insert("id".to_string(), "faq1".to_string());
        props.insert("title".to_string(), "What is this?".to_string());
        let result = acc.render(&props, Some("<p>An accordion</p>"), &HashMap::new());
        assert!(result.contains("What is this?"));
        assert!(result.contains("w-accordion-header"));
        assert!(result.contains("An accordion"));
    }

    #[test]
    fn builtin_dropdown_defaults() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let dd = registry.get("what-dropdown").unwrap();
        let result = dd.render(&HashMap::new(), Some("<a>Item 1</a>"), &HashMap::new());
        assert!(result.contains("Menu"));
        assert!(result.contains("btn btn-secondary"));
        assert!(result.contains("dropdown-menu"));
        assert!(result.contains("Item 1"));
    }

    #[test]
    fn builtin_tooltip_renders() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let tt = registry.get("what-tooltip").unwrap();
        let mut props = HashMap::new();
        props.insert("text".to_string(), "Help text".to_string());
        let result = tt.render(&props, Some("Hover me"), &HashMap::new());
        assert!(result.contains("data-tooltip=\"Help text\""));
        assert!(result.contains("data-tooltip-position=\"top\""));
        assert!(result.contains("Hover me"));
    }

    #[test]
    fn builtin_pagination_renders() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        let pg = registry.get("what-pagination").unwrap();
        let result = pg.render(&HashMap::new(), Some("<a>1</a><a>2</a>"), &HashMap::new());
        assert!(result.contains("navigation-pagination"));
        assert!(result.contains("<a>1</a>"));
    }

    #[test]
    fn builtin_no_jumbo_or_left_nav() {
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();
        assert!(
            registry.get("what-jumbo").is_none(),
            "what-jumbo should be removed"
        );
        assert!(
            registry.get("what-left-nav").is_none(),
            "what-left-nav should be removed"
        );
    }
}