calamine-styles 0.1.0

Fork of calamine with Font, Fill, Border, Alignment, and NumberFormat style parsing for xlsx
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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
// SPDX-License-Identifier: MIT
//
// Copyright 2016-2025, Johann Tuffe.

use std::collections::BTreeMap;
use std::fmt;

/// Represents a color in ARGB format
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Color {
    /// Alpha channel (0-255)
    pub alpha: u8,
    /// Red channel (0-255)
    pub red: u8,
    /// Green channel (0-255)
    pub green: u8,
    /// Blue channel (0-255)
    pub blue: u8,
}

impl Color {
    /// Create a new color from ARGB values
    pub fn new(alpha: u8, red: u8, green: u8, blue: u8) -> Self {
        Self {
            alpha,
            red,
            green,
            blue,
        }
    }

    /// Create a color from RGB values (alpha = 255)
    pub fn rgb(red: u8, green: u8, blue: u8) -> Self {
        Self::new(255, red, green, blue)
    }

    /// Create a color from ARGB integer
    pub fn from_argb(argb: u32) -> Self {
        Self {
            alpha: ((argb >> 24) & 0xFF) as u8,
            red: ((argb >> 16) & 0xFF) as u8,
            green: ((argb >> 8) & 0xFF) as u8,
            blue: (argb & 0xFF) as u8,
        }
    }

    /// Convert to ARGB integer
    pub fn to_argb(&self) -> u32 {
        ((self.alpha as u32) << 24)
            | ((self.red as u32) << 16)
            | ((self.green as u32) << 8)
            | (self.blue as u32)
    }

    /// Check if the color is black
    pub fn is_black(&self) -> bool {
        self.red == 0 && self.green == 0 && self.blue == 0
    }

    /// Check if the color is white
    pub fn is_white(&self) -> bool {
        self.red == 255 && self.green == 255 && self.blue == 255
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{:02X}{:02X}{:02X}", self.red, self.green, self.blue)
    }
}

/// Border style enumeration
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum BorderStyle {
    /// No border
    #[default]
    None,
    /// Thin border
    Thin,
    /// Medium border
    Medium,
    /// Thick border
    Thick,
    /// Double border
    Double,
    /// Hair border
    Hair,
    /// Dashed border
    Dashed,
    /// Dotted border
    Dotted,
    /// Medium dashed border
    MediumDashed,
    /// Dash dot border
    DashDot,
    /// Dash dot dot border
    DashDotDot,
    /// Slant dash dot border
    SlantDashDot,
}

/// Border side
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Border {
    /// Border style
    pub style: BorderStyle,
    /// Border color
    pub color: Option<Color>,
}

impl Border {
    /// Create a new border with style
    pub fn new(style: BorderStyle) -> Self {
        Self { style, color: None }
    }

    /// Create a new border with style and color
    pub fn with_color(style: BorderStyle, color: Color) -> Self {
        Self {
            style,
            color: Some(color),
        }
    }

    /// Check if border is visible
    pub fn is_visible(&self) -> bool {
        self.style != BorderStyle::None
    }
}

/// All borders for a cell
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Borders {
    /// Left border
    pub left: Border,
    /// Right border
    pub right: Border,
    /// Top border
    pub top: Border,
    /// Bottom border
    pub bottom: Border,
    /// Diagonal down border
    pub diagonal_down: Border,
    /// Diagonal up border
    pub diagonal_up: Border,
}

impl Borders {
    /// Create new borders
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if any border is visible
    pub fn has_visible_borders(&self) -> bool {
        self.left.is_visible()
            || self.right.is_visible()
            || self.top.is_visible()
            || self.bottom.is_visible()
            || self.diagonal_down.is_visible()
            || self.diagonal_up.is_visible()
    }
}

/// Font weight
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FontWeight {
    /// Normal weight
    #[default]
    Normal,
    /// Bold weight
    Bold,
}

/// Font style
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FontStyle {
    /// Normal style
    #[default]
    Normal,
    /// Italic style
    Italic,
}

/// Underline style
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum UnderlineStyle {
    /// No underline
    #[default]
    None,
    /// Single underline
    Single,
    /// Double underline
    Double,
    /// Single accounting underline
    SingleAccounting,
    /// Double accounting underline
    DoubleAccounting,
}

/// Font properties
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Font {
    /// Font name
    pub name: Option<String>,
    /// Font size in points
    pub size: Option<f64>,
    /// Font weight
    pub weight: FontWeight,
    /// Font style
    pub style: FontStyle,
    /// Underline style
    pub underline: UnderlineStyle,
    /// Strikethrough
    pub strikethrough: bool,
    /// Font color
    pub color: Option<Color>,
    /// Font family
    pub family: Option<String>,
}

impl Font {
    /// Create a new font
    pub fn new() -> Self {
        Self::default()
    }

    /// Set font name
    pub fn with_name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    /// Set font size
    pub fn with_size(mut self, size: f64) -> Self {
        self.size = Some(size);
        self
    }

    /// Set font weight
    pub fn with_weight(mut self, weight: FontWeight) -> Self {
        self.weight = weight;
        self
    }

    /// Set font style
    pub fn with_style(mut self, style: FontStyle) -> Self {
        self.style = style;
        self
    }

    /// Set underline
    pub fn with_underline(mut self, underline: UnderlineStyle) -> Self {
        self.underline = underline;
        self
    }

    /// Set strikethrough
    pub fn with_strikethrough(mut self, strikethrough: bool) -> Self {
        self.strikethrough = strikethrough;
        self
    }

    /// Set font color
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Set font family
    pub fn with_family(mut self, family: String) -> Self {
        self.family = Some(family);
        self
    }

    /// Check if font is bold
    pub fn is_bold(&self) -> bool {
        self.weight == FontWeight::Bold
    }

    /// Check if font is italic
    pub fn is_italic(&self) -> bool {
        self.style == FontStyle::Italic
    }

    /// Check if font has underline
    pub fn has_underline(&self) -> bool {
        self.underline != UnderlineStyle::None
    }

    /// Check if font has strikethrough
    pub fn has_strikethrough(&self) -> bool {
        self.strikethrough
    }
}

/// A run of text with its own formatting within a rich text cell
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TextRun {
    /// The text content of this run
    pub text: String,
    /// Font properties for this run (None means inherit cell default)
    pub font: Option<Font>,
}

impl TextRun {
    /// Create a new text run with just text (no formatting)
    pub fn new(text: String) -> Self {
        Self { text, font: None }
    }

    /// Create a new text run with text and font
    pub fn with_font(text: String, font: Font) -> Self {
        Self {
            text,
            font: Some(font),
        }
    }

    /// Check if this run has any formatting
    pub fn has_formatting(&self) -> bool {
        self.font.is_some()
    }
}

/// Rich text content with multiple formatted runs
///
/// Rich text allows different parts of a cell's text to have different
/// formatting (bold, italic, colors, etc.). This is common in spreadsheets
/// where users want to emphasize certain words within a cell.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct RichText {
    /// The text runs in order
    pub runs: Vec<TextRun>,
}

impl RichText {
    /// Create a new empty rich text
    pub fn new() -> Self {
        Self::default()
    }

    /// Create rich text from a vector of runs
    pub fn from_runs(runs: Vec<TextRun>) -> Self {
        Self { runs }
    }

    /// Add a text run
    pub fn push(&mut self, run: TextRun) {
        self.runs.push(run);
    }

    /// Add a plain text run (no formatting)
    pub fn push_text(&mut self, text: String) {
        self.runs.push(TextRun::new(text));
    }

    /// Add a formatted text run
    pub fn push_formatted(&mut self, text: String, font: Font) {
        self.runs.push(TextRun::with_font(text, font));
    }

    /// Get the plain text content (all runs concatenated)
    pub fn plain_text(&self) -> String {
        self.runs.iter().map(|r| r.text.as_str()).collect()
    }

    /// Check if the rich text is empty
    pub fn is_empty(&self) -> bool {
        self.runs.is_empty() || self.runs.iter().all(|r| r.text.is_empty())
    }

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

    /// Check if any run has formatting
    pub fn has_formatting(&self) -> bool {
        self.runs.iter().any(|r| r.has_formatting())
    }

    /// Iterate over the runs
    pub fn iter(&self) -> impl Iterator<Item = &TextRun> {
        self.runs.iter()
    }
}

impl std::fmt::Display for RichText {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.plain_text())
    }
}

/// Horizontal alignment
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum HorizontalAlignment {
    /// Left alignment
    Left,
    /// Center alignment
    Center,
    /// Right alignment
    Right,
    /// Justify alignment
    Justify,
    /// Distributed alignment
    Distributed,
    /// Fill alignment
    Fill,
    /// General alignment (default)
    #[default]
    General,
}

/// Vertical alignment
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum VerticalAlignment {
    /// Top alignment
    Top,
    /// Center alignment
    Center,
    /// Bottom alignment
    #[default]
    Bottom,
    /// Justify alignment
    Justify,
    /// Distributed alignment
    Distributed,
}

/// Text rotation in degrees
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TextRotation {
    /// No rotation
    #[default]
    None,
    /// Rotated by degrees (0-180)
    Degrees(u16),
    /// Stacked text
    Stacked,
}

/// Cell alignment properties
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Alignment {
    /// Horizontal alignment
    pub horizontal: HorizontalAlignment,
    /// Vertical alignment
    pub vertical: VerticalAlignment,
    /// Text rotation
    pub text_rotation: TextRotation,
    /// Wrap text
    pub wrap_text: bool,
    /// Indent level
    pub indent: Option<u8>,
    /// Shrink to fit
    pub shrink_to_fit: bool,
}

impl Alignment {
    /// Create new alignment
    pub fn new() -> Self {
        Self::default()
    }

    /// Set horizontal alignment
    pub fn with_horizontal(mut self, horizontal: HorizontalAlignment) -> Self {
        self.horizontal = horizontal;
        self
    }

    /// Set vertical alignment
    pub fn with_vertical(mut self, vertical: VerticalAlignment) -> Self {
        self.vertical = vertical;
        self
    }

    /// Set text rotation
    pub fn with_text_rotation(mut self, rotation: TextRotation) -> Self {
        self.text_rotation = rotation;
        self
    }

    /// Set wrap text
    pub fn with_wrap_text(mut self, wrap: bool) -> Self {
        self.wrap_text = wrap;
        self
    }

    /// Set indent level
    pub fn with_indent(mut self, indent: u8) -> Self {
        self.indent = Some(indent);
        self
    }

    /// Set shrink to fit
    pub fn with_shrink_to_fit(mut self, shrink: bool) -> Self {
        self.shrink_to_fit = shrink;
        self
    }
}

/// Fill pattern type
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FillPattern {
    /// No fill
    #[default]
    None,
    /// Solid fill
    Solid,
    /// Dark gray pattern
    DarkGray,
    /// Medium gray pattern
    MediumGray,
    /// Light gray pattern
    LightGray,
    /// Gray 125 pattern
    Gray125,
    /// Gray 0625 pattern
    Gray0625,
    /// Dark horizontal pattern
    DarkHorizontal,
    /// Dark vertical pattern
    DarkVertical,
    /// Dark down pattern
    DarkDown,
    /// Dark up pattern
    DarkUp,
    /// Dark grid pattern
    DarkGrid,
    /// Dark trellis pattern
    DarkTrellis,
    /// Light horizontal pattern
    LightHorizontal,
    /// Light vertical pattern
    LightVertical,
    /// Light down pattern
    LightDown,
    /// Light up pattern
    LightUp,
    /// Light grid pattern
    LightGrid,
    /// Light trellis pattern
    LightTrellis,
}

/// Fill properties
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Fill {
    /// Fill pattern
    pub pattern: FillPattern,
    /// Foreground color
    pub foreground_color: Option<Color>,
    /// Background color
    pub background_color: Option<Color>,
}

impl Fill {
    /// Create new fill
    pub fn new() -> Self {
        Self::default()
    }

    /// Create solid fill with color
    pub fn solid(color: Color) -> Self {
        Self {
            pattern: FillPattern::Solid,
            foreground_color: Some(color),
            background_color: None,
        }
    }

    /// Set pattern
    pub fn with_pattern(mut self, pattern: FillPattern) -> Self {
        self.pattern = pattern;
        self
    }

    /// Set foreground color
    pub fn with_foreground_color(mut self, color: Color) -> Self {
        self.foreground_color = Some(color);
        self
    }

    /// Set background color
    pub fn with_background_color(mut self, color: Color) -> Self {
        self.background_color = Some(color);
        self
    }

    /// Check if fill is visible
    pub fn is_visible(&self) -> bool {
        self.pattern != FillPattern::None
    }

    /// Get the main fill color (foreground if available, otherwise background)
    pub fn get_color(&self) -> Option<Color> {
        self.foreground_color.or(self.background_color)
    }
}

/// Number format
#[derive(Debug, Clone, PartialEq)]
pub struct NumberFormat {
    /// Format code
    pub format_code: String,
    /// Format ID
    pub format_id: Option<u32>,
}

impl NumberFormat {
    /// Create new number format
    pub fn new(format_code: String) -> Self {
        Self {
            format_code,
            format_id: None,
        }
    }

    /// Create with format ID
    pub fn with_id(mut self, format_id: u32) -> Self {
        self.format_id = Some(format_id);
        self
    }
}

impl Default for NumberFormat {
    fn default() -> Self {
        Self {
            format_code: "General".to_string(),
            format_id: None,
        }
    }
}

/// Cell protection properties
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Protection {
    /// Cell is locked
    pub locked: bool,
    /// Cell is hidden
    pub hidden: bool,
}

impl Protection {
    /// Create new protection
    pub fn new() -> Self {
        Self::default()
    }

    /// Set locked
    pub fn with_locked(mut self, locked: bool) -> Self {
        self.locked = locked;
        self
    }

    /// Set hidden
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }
}

/// Column width information
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnWidth {
    /// Column index (0-based)
    pub column: u32,
    /// Width in Excel units (characters)
    pub width: f64,
    /// Whether the width is custom (manually set)
    pub custom_width: bool,
    /// Whether the column is hidden
    pub hidden: bool,
    /// Best fit width
    pub best_fit: bool,
}

impl ColumnWidth {
    /// Create a new column width
    pub fn new(column: u32, width: f64) -> Self {
        Self {
            column,
            width,
            custom_width: false,
            hidden: false,
            best_fit: false,
        }
    }

    /// Set custom width flag
    pub fn with_custom_width(mut self, custom: bool) -> Self {
        self.custom_width = custom;
        self
    }

    /// Set hidden flag
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Set best fit flag
    pub fn with_best_fit(mut self, best_fit: bool) -> Self {
        self.best_fit = best_fit;
        self
    }

    /// Check if column is visible
    pub fn is_visible(&self) -> bool {
        !self.hidden
    }
}

/// Row height information
#[derive(Debug, Clone, PartialEq)]
pub struct RowHeight {
    /// Row index (0-based)
    pub row: u32,
    /// Height in points
    pub height: f64,
    /// Whether the height is custom (manually set)
    pub custom_height: bool,
    /// Whether the row is hidden
    pub hidden: bool,
    /// Thick top border
    pub thick_top: bool,
    /// Thick bottom border
    pub thick_bottom: bool,
}

impl RowHeight {
    /// Create a new row height
    pub fn new(row: u32, height: f64) -> Self {
        Self {
            row,
            height,
            custom_height: false,
            hidden: false,
            thick_top: false,
            thick_bottom: false,
        }
    }

    /// Set custom height flag
    pub fn with_custom_height(mut self, custom: bool) -> Self {
        self.custom_height = custom;
        self
    }

    /// Set hidden flag
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Set thick top border
    pub fn with_thick_top(mut self, thick_top: bool) -> Self {
        self.thick_top = thick_top;
        self
    }

    /// Set thick bottom border
    pub fn with_thick_bottom(mut self, thick_bottom: bool) -> Self {
        self.thick_bottom = thick_bottom;
        self
    }

    /// Check if row is visible
    pub fn is_visible(&self) -> bool {
        !self.hidden
    }
}

/// Worksheet layout information
#[derive(Debug, Clone, Default, PartialEq)]
pub struct WorksheetLayout {
    /// Column widths (keyed by column index)
    pub column_widths: BTreeMap<u32, ColumnWidth>,
    /// Row heights (keyed by row index)
    pub row_heights: BTreeMap<u32, RowHeight>,
    /// Default column width
    pub default_column_width: Option<f64>,
    /// Default row height
    pub default_row_height: Option<f64>,
}

impl WorksheetLayout {
    /// Create a new worksheet layout
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a column width
    pub fn add_column_width(mut self, column_width: ColumnWidth) -> Self {
        self.column_widths.insert(column_width.column, column_width);
        self
    }

    /// Add a row height
    pub fn add_row_height(mut self, row_height: RowHeight) -> Self {
        self.row_heights.insert(row_height.row, row_height);
        self
    }

    /// Set default column width
    pub fn with_default_column_width(mut self, width: f64) -> Self {
        self.default_column_width = Some(width);
        self
    }

    /// Set default row height
    pub fn with_default_row_height(mut self, height: f64) -> Self {
        self.default_row_height = Some(height);
        self
    }

    /// Get column width for a specific column (O(log n) lookup)
    pub fn get_column_width(&self, column: u32) -> Option<&ColumnWidth> {
        self.column_widths.get(&column)
    }

    /// Get row height for a specific row (O(log n) lookup)
    pub fn get_row_height(&self, row: u32) -> Option<&RowHeight> {
        self.row_heights.get(&row)
    }

    /// Get effective column width (custom or default).
    ///
    /// Returns the column width in Excel's character-based units. If no custom
    /// width is set, returns the worksheet's default column width, or 8.43 if
    /// no default is specified.
    ///
    /// **Note:** Excel column widths are stored in character units relative to
    /// the workbook's default font, not pixels. Converting to pixels requires
    /// font metrics and is font-dependent. The value 8.43 is Excel's standard
    /// default for Calibri 11pt.
    pub fn get_effective_column_width(&self, column: u32) -> f64 {
        self.get_column_width(column)
            .map(|cw| cw.width)
            .or(self.default_column_width)
            .unwrap_or(8.43)
    }

    /// Get effective row height (custom or default).
    ///
    /// Returns the row height in points. If no custom height is set, returns
    /// the worksheet's default row height, or 15.0 if no default is specified.
    ///
    /// **Note:** Row heights in Excel are stored in points (1/72 inch), but
    /// the actual displayed height may vary slightly depending on the default
    /// font. The value 15.0 is Excel's standard default for Calibri 11pt.
    pub fn get_effective_row_height(&self, row: u32) -> f64 {
        self.get_row_height(row)
            .map(|rh| rh.height)
            .or(self.default_row_height)
            .unwrap_or(15.0)
    }

    /// Check if layout has any custom dimensions
    pub fn has_custom_dimensions(&self) -> bool {
        !self.column_widths.is_empty()
            || !self.row_heights.is_empty()
            || self.default_column_width.is_some()
            || self.default_row_height.is_some()
    }
}

/// Complete cell style
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Style {
    /// Font properties
    pub font: Option<Font>,
    /// Fill properties
    pub fill: Option<Fill>,
    /// Border properties
    pub borders: Option<Borders>,
    /// Alignment properties
    pub alignment: Option<Alignment>,
    /// Number format
    pub number_format: Option<NumberFormat>,
    /// Protection properties
    pub protection: Option<Protection>,
    /// Style ID (for internal use)
    pub style_id: Option<u32>,
}

impl Style {
    /// Create new style
    pub fn new() -> Self {
        Self::default()
    }

    /// Set font
    pub fn with_font(mut self, font: Font) -> Self {
        self.font = Some(font);
        self
    }

    /// Set fill
    pub fn with_fill(mut self, fill: Fill) -> Self {
        self.fill = Some(fill);
        self
    }

    /// Set borders
    pub fn with_borders(mut self, borders: Borders) -> Self {
        self.borders = Some(borders);
        self
    }

    /// Set alignment
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = Some(alignment);
        self
    }

    /// Set number format
    pub fn with_number_format(mut self, number_format: NumberFormat) -> Self {
        self.number_format = Some(number_format);
        self
    }

    /// Set protection
    pub fn with_protection(mut self, protection: Protection) -> Self {
        self.protection = Some(protection);
        self
    }

    /// Set style ID
    pub fn with_style_id(mut self, style_id: u32) -> Self {
        self.style_id = Some(style_id);
        self
    }

    /// Get font
    pub fn get_font(&self) -> Option<&Font> {
        self.font.as_ref()
    }

    /// Get fill
    pub fn get_fill(&self) -> Option<&Fill> {
        self.fill.as_ref()
    }

    /// Get borders
    pub fn get_borders(&self) -> Option<&Borders> {
        self.borders.as_ref()
    }

    /// Get alignment
    pub fn get_alignment(&self) -> Option<&Alignment> {
        self.alignment.as_ref()
    }

    /// Get number format
    pub fn get_number_format(&self) -> Option<&NumberFormat> {
        self.number_format.as_ref()
    }

    /// Get protection
    pub fn get_protection(&self) -> Option<&Protection> {
        self.protection.as_ref()
    }

    /// Check if style is empty (no properties set)
    pub fn is_empty(&self) -> bool {
        self.font.is_none()
            && self.fill.is_none()
            && self.borders.is_none()
            && self.alignment.is_none()
            && self.number_format.is_none()
            && self.protection.is_none()
    }

    /// Check if style has any visible properties
    pub fn has_visible_properties(&self) -> bool {
        (self
            .font
            .as_ref()
            .is_some_and(|f| f.color.is_some() || f.is_bold() || f.is_italic()))
            || (self.fill.as_ref().is_some_and(|f| f.is_visible()))
            || (self
                .borders
                .as_ref()
                .is_some_and(|b| b.has_visible_borders()))
            || (self.alignment.as_ref().is_some_and(|a| {
                a.horizontal != HorizontalAlignment::General
                    || a.vertical != VerticalAlignment::Bottom
                    || a.text_rotation != TextRotation::None
                    || a.wrap_text
                    || a.indent.is_some()
                    || a.shrink_to_fit
            }))
    }
}

/// A run of consecutive cells with the same style (row-major order)
#[derive(Debug, Clone)]
struct StyleRun {
    /// Index into the palette (0 = no style/default)
    style_id: u16,
    /// Number of consecutive cells with this style
    count: u32,
}

/// RLE-compressed style storage for a worksheet range.
///
/// Instead of storing one Style per cell (which wastes memory when many cells
/// share the same style), this stores:
/// - A palette of unique styles
/// - Runs of consecutive cells (row-major) that share the same style
///
/// This dramatically reduces memory usage and clone overhead for large worksheets.
#[derive(Debug, Clone, Default)]
pub struct StyleRange {
    start: (u32, u32),
    end: (u32, u32),
    /// Palette of unique styles. Index 0 is reserved for "no style" (empty).
    palette: Vec<Style>,
    /// RLE-encoded runs in row-major order
    runs: Vec<StyleRun>,
    /// Total cell count (for validation)
    total_cells: u64,
}

impl StyleRange {
    /// Create an empty StyleRange
    pub fn empty() -> Self {
        Self::default()
    }

    /// Create a StyleRange from style IDs and a palette (zero-copy).
    ///
    /// This is more efficient than `from_sparse` as it avoids cloning styles.
    ///
    /// - `cells`: Vec of (row, col, style_id) where style_id indexes into palette
    /// - `palette`: The shared palette of unique styles (taken ownership)
    pub fn from_style_ids(cells: Vec<(u32, u32, usize)>, palette: Vec<Style>) -> Self {
        if cells.is_empty() {
            return Self::empty();
        }

        // Find bounds
        let mut row_start = u32::MAX;
        let mut row_end = 0;
        let mut col_start = u32::MAX;
        let mut col_end = 0;
        for (r, c, _) in &cells {
            row_start = row_start.min(*r);
            row_end = row_end.max(*r);
            col_start = col_start.min(*c);
            col_end = col_end.max(*c);
        }

        let width = (col_end - col_start + 1) as usize;
        let height = (row_end - row_start + 1) as usize;
        let total_cells = (width * height) as u64;

        // Create dense style ID array (temporary)
        let mut style_ids = vec![0u16; width * height];

        for (r, c, style_id) in cells {
            let row = (r - row_start) as usize;
            let col = (c - col_start) as usize;
            let idx = row * width + col;
            // style_id is already an index, just need to fit in u16
            style_ids[idx] = style_id.min(u16::MAX as usize) as u16;
        }

        // Compress into RLE runs
        let mut runs = Vec::new();
        if !style_ids.is_empty() {
            let mut current_style = style_ids[0];
            let mut count = 1u32;

            for &style_id in &style_ids[1..] {
                if style_id == current_style {
                    count += 1;
                } else {
                    runs.push(StyleRun {
                        style_id: current_style,
                        count,
                    });
                    current_style = style_id;
                    count = 1;
                }
            }
            runs.push(StyleRun {
                style_id: current_style,
                count,
            });
        }

        runs.shrink_to_fit();

        StyleRange {
            start: (row_start, col_start),
            end: (row_end, col_end),
            palette,
            runs,
            total_cells,
        }
    }

    /// Create a StyleRange from sparse cell data
    ///
    /// Takes cells with positions and styles, compresses into RLE format.
    pub fn from_sparse(cells: Vec<(u32, u32, Style)>) -> Self {
        if cells.is_empty() {
            return Self::empty();
        }

        // Find bounds
        let mut row_start = u32::MAX;
        let mut row_end = 0;
        let mut col_start = u32::MAX;
        let mut col_end = 0;
        for (r, c, _) in &cells {
            row_start = row_start.min(*r);
            row_end = row_end.max(*r);
            col_start = col_start.min(*c);
            col_end = col_end.max(*c);
        }

        let width = (col_end - col_start + 1) as usize;
        let height = (row_end - row_start + 1) as usize;
        let total_cells = (width * height) as u64;

        // Build palette and map styles to IDs
        // Use style_id from Excel if available, otherwise assign sequential IDs
        let mut palette: Vec<Style> = vec![Style::default()]; // Index 0 = empty/default
        let mut style_to_id: std::collections::HashMap<u32, u16> = std::collections::HashMap::new();

        // Create dense style ID array (temporary)
        let mut style_ids = vec![0u16; width * height];

        for (r, c, style) in cells {
            let row = (r - row_start) as usize;
            let col = (c - col_start) as usize;
            let idx = row * width + col;

            if style.is_empty() {
                continue; // Leave as 0
            }

            // Use Excel's style_id if available for deduplication
            // This groups cells with the same formatting together
            let excel_style_id = style.style_id.unwrap_or_else(|| {
                // Fallback: use palette length as unique ID (no dedup for these)
                palette.len() as u32
            });

            let style_id = if let Some(&id) = style_to_id.get(&excel_style_id) {
                id
            } else {
                let id = palette.len() as u16;
                palette.push(style);
                style_to_id.insert(excel_style_id, id);
                id
            };

            style_ids[idx] = style_id;
        }

        // Compress into RLE runs
        let mut runs = Vec::new();
        if !style_ids.is_empty() {
            let mut current_style = style_ids[0];
            let mut count = 1u32;

            for &style_id in &style_ids[1..] {
                if style_id == current_style {
                    count += 1;
                } else {
                    runs.push(StyleRun {
                        style_id: current_style,
                        count,
                    });
                    current_style = style_id;
                    count = 1;
                }
            }
            // Push final run
            runs.push(StyleRun {
                style_id: current_style,
                count,
            });
        }

        runs.shrink_to_fit();
        palette.shrink_to_fit();

        StyleRange {
            start: (row_start, col_start),
            end: (row_end, col_end),
            palette,
            runs,
            total_cells,
        }
    }

    /// Get the start position of the range
    pub fn start(&self) -> Option<(u32, u32)> {
        if self.is_empty() {
            None
        } else {
            Some(self.start)
        }
    }

    /// Get the end position of the range
    pub fn end(&self) -> Option<(u32, u32)> {
        if self.is_empty() {
            None
        } else {
            Some(self.end)
        }
    }

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

    /// Get width of the range
    pub fn width(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            (self.end.1 - self.start.1 + 1) as usize
        }
    }

    /// Get height of the range
    pub fn height(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            (self.end.0 - self.start.0 + 1) as usize
        }
    }

    /// Get style at a position (relative to range start)
    ///
    /// Returns None if position is out of bounds, or reference to style.
    pub fn get(&self, pos: (usize, usize)) -> Option<&Style> {
        let width = self.width();
        let height = self.height();

        if pos.0 >= height || pos.1 >= width {
            return None;
        }

        let linear_idx = pos.0 * width + pos.1;
        let style_id = self.style_id_at(linear_idx)?;
        self.palette.get(style_id as usize)
    }

    /// Get style ID at a linear index using binary search on runs
    fn style_id_at(&self, linear_idx: usize) -> Option<u16> {
        let mut offset = 0usize;
        for run in &self.runs {
            let run_end = offset + run.count as usize;
            if linear_idx < run_end {
                return Some(run.style_id);
            }
            offset = run_end;
        }
        None
    }

    /// Iterate over all cells with their positions and styles
    pub fn cells(&self) -> StyleRangeCells<'_> {
        StyleRangeCells {
            range: self,
            run_idx: 0,
            run_offset: 0,
            linear_idx: 0,
        }
    }

    /// Get number of unique styles (excluding empty)
    pub fn unique_style_count(&self) -> usize {
        self.palette.len().saturating_sub(1)
    }

    /// Get number of RLE runs (for diagnostics)
    pub fn run_count(&self) -> usize {
        self.runs.len()
    }

    /// Get compression ratio (cells / runs)
    pub fn compression_ratio(&self) -> f64 {
        if self.runs.is_empty() {
            0.0
        } else {
            self.total_cells as f64 / self.runs.len() as f64
        }
    }
}

/// Iterator over cells in a StyleRange
pub struct StyleRangeCells<'a> {
    range: &'a StyleRange,
    run_idx: usize,
    run_offset: u32,
    linear_idx: u64,
}

impl<'a> Iterator for StyleRangeCells<'a> {
    type Item = (usize, usize, &'a Style);

    fn next(&mut self) -> Option<Self::Item> {
        if self.run_idx >= self.range.runs.len() {
            return None;
        }

        let width = self.range.width();
        if width == 0 {
            return None;
        }

        let row = (self.linear_idx / width as u64) as usize;
        let col = (self.linear_idx % width as u64) as usize;

        let run = &self.range.runs[self.run_idx];
        let style = self.range.palette.get(run.style_id as usize)?;

        self.linear_idx += 1;
        self.run_offset += 1;

        if self.run_offset >= run.count {
            self.run_idx += 1;
            self.run_offset = 0;
        }

        Some((row, col, style))
    }
}

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

    #[test]
    fn test_color() {
        let color = Color::rgb(255, 0, 128);
        assert_eq!(color.red, 255);
        assert_eq!(color.green, 0);
        assert_eq!(color.blue, 128);
        assert_eq!(color.alpha, 255);
        assert_eq!(color.to_string(), "#FF0080");
    }

    #[test]
    fn test_font() {
        let font = Font::new()
            .with_name("Arial".to_string())
            .with_size(12.0)
            .with_weight(FontWeight::Bold)
            .with_color(Color::rgb(255, 0, 0));

        assert_eq!(font.name, Some("Arial".to_string()));
        assert_eq!(font.size, Some(12.0));
        assert!(font.is_bold());
        assert_eq!(font.color, Some(Color::rgb(255, 0, 0)));
    }

    #[test]
    fn test_style() {
        let style = Style::new()
            .with_font(Font::new().with_name("Arial".to_string()))
            .with_fill(Fill::solid(Color::rgb(255, 255, 0)));

        assert!(!style.is_empty());
        assert!(style.get_font().is_some());
        assert!(style.get_fill().is_some());
    }

    #[test]
    fn test_border_with_color() {
        let border = Border::with_color(BorderStyle::Thin, Color::rgb(255, 0, 0));
        assert_eq!(border.style, BorderStyle::Thin);
        assert_eq!(border.color, Some(Color::rgb(255, 0, 0)));
        assert!(border.is_visible());
    }

    #[test]
    fn test_border_without_color() {
        let border = Border::new(BorderStyle::Medium);
        assert_eq!(border.style, BorderStyle::Medium);
        assert_eq!(border.color, None);
        assert!(border.is_visible());
    }

    #[test]
    fn test_borders_with_mixed_colors() {
        let mut borders = Borders::new();
        borders.left = Border::with_color(BorderStyle::Thin, Color::rgb(255, 0, 0));
        borders.right = Border::new(BorderStyle::Medium);
        borders.top = Border::with_color(BorderStyle::Thick, Color::rgb(0, 255, 0));

        assert_eq!(borders.left.color, Some(Color::rgb(255, 0, 0)));
        assert_eq!(borders.right.color, None);
        assert_eq!(borders.top.color, Some(Color::rgb(0, 255, 0)));
        assert!(borders.has_visible_borders());
    }

    #[test]
    fn test_column_width() {
        let column_width = ColumnWidth::new(5, 12.5)
            .with_custom_width(true)
            .with_hidden(false)
            .with_best_fit(true);

        assert_eq!(column_width.column, 5);
        assert_eq!(column_width.width, 12.5);
        assert!(column_width.custom_width);
        assert!(!column_width.hidden);
        assert!(column_width.best_fit);
        assert!(column_width.is_visible());
    }

    #[test]
    fn test_row_height() {
        let row_height = RowHeight::new(10, 20.0)
            .with_custom_height(true)
            .with_hidden(false)
            .with_thick_top(true)
            .with_thick_bottom(false);

        assert_eq!(row_height.row, 10);
        assert_eq!(row_height.height, 20.0);
        assert!(row_height.custom_height);
        assert!(!row_height.hidden);
        assert!(row_height.thick_top);
        assert!(!row_height.thick_bottom);
        assert!(row_height.is_visible());
    }

    #[test]
    fn test_worksheet_layout() {
        let layout = WorksheetLayout::new()
            .add_column_width(ColumnWidth::new(0, 10.0))
            .add_column_width(ColumnWidth::new(1, 15.0))
            .add_row_height(RowHeight::new(0, 18.0))
            .add_row_height(RowHeight::new(1, 22.0))
            .with_default_column_width(8.43)
            .with_default_row_height(15.0);

        assert_eq!(layout.column_widths.len(), 2);
        assert_eq!(layout.row_heights.len(), 2);
        assert_eq!(layout.default_column_width, Some(8.43));
        assert_eq!(layout.default_row_height, Some(15.0));
        assert!(layout.has_custom_dimensions());

        // Test getting specific column width
        let col_width = layout.get_column_width(0).unwrap();
        assert_eq!(col_width.width, 10.0);

        // Test getting specific row height
        let row_height = layout.get_row_height(1).unwrap();
        assert_eq!(row_height.height, 22.0);

        // Test effective widths/heights
        assert_eq!(layout.get_effective_column_width(0), 10.0); // Custom width
        assert_eq!(layout.get_effective_column_width(5), 8.43); // Default width
        assert_eq!(layout.get_effective_row_height(0), 18.0); // Custom height
        assert_eq!(layout.get_effective_row_height(5), 15.0); // Default height
    }

    #[test]
    fn test_worksheet_layout_defaults() {
        let layout = WorksheetLayout::new();

        assert!(!layout.has_custom_dimensions());
        assert_eq!(layout.get_effective_column_width(0), 8.43); // Excel default
        assert_eq!(layout.get_effective_row_height(0), 15.0); // Excel default
    }
}