File size: 46,965 Bytes
d97b8f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { createEditor, Descendant, Element as SlateElement, Transforms, Editor, BaseEditor, Node } from 'slate';
import { Slate, Editable, withReact, RenderElementProps, RenderLeafProps, ReactEditor } from 'slate-react';
import { withHistory, HistoryEditor } from 'slate-history';
import { Button } from '@/components/ui/button';
import { Bold, Italic, Underline, List, ListOrdered, AlignLeft, AlignCenter, AlignRight, Indent, Outdent, Palette } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

type RichTextEditorProps = {
  initialValue?: string;
  onChange: (value: string) => void;
  placeholder?: string;
  readOnly?: boolean;
  disabled?: boolean;
  minHeight?: string;
  className?: string;
};

// Define the type for text nodes
type CustomText = {
  text: string;
  bold?: boolean;
  italic?: boolean;
  underline?: boolean;
  color?: string;
};

// Define types for elements
type ParagraphElement = {
  type: 'paragraph';
  align?: 'left' | 'center' | 'right';
  indent?: number;
  children: CustomText[];
};

type ListItemElement = {
  type: 'list-item';
  align?: 'left' | 'center' | 'right';
  indent?: number;
  children: CustomText[];
};

type BulletedListElement = {
  type: 'bulleted-list';
  align?: 'left' | 'center' | 'right';
  indent?: number;
  children: ListItemElement[];
};

type NumberedListElement = {
  type: 'numbered-list';
  align?: 'left' | 'center' | 'right';
  indent?: number;
  children: ListItemElement[];
};

type CustomElement = ParagraphElement | ListItemElement | BulletedListElement | NumberedListElement;

// Fix type declarations for Slate
type CustomEditor = BaseEditor & ReactEditor & HistoryEditor;

declare module 'slate' {
  interface CustomTypes {
    Editor: BaseEditor & ReactEditor & HistoryEditor;
    Element: CustomElement;
    Text: CustomText;
  }
}

// Initial value for the editor
const initialValue: Descendant[] = [
  {
    type: 'paragraph',
    children: [{ text: '' }],
  },
];

// Helper to serialize editor content to HTML
const serializeToHtml = (nodes: Descendant[]): string => {
  return nodes
    .map(node => {
      if ('type' in node) {
        switch (node.type) {
          case 'paragraph':
            const textContent = node.children.map(child => {
              let text = child.text;
              if (child.bold) text = `<strong>${text}</strong>`;
              if (child.italic) text = `<em>${text}</em>`;
              if (child.underline) text = `<u>${text}</u>`;
              if (child.color) text = `<span style="color:${child.color}">${text}</span>`;
              return text;
            }).join('');
            const align = node.align ? ` style="text-align: ${node.align}` : '';
            const indent = node.indent ? `${align ? ';' : ' style="'}padding-left: ${node.indent * 24}px` : '';
            const style = (align || indent) ? `${align}${indent}"` : '';
            return `<p${style}>${textContent}</p>`;
          case 'bulleted-list':
            const ulAlign = node.align ? ` style="text-align: ${node.align}"` : '';
            const ulIndent = node.indent ? `${ulAlign ? ';' : ' style="'}padding-left: ${node.indent * 24}px"` : '';
            const ulStyle = (ulAlign || ulIndent) ? `${ulAlign}${ulIndent}"` : '';
            return `<ul${ulStyle}>${node.children.map(item => 

              `<li>${item.children.map(child => {

                let text = child.text;

                if (child.bold) text = `<strong>${text}</strong>`;

                if (child.italic) text = `<em>${text}</em>`;

                if (child.underline) text = `<u>${text}</u>`;

                if (child.color) text = `<span style="color:${child.color}">${text}</span>`;

                return text;

              }).join('')}</li>`

            ).join('')}</ul>`;
          case 'numbered-list':
            const olAlign = node.align ? ` style="text-align: ${node.align}"` : '';
            const olIndent = node.indent ? `${olAlign ? ';' : ' style="'}padding-left: ${node.indent * 24}px"` : '';
            const olStyle = (olAlign || olIndent) ? `${olAlign}${olIndent}"` : '';
            return `<ol${olStyle}>${node.children.map(item => 

              `<li>${item.children.map(child => {

                let text = child.text;

                if (child.bold) text = `<strong>${text}</strong>`;

                if (child.italic) text = `<em>${text}</em>`;

                if (child.underline) text = `<u>${text}</u>`;

                if (child.color) text = `<span style="color:${child.color}">${text}</span>`;

                return text;

              }).join('')}</li>`

            ).join('')}</ol>`;
          case 'list-item':
            const liAlign = node.align ? ` style="text-align: ${node.align}"` : '';
            const liIndent = node.indent ? `${liAlign ? ';' : ' style="'}padding-left: ${node.indent * 24}px"` : '';
            const liStyle = (liAlign || liIndent) ? `${liAlign}${liIndent}"` : '';
            return `<li${liStyle}>${node.children.map(child => {

              let text = child.text;

              if (child.bold) text = `<strong>${text}</strong>`;

              if (child.italic) text = `<em>${text}</em>`;

              if (child.underline) text = `<u>${text}</u>`;

              if (child.color) text = `<span style="color:${child.color}">${text}</span>`;

              return text;

            }).join('')}</li>`;
          default:
            return '';
        }
      } else {
        // It's a text node
        let text = node.text;
        if (node.bold) text = `<strong>${text}</strong>`;
        if (node.italic) text = `<em>${text}</em>`;
        if (node.underline) text = `<u>${text}</u>`;
        if (node.color) text = `<span style="color:${node.color}">${text}</span>`;
        return text;
      }
    })
    .join('');
};

// Improved HTML parser to handle more complex HTML content
const parseFromHtml = (html: string): Descendant[] => {
  if (!html) return initialValue;
  
  try {
    // Create a temporary DOM element to parse the HTML
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    
    const result: Descendant[] = [];
    
    // Check if we have a plain text with bullet characters (•)
    if (doc.body.textContent?.includes('•')) {
      const textContent = doc.body.textContent;
      const lines = textContent.split('\n').filter(line => line.trim().length > 0);
      
      // If we have bullet characters in text, convert to proper list format
      if (lines.some(line => line.trim().startsWith('•'))) {
        const listItems: ListItemElement[] = [];
        let currentParagraph: ParagraphElement | null = null;
        
        lines.forEach(line => {
          const trimmedLine = line.trim();
          if (trimmedLine.startsWith('•')) {
            // If we had a paragraph in progress, add it to result
            if (currentParagraph) {
              result.push(currentParagraph);
              currentParagraph = null;
            }
            
            // Add as a list item
            listItems.push({
              type: 'list-item',
              children: [{ text: trimmedLine.substring(1).trim() }]
            });
          } else {
            // If we had list items in progress, add them as a bulleted list
            if (listItems.length > 0) {
              result.push({
                type: 'bulleted-list',
                children: listItems
              });
              // Reset list items
              listItems.length = 0;
            }
            
            // Add as a paragraph
            if (!currentParagraph) {
              currentParagraph = {
                type: 'paragraph',
                children: [{ text: trimmedLine }]
              };
            } else {
              // Append to existing paragraph with a space
              currentParagraph.children[0].text += ' ' + trimmedLine;
            }
          }
        });
        
        // Add any remaining list items or paragraphs
        if (listItems.length > 0) {
          result.push({
            type: 'bulleted-list',
            children: listItems
          });
        }
        
        if (currentParagraph) {
          result.push(currentParagraph);
        }
        
        return result.length > 0 ? result : initialValue;
      }
    }
    
    // Process each top-level element normally
    Array.from(doc.body.childNodes).forEach(node => {
      if (node.nodeType === 1) { // ELEMENT_NODE is 1
        const element = node as Element;
        result.push(...parseElement(element));
      } else if (node.nodeType === 3 && node.textContent?.trim()) { // TEXT_NODE is 3
        // Handle direct text nodes
        result.push({ 
          type: 'paragraph',
          children: [{ text: node.textContent || '' }]
        });
      }
    });
    
    return result.length > 0 ? result : initialValue;
  } catch (e) {
    console.error('Error parsing HTML:', e);
    return initialValue;
  }
};

// Helper function to parse HTML elements recursively
const parseElement = (element: Element): Descendant[] => {
  const result: Descendant[] = [];
  
  // Handle different element types
  switch (element.tagName.toLowerCase()) {
    case 'p':
      // Handle paragraphs with formatting
      const paragraph: ParagraphElement = {
        type: 'paragraph',
        children: parseTextWithFormatting(element),
      };
      
      // Extract alignment and indentation if available
      const style = element.getAttribute('style');
      if (style) {
        if (style.includes('text-align: center')) {
          paragraph.align = 'center';
        } else if (style.includes('text-align: right')) {
          paragraph.align = 'right';
        } else if (style.includes('text-align: left')) {
          paragraph.align = 'left';
        }
        
        // Extract indentation
        const indentMatch = style.match(/padding-left:\s*(\d+)px/i);
        if (indentMatch && indentMatch[1]) {
          const indentPx = parseInt(indentMatch[1], 10);
          paragraph.indent = Math.round(indentPx / 24); // Convert px to our indent level
        }
      }
      
      result.push(paragraph);
      break;
      
    case 'div':
      // Special case for divs that might be containing bulleted lists with specific styling
      if (element.innerHTML.includes('•') || 
          element.innerHTML.includes('&#8226;') ||
          element.innerHTML.includes('&bull;')) {
        // Try to extract bullet points
        const children = Array.from(element.childNodes);
        const listItems: ListItemElement[] = [];
        
        children.forEach(child => {
          if (child.nodeType === 3) { // TEXT_NODE
            const text = child.textContent || '';
            if (text.trim().startsWith('•') || text.trim().startsWith('●')) {
              listItems.push({
                type: 'list-item',
                children: [{ text: text.replace(/^[•●]\s*/, '') }]
              });
            }
          } else if (child.nodeType === 1) { // ELEMENT_NODE
            const childElement = child as Element;
            const text = childElement.textContent || '';
            if (text.trim().startsWith('•') || text.trim().startsWith('●')) {
              listItems.push({
                type: 'list-item',
                children: parseTextWithFormatting(childElement).map(node => {
                  // Remove bullet character
                  if (typeof node.text === 'string') {
                    return { ...node, text: node.text.replace(/^[•●]\s*/, '') };
                  }
                  return node;
                })
              });
            }
          }
        });
        
        if (listItems.length > 0) {
          result.push({
            type: 'bulleted-list',
            children: listItems
          });
          break;
        }
      }
      
      // For regular divs, process children and create a paragraph
      const children = parseTextWithFormatting(element);
      const divStyle = element.getAttribute('style');
      const divParagraph: ParagraphElement = {
        type: 'paragraph',
        children,
      };
      
      if (divStyle) {
        if (divStyle.includes('text-align: center')) {
          divParagraph.align = 'center';
        } else if (divStyle.includes('text-align: right')) {
          divParagraph.align = 'right';
        } else if (divStyle.includes('text-align: left')) {
          divParagraph.align = 'left';
        }
        
        // Extract indentation
        const divIndentMatch = divStyle.match(/padding-left:\s*(\d+)px/i);
        if (divIndentMatch && divIndentMatch[1]) {
          const indentPx = parseInt(divIndentMatch[1], 10);
          divParagraph.indent = Math.round(indentPx / 24);
        }
      }
      
      result.push(divParagraph);
      break;
      
    case 'h1':
    case 'h2':
    case 'h3':
    case 'h4':
    case 'h5':
    case 'h6':
      // For headings, create a paragraph with formatting
      const headingStyle = element.getAttribute('style');
      const headingParagraph: ParagraphElement = {
        type: 'paragraph',
        children: parseTextWithFormatting(element),
      };
      
      if (headingStyle) {
        if (headingStyle.includes('text-align: center')) {
          headingParagraph.align = 'center';
        } else if (headingStyle.includes('text-align: right')) {
          headingParagraph.align = 'right';
        } else if (headingStyle.includes('text-align: left')) {
          headingParagraph.align = 'left';
        }
        
        // Extract indentation
        const headingIndentMatch = headingStyle.match(/padding-left:\s*(\d+)px/i);
        if (headingIndentMatch && headingIndentMatch[1]) {
          const indentPx = parseInt(headingIndentMatch[1], 10);
          headingParagraph.indent = Math.round(indentPx / 24);
        }
      }
      
      result.push(headingParagraph);
      break;
      
    case 'ul':
      // Handle unordered lists - first check if it's empty
      const listItems = Array.from(element.querySelectorAll('li'));
      if (listItems.length > 0) {
        const ulStyle = element.getAttribute('style');
        const list: BulletedListElement = {
          type: 'bulleted-list',
          children: listItems.map(li => {
            const liStyle = li.getAttribute('style');
            const listItem: ListItemElement = {
              type: 'list-item',
              children: parseTextWithFormatting(li),
            };
            
            if (liStyle) {
              if (liStyle.includes('text-align: center')) {
                listItem.align = 'center';
              } else if (liStyle.includes('text-align: right')) {
                listItem.align = 'right';
              } else if (liStyle.includes('text-align: left')) {
                listItem.align = 'left';
              }
              
              // Extract indentation for list item
              const liIndentMatch = liStyle.match(/padding-left:\s*(\d+)px/i);
              if (liIndentMatch && liIndentMatch[1]) {
                const indentPx = parseInt(liIndentMatch[1], 10);
                listItem.indent = Math.round(indentPx / 24);
              }
            }
            
            return listItem;
          }),
        };
        
        if (ulStyle) {
          if (ulStyle.includes('text-align: center')) {
            list.align = 'center';
          } else if (ulStyle.includes('text-align: right')) {
            list.align = 'right';
          } else if (ulStyle.includes('text-align: left')) {
            list.align = 'left';
          }
          
          // Extract indentation for the list
          const ulIndentMatch = ulStyle.match(/padding-left:\s*(\d+)px/i);
          if (ulIndentMatch && ulIndentMatch[1]) {
            const indentPx = parseInt(ulIndentMatch[1], 10);
            list.indent = Math.round(indentPx / 24);
          }
        }
        
        result.push(list);
      }
      break;
      
    case 'ol':
      // Handle ordered lists - first check if it's empty
      const orderedListItems = Array.from(element.querySelectorAll('li'));
      if (orderedListItems.length > 0) {
        const olStyle = element.getAttribute('style');
        const orderedList: NumberedListElement = {
          type: 'numbered-list',
          children: orderedListItems.map(li => {
            const liStyle = li.getAttribute('style');
            const listItem: ListItemElement = {
              type: 'list-item',
              children: parseTextWithFormatting(li),
            };
            
            if (liStyle) {
              if (liStyle.includes('text-align: center')) {
                listItem.align = 'center';
              } else if (liStyle.includes('text-align: right')) {
                listItem.align = 'right';
              } else if (liStyle.includes('text-align: left')) {
                listItem.align = 'left';
              }
              
              // Extract indentation for list item
              const liIndentMatch = liStyle.match(/padding-left:\s*(\d+)px/i);
              if (liIndentMatch && liIndentMatch[1]) {
                const indentPx = parseInt(liIndentMatch[1], 10);
                listItem.indent = Math.round(indentPx / 24);
              }
            }
            
            return listItem;
          }),
        };
        
        if (olStyle) {
          if (olStyle.includes('text-align: center')) {
            orderedList.align = 'center';
          } else if (olStyle.includes('text-align: right')) {
            orderedList.align = 'right';
          } else if (olStyle.includes('text-align: left')) {
            orderedList.align = 'left';
          }
          
          // Extract indentation for the list
          const olIndentMatch = olStyle.match(/padding-left:\s*(\d+)px/i);
          if (olIndentMatch && olIndentMatch[1]) {
            const indentPx = parseInt(olIndentMatch[1], 10);
            orderedList.indent = Math.round(indentPx / 24);
          }
        }
        
        result.push(orderedList);
      }
      break;
      
    case 'li':
      // Create standalone list item if not in a list context
      const liItemStyle = element.getAttribute('style');
      const listItem: ListItemElement = {
        type: 'list-item',
        children: parseTextWithFormatting(element),
      };
      
      if (liItemStyle) {
        if (liItemStyle.includes('text-align: center')) {
          listItem.align = 'center';
        } else if (liItemStyle.includes('text-align: right')) {
          listItem.align = 'right';
        } else if (liItemStyle.includes('text-align: left')) {
          listItem.align = 'left';
        }
        
        // Extract indentation
        const liItemIndentMatch = liItemStyle.match(/padding-left:\s*(\d+)px/i);
        if (liItemIndentMatch && liItemIndentMatch[1]) {
          const indentPx = parseInt(liItemIndentMatch[1], 10);
          listItem.indent = Math.round(indentPx / 24);
        }
      }
      
      result.push(listItem);
      break;
      
    case 'br':
      // Handle line breaks by creating a new paragraph
      result.push({
        type: 'paragraph',
        children: [{ text: '' }],
      });
      break;
      
    default:
      // For other elements, recursively process children
      let hasAddedContent = false;
      
      Array.from(element.childNodes).forEach(childNode => {
        if (childNode.nodeType === 1) { // ELEMENT_NODE
          const childResults = parseElement(childNode as Element);
          if (childResults.length > 0) {
            result.push(...childResults);
            hasAddedContent = true;
          }
        } else if (childNode.nodeType === 3 && childNode.textContent?.trim()) { // TEXT_NODE is 3
          result.push({
            type: 'paragraph',
            children: [{ text: childNode.textContent || '' }],
          });
          hasAddedContent = true;
        }
      });
      
      // If no content was added but the element has text, add it as a paragraph
      if (!hasAddedContent && element.textContent?.trim()) {
        result.push({
          type: 'paragraph',
          children: [{ text: element.textContent || '' }],
        });
      }
  }
  
  return result;
};

// Parse text with inline formatting
const parseTextWithFormatting = (element: Element): CustomText[] => {
  const result: CustomText[] = [];
  
  // If there's only text content and no children with formatting, return a simple text node
  if (!element.childNodes.length || 
      (element.childNodes.length === 1 && element.childNodes[0].nodeType === 3)) { // TEXT_NODE is 3
    return [{ text: element.textContent || '' }];
  }
  
  // Process each child node to handle formatting
  Array.from(element.childNodes).forEach(node => {
    if (node.nodeType === 3) { // TEXT_NODE
      // Handle text nodes
      if (node.textContent?.trim()) {
        result.push({ text: node.textContent || '' });
      }
    } else if (node.nodeType === 1) { // ELEMENT_NODE
      const childElement = node as Element;
      const tagName = childElement.tagName.toLowerCase();
      
      // Handle formatting elements
      switch (tagName) {
        case 'strong':
        case 'b':
          result.push({ text: childElement.textContent || '', bold: true });
          break;
          
        case 'em':
        case 'i':
          result.push({ text: childElement.textContent || '', italic: true });
          break;
          
        case 'u':
          result.push({ text: childElement.textContent || '', underline: true });
          break;
          
        case 'span':
          // Process span with potential inline styling
          const spanStyle = childElement.getAttribute('style');
          const text = childElement.textContent || '';
          const formatting: Partial<CustomText> = { text };
          
          if (spanStyle) {
            if (spanStyle.includes('font-weight: bold') || spanStyle.includes('font-weight:bold')) {
              formatting.bold = true;
            }
            if (spanStyle.includes('font-style: italic') || spanStyle.includes('font-style:italic')) {
              formatting.italic = true;
            }
            if (spanStyle.includes('text-decoration: underline') || spanStyle.includes('text-decoration:underline')) {
              formatting.underline = true;
            }
            
            // Extract color if present
            const colorMatch = spanStyle.match(/color:\s*(#[0-9a-f]{3,6}|rgb\([^)]+\)|[a-z]+)/i);
            if (colorMatch && colorMatch[1]) {
              formatting.color = colorMatch[1];
            }
          }
          
          result.push(formatting as CustomText);
          break;
          
        default:
          // Recursively handle other elements
          result.push(...parseTextWithFormatting(childElement));
      }
    }
  });
  
  return result;
};

// Format button component
type FormatButtonProps = {
  format: string;
  icon: React.ReactNode;
  isActive?: boolean;
  onMouseDown: (e: React.MouseEvent) => void;
};

const FormatButton: React.FC<FormatButtonProps> = ({ 

  format, 

  icon, 

  isActive = false, 

  onMouseDown 

}) => {
  return (
    <Button

      type="button"

      variant={isActive ? "default" : "ghost"}

      size="sm"

      onMouseDown={onMouseDown}

      className="h-8 w-8 p-0"

      title={format.charAt(0).toUpperCase() + format.slice(1)}

    >

      {icon}

    </Button>
  );
};

// Custom type for Slate Element props with align support
interface CustomRenderElementProps extends Omit<RenderElementProps, 'element'> {
  element: CustomElement;
}

// Element renderer
const Element = ({ attributes, children, element }: CustomRenderElementProps) => {
  const style: React.CSSProperties = { 
    textAlign: element.align as React.CSSProperties['textAlign'] || undefined
  };
  
  // Apply indentation with more visible styling
  if (element.indent) {
    style.paddingLeft = `${element.indent * 24}px`;
    style.borderLeft = '2px solid #e2e8f0';
    style.marginLeft = '8px';
  }
  
  switch (element.type) {
    case 'bulleted-list':
      return <ul {...attributes} className="list-disc ml-6" style={style}>{children}</ul>;
    case 'numbered-list':
      return <ol {...attributes} className="list-decimal ml-6" style={style}>{children}</ol>;
    case 'list-item':
      return <li {...attributes} style={style}>{children}</li>;
    default:
      return <p {...attributes} style={style}>{children}</p>;
  }
};

// Leaf renderer
const Leaf = ({ attributes, children, leaf }: RenderLeafProps) => {
  let style: React.CSSProperties = {};
  
  // Apply color if specified
  if (leaf.color) {
    style.color = leaf.color;
  }
  
  let textElement = <span {...attributes} style={style}>{children}</span>;
  
  if (leaf.bold) {
    textElement = <strong>{textElement}</strong>;
  }
  
  if (leaf.italic) {
    textElement = <em>{textElement}</em>;
  }
  
  if (leaf.underline) {
    textElement = <u>{textElement}</u>;
  }
  
  return textElement;
};

// Custom editor commands
const CustomEditor = {
  isMarkActive(editor: CustomEditor, format: string) {
    const marks = Editor.marks(editor);
    return marks ? marks[format] === true : false;
  },

  isBlockActive(editor: CustomEditor, format: string, attributeName = 'type') {
    const { selection } = editor;
    if (!selection) return false;

    try {
      const [match] = Array.from(
        Editor.nodes(editor, {
          at: Editor.unhangRange(editor, selection),
          match: n => 
            !Editor.isEditor(n) && 
            SlateElement.isElement(n) && 
            (n as any)[attributeName] === format,
        })
      );
      
      return !!match;
    } catch (error) {
      console.error('Error checking block active state:', error);
      return false;
    }
  },

  toggleMark(editor: CustomEditor, format: string) {
    const isActive = CustomEditor.isMarkActive(editor, format);
    
    if (isActive) {
      Editor.removeMark(editor, format);
    } else {
      Editor.addMark(editor, format, true);
    }
  },

  toggleBlock(editor: CustomEditor, format: string) {
    const isActive = CustomEditor.isBlockActive(editor, format);
    
    Transforms.unwrapNodes(editor, {
      match: n => 
        !Editor.isEditor(n) && 
        SlateElement.isElement(n) && 
        ['bulleted-list', 'numbered-list'].includes((n as any).type),
      split: true,
    });
    
    const newProperties: Partial<CustomElement> = {
      type: isActive ? 'paragraph' : format === 'bulleted-list' || format === 'numbered-list' 
        ? 'list-item' 
        : format as any
    };
    
    Transforms.setNodes(editor, newProperties, {
      match: n => !Editor.isEditor(n) && SlateElement.isElement(n),
    });
    
    if (!isActive && (format === 'bulleted-list' || format === 'numbered-list')) {
      const block = { type: format, children: [] };
      Transforms.wrapNodes(editor, block as any);
    }
  },

  toggleAlign(editor: CustomEditor, alignment: 'left' | 'center' | 'right') {
    // Check if the current alignment is already active
    const isActive = CustomEditor.isBlockActive(editor, alignment, 'align');
    
    // Set or unset the alignment
    const newProperties: Partial<CustomElement> = { 
      align: isActive ? undefined : alignment 
    };
    
    Transforms.setNodes(editor, newProperties, {
      match: n => !Editor.isEditor(n) && SlateElement.isElement(n),
    });
  },

  setColor(editor: CustomEditor, color: string) {
    Editor.addMark(editor, 'color', color);
  },

  increaseIndent(editor: CustomEditor) {
    const { selection } = editor;
    if (!selection) return;

    try {
      const nodeEntries = Editor.nodes(editor, {
        at: selection,
        match: n => !Editor.isEditor(n) && SlateElement.isElement(n),
      });

      for (const [node, path] of nodeEntries) {
        const element = node as CustomElement;
        const currentIndent = element.indent || 0;
        
        if (currentIndent < 5) {
          Transforms.setNodes(
            editor,
            { indent: currentIndent + 1 } as Partial<CustomElement>,
            { at: path }
          );
        }
      }
    } catch (error) {
      console.error('Error increasing indent:', error);
    }
  },

  decreaseIndent(editor: CustomEditor) {
    const { selection } = editor;
    if (!selection) return;

    try {
      const nodeEntries = Editor.nodes(editor, {
        at: selection,
        match: n => !Editor.isEditor(n) && SlateElement.isElement(n),
      });

      for (const [node, path] of nodeEntries) {
        const element = node as CustomElement;
        const currentIndent = element.indent || 0;
        
        if (currentIndent > 0) {
          Transforms.setNodes(
            editor,
            { indent: currentIndent - 1 } as Partial<CustomElement>,
            { at: path }
          );
        }
      }
    } catch (error) {
      console.error('Error decreasing indent:', error);
    }
  }
};

const colorOptions = [
  { color: '#000000', label: 'Black' },
  { color: '#1C7ED6', label: 'Blue' },
  { color: '#2B8A3E', label: 'Green' },
  { color: '#E03131', label: 'Red' },
  { color: '#F59F00', label: 'Orange' },
  { color: '#7048E8', label: 'Purple' },
  { color: '#868E96', label: 'Gray' },
];

// Custom color picker with custom popover
const ColorButton: React.FC<{   
  onSelectColor: (color: string) => void,  
  activeColor?: string
}> = ({ onSelectColor, activeColor = "#000000" }) => {
  // State to track if the color picker is open
  const [isOpen, setIsOpen] = useState(false);
  // Reference to the button element
  const buttonRef = useRef<HTMLButtonElement>(null);
  // Reference to the dropdown element
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close the dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        isOpen &&        
        dropdownRef.current &&        
        buttonRef.current &&        
        !dropdownRef.current.contains(event.target as Element) &&        
        !buttonRef.current.contains(event.target as Element)
      ) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  const handleButtonClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsOpen(!isOpen);
  };

  return (
    <div className="relative inline-block">

      <Button

        ref={buttonRef}

        type="button"

        variant="ghost"

        size="sm"

        className="h-8 w-8 p-0 relative"

        title="Text Color"

        onMouseDown={handleButtonClick}

      >

        <Palette className="h-4 w-4" />

        <div 

          className="absolute bottom-1 right-1 w-2 h-2 rounded-full border border-white"

          style={{ backgroundColor: activeColor }}

        />

      </Button>



      {isOpen && (

        <div

          ref={dropdownRef}

          className="absolute z-50 mt-1 w-40 p-2 bg-popover shadow-md rounded-md border border-border"

          style={{ top: "100%", left: "50%", transform: "translateX(-50%)" }}

        >

          <div className="flex flex-wrap gap-1">{colorOptions.map((colorOption) => (

            <Button

              key={colorOption.color}

              type="button"

              variant="ghost"

              size="sm"

              className="h-6 w-6 p-0 rounded-sm"

              style={{ backgroundColor: colorOption.color }}

              title={colorOption.label}

              onMouseDown={(e) => {

                e.preventDefault();

                e.stopPropagation();

                onSelectColor(colorOption.color);

                setIsOpen(false);

              }}

            />

          ))}</div>

        </div>

      )}

    </div>
  );
};

export const SlateRichTextEditor: React.FC<RichTextEditorProps> = ({

  initialValue: initialContent = '',

  onChange,

  placeholder = 'Enter text...',

  readOnly = false,

  disabled = false,

  minHeight = '100px',

  className = '',

}) => {
  // Create a Slate editor object that won't change across renders
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  
  // Keep track of state for the formatting buttons
  const [formats, setFormats] = useState({
    bold: false,
    italic: false,
    underline: false,
    'bulleted-list': false,
    'numbered-list': false,
    'align-left': false,
    'align-center': false,
    'align-right': false,
  });
  
  // Track the current text color
  const [currentColor, setCurrentColor] = useState('#000000');
  
  // Initialize content from props
  const [editorValue, setEditorValue] = useState<Descendant[]>(() => 
    parseFromHtml(initialContent)
  );
  
  // Use a key to force remount when initialContent changes
  const [editorKey, setEditorKey] = useState(0);
  
  useEffect(() => {
    const newValue = parseFromHtml(initialContent);
    setEditorValue(newValue);
    setEditorKey(prev => prev + 1);
  }, [initialContent]);
  
  // Update content and trigger onChange
  const handleChange = (value: Descendant[]) => {
    setEditorValue(value);
    
    // Update format states based on current selection
    const selection = editor.selection;
    if (selection) {
      // Check text formatting
      setFormats(prevFormats => ({
        ...prevFormats,
        bold: CustomEditor.isMarkActive(editor, 'bold'),
        italic: CustomEditor.isMarkActive(editor, 'italic'),
        underline: CustomEditor.isMarkActive(editor, 'underline'),
        'bulleted-list': CustomEditor.isBlockActive(editor, 'bulleted-list'),
        'numbered-list': CustomEditor.isBlockActive(editor, 'numbered-list'),
      }));
      
      // Check current color
      const marks = Editor.marks(editor);
      if (marks && marks.color) {
        setCurrentColor(marks.color as string);
      }
    }
    
    // Convert to HTML and trigger the onChange
    const htmlContent = serializeToHtml(value);
    onChange(htmlContent);
  };
  
  // Define a rendering function for custom elements
  const renderElement = useCallback((props: RenderElementProps) => {
    return <Element {...props as CustomRenderElementProps} />;
  }, []);
  
  // Define a rendering function for custom text nodes
  const renderLeaf = useCallback((props: RenderLeafProps) => <Leaf {...props} />, []);
  
  // Toggle mark function
  const toggleMark = (e: React.MouseEvent, format: string) => {
    e.preventDefault();
    e.stopPropagation(); // Prevent event bubbling
    
    if (format === 'bold' || format === 'italic' || format === 'underline') {
      // For text formatting
      CustomEditor.toggleMark(editor, format);
      
      // Update format state
      setFormats(prev => ({
        ...prev,
        [format]: !CustomEditor.isMarkActive(editor, format),
      }));
    } else if (format.startsWith('align-')) {
      // For alignment
      const align = format.replace('align-', '') as 'left' | 'center' | 'right';
      
      // Check if this alignment is already active
      const isActive = CustomEditor.isBlockActive(editor, align, 'align');
      
      // Clear other alignment formats
      setFormats(prev => ({
        ...prev,
        'align-left': format === 'align-left' && !isActive,
        'align-center': format === 'align-center' && !isActive,
        'align-right': format === 'align-right' && !isActive,
      }));
      
      // Set alignment on the current block
      CustomEditor.toggleAlign(editor, align);
    } else if (format === 'bulleted-list' || format === 'numbered-list') {
      // For lists
      CustomEditor.toggleBlock(editor, format);
      
      // Update format state
      setFormats(prev => ({
        ...prev,
        'bulleted-list': format === 'bulleted-list' && !prev['bulleted-list'],
        'numbered-list': format === 'numbered-list' && !prev['numbered-list'],
      }));
    }
  };
  
  // Handle paste to preserve formatting
  const handlePaste = useCallback(
    (event: React.ClipboardEvent) => {
      event.preventDefault();
      
      // Get clipboard data
      const clipboardData = event.clipboardData;
      
      // Try to get HTML content first
      let html = clipboardData.getData('text/html');
      const plainText = clipboardData.getData('text/plain');
      
      // Check if plain text has bullet points
      const hasBulletPoints = plainText.includes('•') || plainText.includes('●') || 
                              (/^\s*[-*]\s+/m).test(plainText);
      
      // If no HTML or we detect bullet points in plain text, handle specially
      if (!html.trim() || hasBulletPoints) {
        // If we detect markdown-style lists or bullet characters
        if (hasBulletPoints || (/^\s*[-*]\s+/m).test(plainText)) {
          const lines = plainText.split('\n').filter(line => line.trim().length > 0);
          const bulletedItems: ListItemElement[] = [];
          const paragraphs: ParagraphElement[] = [];
          
          lines.forEach(line => {
            const trimmedLine = line.trim();
            // Match various bullet styles: •, ●, -, *
            if (trimmedLine.startsWith('•') || trimmedLine.startsWith('●') || 
                trimmedLine.match(/^\s*[-*]\s+/)) {
              // Add as list item, stripping the bullet character
              bulletedItems.push({
                type: 'list-item',
                children: [{ 
                  text: trimmedLine.replace(/^[•●]|\s*[-*]\s+/, '').trim() 
                }]
              });
            } else {
              // Regular paragraph
              paragraphs.push({
                type: 'paragraph',
                children: [{ text: trimmedLine }]
              });
            }
          });
          
          // Insert paragraphs and list items
          if (paragraphs.length > 0) {
            editor.insertFragment(paragraphs as any);
          }
          
          if (bulletedItems.length > 0) {
            editor.insertFragment([{
              type: 'bulleted-list',
              children: bulletedItems
            }] as any);
          }
          
          return;
        }
        
        // If no special formatting detected, insert as plain text
        if (plainText) {
          editor.insertText(plainText);
        }
        return;
      }
      
      // Create valid HTML if it seems like a fragment
      if (!html.includes('<html') && !html.includes('<body')) {
        html = `<html><body>${html}</body></html>`;
      }
      
      // Parse HTML content to Slate format
      const parsed = parseFromHtml(html);
      
      // Insert the parsed content
      editor.insertFragment(parsed);
    },
    [editor]
  );
  
  // Add debug logging for input events
  const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
    console.log('Key down event:', event.key);
  }, [editor]);

  // Ensure editor focuses on click
  const handleClick = useCallback((event: React.MouseEvent<HTMLDivElement>) => {
    console.log('Editor clicked, focusing');
    ReactEditor.focus(editor);
  }, [editor]);
  
  // Handle indent/outdent
  const handleIndent = (e: React.MouseEvent, increase: boolean) => {
    e.preventDefault();
    e.stopPropagation();
    
    // Get the current selection
    const { selection } = editor;
    if (!selection) {
      console.warn('No selection to indent');
      return;
    }
    
    // Create a reusable function to help with indentation
    const modifyIndent = (element: CustomElement) => {
      if (increase) {
        const currentIndent = element.indent || 0;
        if (currentIndent < 5) { // Limit max indent
          return { ...element, indent: currentIndent + 1 };
        }
      } else {
        const currentIndent = element.indent || 0;
        if (currentIndent > 0) {
          return { ...element, indent: currentIndent - 1 };
        }
      }
      return element;
    };
    
    // Apply the indentation to all selected blocks
    try {
      const startPoint = selection.anchor.path[0];
      const endPoint = selection.focus.path[0];
      
      // Determine the range of blocks to indent
      const start = Math.min(startPoint, endPoint);
      const end = Math.max(startPoint, endPoint);
      
      console.log(`Indenting blocks from ${start} to ${end}`);
      
      // Modify each block in the selection range
      for (let i = start; i <= end; i++) {
        const path = [i];
        const node = Node.get(editor, path) as CustomElement;
        
        if (SlateElement.isElement(node)) {
          // Get current indent value
          const currentIndent = node.indent || 0;
          const newIndent = increase 
            ? Math.min(currentIndent + 1, 5) // Increase with max limit of 5
            : Math.max(currentIndent - 1, 0); // Decrease with min limit of 0
          
          console.log(`Block ${i}: Changing indent from ${currentIndent} to ${newIndent}`);
          
          // Apply the change
          if (newIndent !== currentIndent) {
            Transforms.setNodes(
              editor,
              { indent: newIndent },
              { at: path }
            );
          }
        }
      }
      
      // Force update to ensure changes are reflected
      const html = serializeToHtml(editor.children as Descendant[]);
      console.log('Updated HTML:', html);
      onChange(html);
      
    } catch (error) {
      console.error('Error applying indentation:', error);
    }
  };
  
  // Handle color selection
  const handleColorSelect = (color: string) => {
    setCurrentColor(color);
    CustomEditor.setColor(editor, color);
  };
  
  return (
    <div 

      className={`border rounded-md ${className}`} 

      style={{ minHeight }}

      onClick={e => e.stopPropagation()}

    >

      <Slate

        key={editorKey}

        editor={editor}

        initialValue={editorValue}

        onChange={handleChange}

      >

        {!readOnly && !disabled && (

          <div 

            className="p-1 border-b flex flex-wrap gap-1 bg-muted/20"

            onMouseDown={e => e.stopPropagation()}

            onClick={e => e.stopPropagation()}

          >

            <FormatButton

              format="bold"

              icon={<Bold className="h-4 w-4" />}

              isActive={formats.bold}

              onMouseDown={(e) => toggleMark(e, 'bold')}

            />

            <FormatButton

              format="italic"

              icon={<Italic className="h-4 w-4" />}

              isActive={formats.italic}

              onMouseDown={(e) => toggleMark(e, 'italic')}

            />

            <FormatButton

              format="underline"

              icon={<Underline className="h-4 w-4" />}

              isActive={formats.underline}

              onMouseDown={(e) => toggleMark(e, 'underline')}

            />

            

            <ColorButton 

              onSelectColor={handleColorSelect} 

              activeColor={currentColor}

            />

            

            <div className="h-8 w-px bg-border mx-1" />

            

            <FormatButton

              format="bulleted-list"

              icon={<List className="h-4 w-4" />}

              isActive={formats['bulleted-list']}

              onMouseDown={(e) => toggleMark(e, 'bulleted-list')}

            />

            <FormatButton

              format="numbered-list"

              icon={<ListOrdered className="h-4 w-4" />}

              isActive={formats['numbered-list']}

              onMouseDown={(e) => toggleMark(e, 'numbered-list')}

            />

            

            <div className="h-8 w-px bg-border mx-1" />

            

            <FormatButton

              format="indent"

              icon={<Indent className="h-4 w-4" />}

              onMouseDown={(e) => handleIndent(e, true)}

            />

            <FormatButton

              format="outdent"

              icon={<Outdent className="h-4 w-4" />}

              onMouseDown={(e) => handleIndent(e, false)}

            />

            

            <div className="h-8 w-px bg-border mx-1" />

            

            <FormatButton

              format="align-left"

              icon={<AlignLeft className="h-4 w-4" />}

              isActive={formats['align-left']}

              onMouseDown={(e) => toggleMark(e, 'align-left')}

            />

            <FormatButton

              format="align-center"

              icon={<AlignCenter className="h-4 w-4" />}

              isActive={formats['align-center']}

              onMouseDown={(e) => toggleMark(e, 'align-center')}

            />

            <FormatButton

              format="align-right"

              icon={<AlignRight className="h-4 w-4" />}

              isActive={formats['align-right']}

              onMouseDown={(e) => toggleMark(e, 'align-right')}

            />

          </div>

        )}

        <Editable

          renderElement={renderElement}

          renderLeaf={renderLeaf}

          placeholder={placeholder || 'Enter some text...'}

          readOnly={readOnly || disabled}

          onKeyDown={handleKeyDown}

          onClick={handleClick}

          className={`outline-none p-3 ${minHeight || 'min-h-[100px]'}`}

          onPaste={handlePaste}

        />

      </Slate>

    </div>
  );
};

export default SlateRichTextEditor;