kyori-component-json 0.2.1

A library for serializing and deserializing Kyori Component JSON content
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
//! # kyori-component-json
//!
//! A library for serialising and deserialising Minecraft's JSON component format, also known as
//! 'raw JSON text'. Minecraft uses this format to display rich text throughout the game, including in
//! commands such as /tellraw and in elements such as books, signs, scoreboards and entity names.
//!
//! ## Features
//! - Full support for Minecraft's component specification (as of Java Edition 1.21.5+)
//! - Serialization and deserialization using Serde
//! - Builder-style API for constructing components
//! - Style inheritance and component nesting
//! - Comprehensive type safety for all component elements
//!
//! ## When to Use
//! This library is useful when:
//! - Generating complex chat messages with formatting and interactivity
//! - Creating custom books or signs with rich text
//! - Building command generators that use `/tellraw` or `/title`
//! - Processing component data from Minecraft APIs or data packs
//!
//! ## Getting Started
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! kyori-component-json = "0.1"
//! serde-json = "1.0"
//! ```
//!
//! ## Basic Example
//! ```
//! use kyori_component_json::*;
//! use serde_json::json;
//!
//! // Create a formatted chat message
//! let message = Component::text("Hello ")
//!     .color(Some(Color::Named(NamedColor::Yellow)))
//!     .append(
//!         Component::text("World!")
//!             .color(Some(Color::Named(NamedColor::White)))
//!             .decoration(TextDecoration::Bold, Some(true))
//!     )
//!     .append_newline()
//!     .append(
//!         Component::text("Click here")
//!             .click_event(Some(ClickEvent::RunCommand {
//!                 command: "/say I was clicked!".into()
//!             }))
//!             .hover_event(Some(HoverEvent::ShowText {
//!                 value: Component::text("Run a command!")
//!             }))
//!     );
//!
//! // Serialize to JSON
//! let json = serde_json::to_value(&message).unwrap();
//! assert_eq!(json, json!({
//!     "text": "Hello ",
//!     "color": "yellow",
//!     "extra": [
//!         {
//!             "text": "World!",
//!             "color": "white",
//!             "bold": true
//!         },
//!         {"text": "\n"},
//!         {
//!             "text": "Click here",
//!             "click_event": {
//!                 "action": "run_command",
//!                 "command": "/say I was clicked!"
//!             },
//!             "hover_event": {
//!                 "action": "show_text",
//!                 "value": {"text": "Run a command!"}
//!             }
//!         }
//!     ]
//! }));
//! ```
//!
//! ## Key Concepts
//! 1. **Components** - The building blocks of Minecraft text:
//!    - `String`: Plain text shorthand
//!    - `Array`: List of components
//!    - `Object`: Full component with properties
//! 2. **Content Types** - Special content like translations or scores
//! 3. **Formatting** - Colors, styles, and fonts
//! 4. **Interactivity** - Click and hover events
//!
//! See [Minecraft Wiki](https://minecraft.wiki/w/Text_component_format) for full specification.
#![warn(missing_docs)]
#![warn(clippy::perf)]
#![warn(clippy::unwrap_used, clippy::expect_used)]
#![forbid(missing_copy_implementations, missing_debug_implementations)]
#![forbid(unsafe_code)]

mod colors;
pub mod minimessage;
pub mod parsing;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;
use std::{collections::HashMap, fmt, str::FromStr};

/// Represents a Minecraft text component. Allows de/serialization using Serde with JSON.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Component {
    /// Simple string component (shorthand for `{text: "value"}`)
    String(String),
    /// Array of components (shorthand for first component with extras)
    Array(Vec<Component>),
    /// Full component object with properties
    Object(Box<ComponentObject>),
}

/// Content type of a component object
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContentType {
    /// Plain text content
    Text,
    /// Localized translation text
    Translatable,
    /// Scoreboard value
    Score,
    /// Entity selector
    Selector,
    /// Key binding display
    Keybind,
    /// NBT data display
    Nbt,
}

/// Named text colors from Minecraft
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NamedColor {
    /// #000000
    Black,
    /// #0000AA
    DarkBlue,
    /// #00AA00
    DarkGreen,
    /// #00AAAA
    DarkAqua,
    /// #AA0000
    DarkRed,
    /// #AA00AA
    DarkPurple,
    /// #FFAA00
    Gold,
    /// #AAAAAA
    Gray,
    /// #555555
    DarkGray,
    /// #5555FF
    Blue,
    /// #55FF55
    Green,
    /// #55FFFF
    Aqua,
    /// #FF5555
    Red,
    /// #FF55FF
    LightPurple,
    /// #FFFF55
    Yellow,
    /// #FFFFFF
    White,
}

impl FromStr for NamedColor {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        colors::NAME_TO_NAMED_COLOR
            .iter()
            // look for case-insensitive match by name
            .find(|(name, _)| name.eq_ignore_ascii_case(s))
            // and return the color
            .map(|(_, color)| *color)
            // if not found, return error
            .ok_or(())
    }
}

/// Text color representation (either named or hex)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Color {
    /// Predefined Minecraft color name
    Named(NamedColor),
    /// Hex color code in #RRGGBB format
    Hex(String),
}

impl Color {
    /// Gets the named color for a given `Color`.
    /// If the color is not a named color, it will try to find a matching named color for a hex color.
    pub fn to_named(&self) -> Option<NamedColor> {
        match self {
            Color::Named(named) => Some(*named),
            Color::Hex(hex) => colors::HEX_CODE_TO_NAMED_COLOR
                .iter()
                .find(|(h, _)| h == &hex.as_str())
                .map(|(_, n)| *n),
        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Color::Named(named) => named.fmt(f),
            Color::Hex(hex) => hex.fmt(f),
        }
    }
}

impl From<(u8, u8, u8)> for Color {
    fn from((r, g, b): (u8, u8, u8)) -> Self {
        Color::Hex(format!("#{:02X}{:02X}{:02X}", r, g, b))
    }
}

impl From<[u8; 3]> for Color {
    fn from([r, g, b]: [u8; 3]) -> Self {
        Color::Hex(format!("#{:02X}{:02X}{:02X}", r, g, b))
    }
}

impl Serialize for Color {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Color::Named(named) => named.serialize(serializer),
            Color::Hex(hex) => hex.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for Color {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        if let Ok(named) = serde_json::from_str::<NamedColor>(&format!("\"{s}\"")) {
            Ok(Color::Named(named))
        } else {
            Ok(Color::Hex(s))
        }
    }
}

/// Shadow color representation (integer or float array)
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ShadowColor {
    /// RGBA packed as 32-bit integer (0xRRGGBBAA)
    Int(i32),
    /// RGBA as [0.0-1.0] float values
    Floats([f32; 4]),
}

/// Actions triggered when clicking text
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "action")]
#[allow(missing_docs)]
pub enum ClickEvent {
    /// Open URL in browser
    OpenUrl { url: String },
    /// Open file (client-side only)
    OpenFile { path: String },
    /// Execute command
    RunCommand { command: String },
    /// Suggest command in chat
    SuggestCommand { command: String },
    /// Change page in books
    ChangePage { page: i32 },
    /// Copy text to clipboard
    CopyToClipboard { value: String },
}

/// UUID representation for entity hover events
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UuidRepr {
    /// String representation (hyphenated hex format)
    String(String),
    /// Integer array representation
    IntArray([i32; 4]),
}

/// Information shown when hovering over text
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "action")]
pub enum HoverEvent {
    /// Show text component
    ShowText {
        /// Text to display
        value: Component,
    },
    /// Show item tooltip
    ShowItem {
        /// Item ID (e.g., "minecraft:diamond_sword")
        id: String,
        /// Stack count
        #[serde(skip_serializing_if = "Option::is_none")]
        count: Option<i32>,
        /// Additional item components
        #[serde(skip_serializing_if = "Option::is_none")]
        components: Option<Value>,
    },
    /// Show entity information
    ShowEntity {
        /// Custom name override
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<Component>,
        /// Entity type ID
        id: String,
        /// Entity UUID
        uuid: UuidRepr,
    },
}

/// Scoreboard value content
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScoreContent {
    /// Score holder (player name or selector)
    pub name: String,
    /// Objective name
    pub objective: String,
}

/// Source for NBT data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NbtSource {
    /// Block entity data
    Block,
    /// Entity data
    Entity,
    /// Command storage
    Storage,
}

/// Core component structure containing all properties
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComponentObject {
    /// Content type specification
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub content_type: Option<ContentType>,

    /// Plain text content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    /// Translation key
    #[serde(skip_serializing_if = "Option::is_none")]
    pub translate: Option<String>,

    /// Fallback text for missing translations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback: Option<String>,

    /// Arguments for translations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub with: Option<Vec<Component>>,

    /// Scoreboard value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<ScoreContent>,

    /// Entity selector
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,

    /// Custom separator for multi-value components
    #[serde(skip_serializing_if = "Option::is_none")]
    pub separator: Option<Box<Component>>,

    /// Key binding name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keybind: Option<String>,

    /// NBT path query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbt: Option<String>,

    /// NBT source type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<NbtSource>,

    /// Whether to interpret NBT as components
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interpret: Option<bool>,

    /// Block coordinates for NBT source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub block: Option<String>,

    /// Entity selector for NBT source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity: Option<String>,

    /// Storage ID for NBT source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage: Option<String>,

    /// Child components
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<Vec<Component>>,

    /// Text color
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,

    /// Font resource location
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font: Option<String>,

    /// Bold formatting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bold: Option<bool>,

    /// Italic formatting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub italic: Option<bool>,

    /// Underline formatting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub underlined: Option<bool>,

    /// Strikethrough formatting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strikethrough: Option<bool>,

    /// Obfuscated text
    #[serde(skip_serializing_if = "Option::is_none")]
    pub obfuscated: Option<bool>,

    /// Text shadow color
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shadow_color: Option<ShadowColor>,

    /// Text insertion on shift-click
    #[serde(skip_serializing_if = "Option::is_none")]
    pub insertion: Option<String>,

    /// Click action
    #[serde(skip_serializing_if = "Option::is_none")]
    pub click_event: Option<ClickEvent>,

    /// Hover action
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hover_event: Option<HoverEvent>,
}

/// Style properties for components
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Style {
    /// Text color
    pub color: Option<Color>,
    /// Font resource location
    pub font: Option<String>,
    /// Bold formatting
    pub bold: Option<bool>,
    /// Italic formatting
    pub italic: Option<bool>,
    /// Underline formatting
    pub underlined: Option<bool>,
    /// Strikethrough formatting
    pub strikethrough: Option<bool>,
    /// Obfuscated text
    pub obfuscated: Option<bool>,
    /// Text shadow color
    pub shadow_color: Option<ShadowColor>,
    /// Text insertion on shift-click
    pub insertion: Option<String>,
    /// Click action
    pub click_event: Option<ClickEvent>,
    /// Hover action
    pub hover_event: Option<HoverEvent>,
}

/// Text decoration styles
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextDecoration {
    /// Bold text
    Bold,
    /// Italic text
    Italic,
    /// Underlined text
    Underlined,
    /// Strikethrough text
    Strikethrough,
    /// Obfuscated (scrambled) text
    Obfuscated,
}

/// Style properties for merging (unused in current implementation)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StyleMerge {
    /// Color property
    Color,
    /// Font property
    Font,
    /// Bold property
    Bold,
    /// Italic property
    Italic,
    /// Underline property
    Underlined,
    /// Strikethrough property
    Strikethrough,
    /// Obfuscated property
    Obfuscated,
    /// Shadow color property
    ShadowColor,
    /// Insertion property
    Insertion,
    /// Click event property
    ClickEvent,
    /// Hover event property
    HoverEvent,
}

impl Component {
    /// Creates a plain text component
    pub fn text(text: impl AsRef<str>) -> Self {
        Component::Object(Box::new(ComponentObject {
            text: Some(text.as_ref().to_string()),
            ..Default::default()
        }))
    }

    /// Appends a child component
    pub fn append<C: Into<Component>>(self, component: C) -> Self {
        let component = component.into();
        match self {
            Component::String(s) => Component::Object(Box::new(ComponentObject {
                content_type: Some(ContentType::Text),
                text: Some(s),
                extra: Some(vec![component]),
                ..Default::default()
            })),
            Component::Array(mut vec) => {
                vec.push(component);
                Component::Array(vec)
            }
            Component::Object(mut obj) => {
                if let Some(extras) = &mut obj.extra {
                    extras.push(component);
                } else {
                    obj.extra = Some(vec![component]);
                }
                Component::Object(obj)
            }
        }
    }

    /// Appends a newline character
    pub fn append_newline(self) -> Self {
        self.append(Component::text("\n"))
    }

    /// Appends a space character
    pub fn append_space(self) -> Self {
        self.append(Component::text(" "))
    }

    /// Returns the "plain text" representation of this component as a [`Cow<str>`].
    ///
    /// This is the closest equivalent to [Kyori's plain text serializer](https://javadoc.io/doc/net.kyori/adventure-text-serializer-plain/latest/net/kyori/adventure/text/serializer/plain/PlainTextComponentSerializer.html)
    ///
    /// # Behavior by variant
    ///
    /// - `Component::String`: Returns a borrowed `&str` of the string content.
    /// - `Component::Object`:  
    ///     - If the object has `text` and no `extra` children, returns a borrowed `&str`.
    ///     - If the object has `extra` children, returns an owned `String` concatenating
    ///       the object's `text` (if any) with the `to_plain_text` of each child.
    /// - `Component::Array`: Returns an owned `String` concatenating the `to_plain_text`
    ///   of each element in the array.
    ///
    /// # Notes
    ///
    /// This method may allocate a new `String` if concatenation is needed.  
    /// Use [`Self::get_plain_text`] if you only need a cheap, O(1) borrowed string from a single component.
    pub fn to_plain_text(&self) -> Cow<'_, str> {
        match self {
            Component::String(s) => Cow::Borrowed(s),
            Component::Object(obj) => {
                if obj.extra.is_none()
                    && let Some(text) = &obj.text
                {
                    return Cow::Borrowed(text);
                }

                let mut result = String::new();
                if let Some(text) = &obj.text {
                    result.push_str(text);
                }
                if let Some(children) = &obj.extra {
                    for child in children {
                        result.push_str(&child.to_plain_text());
                    }
                }
                Cow::Owned(result)
            }
            Component::Array(components) => {
                let mut result = String::new();
                for c in components {
                    result.push_str(&c.to_plain_text());
                }
                Cow::Owned(result)
            }
        }
    }

    /// Returns the raw `text` field if this component is a string or an object with a text field.
    ///
    /// Does not traverse children or consider other fields. Cheap, O(1) operation alternative to [`Self::to_plain_text`].
    pub fn get_plain_text(&self) -> Option<&str> {
        match self {
            Component::String(s) => Some(s),
            Component::Object(obj) => obj.text.as_deref(),
            _ => None,
        }
    }

    /// Applies fallback styles to unset properties
    pub fn apply_fallback_style(self, fallback: &Style) -> Self {
        match self {
            Component::String(s) => {
                let mut obj = ComponentObject {
                    content_type: Some(ContentType::Text),
                    text: Some(s),
                    ..Default::default()
                };
                obj.merge_style(fallback);
                Component::Object(Box::new(obj))
            }
            Component::Array(vec) => Component::Array(
                vec.into_iter()
                    .map(|c| c.apply_fallback_style(fallback))
                    .collect(),
            ),
            Component::Object(mut obj) => {
                obj.merge_style(fallback);
                if let Some(extras) = obj.extra {
                    obj.extra = Some(
                        extras
                            .into_iter()
                            .map(|c| c.apply_fallback_style(fallback))
                            .collect(),
                    );
                }
                Component::Object(obj)
            }
        }
    }

    /// Sets text color
    pub fn color(self, color: Option<Color>) -> Self {
        self.map_object(|mut obj| {
            obj.color = color;
            obj
        })
    }

    /// Sets font
    pub fn font(self, font: Option<String>) -> Self {
        self.map_object(|mut obj| {
            obj.font = font;
            obj
        })
    }

    /// Sets text decoration state
    pub fn decoration(self, decoration: TextDecoration, state: Option<bool>) -> Self {
        self.map_object(|mut obj| {
            match decoration {
                TextDecoration::Bold => obj.bold = state,
                TextDecoration::Italic => obj.italic = state,
                TextDecoration::Underlined => obj.underlined = state,
                TextDecoration::Strikethrough => obj.strikethrough = state,
                TextDecoration::Obfuscated => obj.obfuscated = state,
            }
            obj
        })
    }

    /// Sets multiple decorations at once
    pub fn decorations(self, decorations: &HashMap<TextDecoration, Option<bool>>) -> Self {
        self.map_object(|mut obj| {
            for (decoration, state) in decorations {
                match decoration {
                    TextDecoration::Bold => obj.bold = *state,
                    TextDecoration::Italic => obj.italic = *state,
                    TextDecoration::Underlined => obj.underlined = *state,
                    TextDecoration::Strikethrough => obj.strikethrough = *state,
                    TextDecoration::Obfuscated => obj.obfuscated = *state,
                }
            }
            obj
        })
    }

    /// Sets click event
    pub fn click_event(self, event: Option<ClickEvent>) -> Self {
        self.map_object(|mut obj| {
            obj.click_event = event;
            obj
        })
    }

    /// Sets hover event
    pub fn hover_event(self, event: Option<HoverEvent>) -> Self {
        self.map_object(|mut obj| {
            obj.hover_event = event;
            obj
        })
    }

    /// Sets insertion text
    pub fn insertion(self, insertion: Option<String>) -> Self {
        self.map_object(|mut obj| {
            obj.insertion = insertion;
            obj
        })
    }

    /// Checks if a decoration is enabled
    pub fn has_decoration(&self, decoration: TextDecoration) -> bool {
        match self {
            Component::Object(obj) => match decoration {
                TextDecoration::Bold => obj.bold.unwrap_or(false),
                TextDecoration::Italic => obj.italic.unwrap_or(false),
                TextDecoration::Underlined => obj.underlined.unwrap_or(false),
                TextDecoration::Strikethrough => obj.strikethrough.unwrap_or(false),
                TextDecoration::Obfuscated => obj.obfuscated.unwrap_or(false),
            },
            _ => false,
        }
    }

    /// Checks if any styling is present
    pub fn has_styling(&self) -> bool {
        match self {
            Component::Object(obj) => {
                obj.color.is_some()
                    || obj.font.is_some()
                    || obj.bold.is_some()
                    || obj.italic.is_some()
                    || obj.underlined.is_some()
                    || obj.strikethrough.is_some()
                    || obj.obfuscated.is_some()
                    || obj.shadow_color.is_some()
                    || obj.insertion.is_some()
                    || obj.click_event.is_some()
                    || obj.hover_event.is_some()
            }
            _ => false,
        }
    }

    /// Sets child components
    pub fn set_children(self, children: Vec<Component>) -> Self {
        self.map_object(|mut obj| {
            obj.extra = Some(children);
            obj
        })
    }

    /// Gets child components
    pub fn get_children(&self) -> &[Component] {
        match self {
            Component::Object(obj) => obj.extra.as_deref().unwrap_or_default(),
            Component::Array(vec) => vec.as_slice(),
            Component::String(_) => &[],
        }
    }

    /// Internal method to apply transformations to component objects
    fn map_object<F>(self, f: F) -> Self
    where
        F: FnOnce(ComponentObject) -> ComponentObject,
    {
        match self {
            Component::String(s) => {
                let obj = ComponentObject {
                    content_type: Some(ContentType::Text),
                    text: Some(s),
                    ..Default::default()
                };
                Component::Object(Box::new(f(obj)))
            }
            Component::Array(vec) => {
                let mut obj = ComponentObject {
                    extra: Some(vec),
                    ..Default::default()
                };
                obj = f(obj);
                Component::Object(Box::new(obj))
            }
            Component::Object(obj) => Component::Object(Box::new(f(*obj))),
        }
    }
}

impl ComponentObject {
    /// Merges style properties from a fallback style
    fn merge_style(&mut self, fallback: &Style) {
        if self.color.is_none() {
            self.color = fallback.color.clone();
        }
        if self.font.is_none() {
            self.font = fallback.font.clone();
        }
        if self.bold.is_none() {
            self.bold = fallback.bold;
        }
        if self.italic.is_none() {
            self.italic = fallback.italic;
        }
        if self.underlined.is_none() {
            self.underlined = fallback.underlined;
        }
        if self.strikethrough.is_none() {
            self.strikethrough = fallback.strikethrough;
        }
        if self.obfuscated.is_none() {
            self.obfuscated = fallback.obfuscated;
        }
        if self.shadow_color.is_none() {
            self.shadow_color = fallback.shadow_color;
        }
        if self.insertion.is_none() {
            self.insertion = fallback.insertion.clone();
        }
        if self.click_event.is_none() {
            self.click_event = fallback.click_event.clone();
        }
        if self.hover_event.is_none() {
            self.hover_event = fallback.hover_event.clone();
        }
    }
}

/// Error type for color parsing
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseColorError;

impl std::fmt::Display for ParseColorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid color format")
    }
}

impl std::error::Error for ParseColorError {}

fn parse_hex_color(s: &str) -> Option<[u8; 3]> {
    let s = s.strip_prefix('#')?;
    if s.len() == 6 {
        let r = u8::from_str_radix(&s[0..2], 16).ok()?;
        let g = u8::from_str_radix(&s[2..4], 16).ok()?;
        let b = u8::from_str_radix(&s[4..6], 16).ok()?;
        return Some([r, g, b]);
    }
    None
}



impl FromStr for Color {
    type Err = ParseColorError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(named) = s.parse::<NamedColor>() {
            return Ok(Color::Named(named));
        }

        if parse_hex_color(s).is_some() {
            return Ok(Color::Hex(s.to_string()));
        }

        Err(ParseColorError)
    }
}

impl<T: AsRef<str>> From<T> for Component {
    fn from(value: T) -> Component {
        let s: &str = value.as_ref();
        Component::String(s.to_string())
    }
}

impl fmt::Display for NamedColor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            NamedColor::Black => "black",
            NamedColor::DarkBlue => "dark_blue",
            NamedColor::DarkGreen => "dark_green",
            NamedColor::DarkAqua => "dark_aqua",
            NamedColor::DarkRed => "dark_red",
            NamedColor::DarkPurple => "dark_purple",
            NamedColor::Gold => "gold",
            NamedColor::Gray => "gray",
            NamedColor::DarkGray => "dark_gray",
            NamedColor::Blue => "blue",
            NamedColor::Green => "green",
            NamedColor::Aqua => "aqua",
            NamedColor::Red => "red",
            NamedColor::LightPurple => "light_purple",
            NamedColor::Yellow => "yellow",
            NamedColor::White => "white",
        };
        write!(f, "{s}")
    }
}

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

    #[test]
    fn test_parse_message() {
        let raw_json = r#"
        {
          "text": "Hello, ",
          "color": "yellow",
          "extra": [
            {
              "text": "World!",
              "color": "white",
              "bold": true
            },
            {
              "translate": "chat.type.say",
              "with": [
                { "selector": "@p" }
              ]
            }
          ]
        }
        "#;

        let component: Component = serde_json::from_str(raw_json).unwrap();
        println!("Message: {component:#?}");
    }
}