File size: 57,112 Bytes
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
 
 
26ebdd4
25f49c9
 
 
 
 
 
26ebdd4
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
25f49c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ebdd4
 
 
25f49c9
26ebdd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestor PDF - Poder Judicial de Neuquén</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
    <style>
        .dropzone {
            border: 2px dashed #3b82f6;
            border-radius: 0.5rem;
            transition: all 0.3s ease;
        }
        .dropzone.active {
            border-color: #10b981;
            background-color: #f0f9ff;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .signature-preview {
            border: 1px solid #e5e7eb;
            background-color: #f9fafb;
            min-height: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .progress-bar {
            height: 8px;
            background-color: #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #3b82f6;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- Encabezado -->
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="text-xl font-bold text-blue-800">Poder Judicial de Neuquén</div>
            <div class="text-xl font-bold text-gray-700">AIGDE</div>
        </div>
    </header>

    <!-- Contenido principal -->
    <main class="container mx-auto px-4 py-8">
        <div class="bg-white rounded-xl shadow-md overflow-hidden">
            <!-- Pestañas -->
            <div class="flex border-b">
                <button class="tab-btn px-6 py-3 font-medium text-gray-600 hover:text-blue-600 focus:outline-none border-b-2 border-transparent hover:border-blue-300 transition" data-tab="merge">
                    <i class="fas fa-object-group mr-2"></i> Unir PDFs
                </button>
                <button class="tab-btn px-6 py-3 font-medium text-gray-600 hover:text-blue-600 focus:outline-none border-b-2 border-transparent hover:border-blue-300 transition" data-tab="extract">
                    <i class="fas fa-cut mr-2"></i> Extraer páginas
                </button>
                <button class="tab-btn px-6 py-3 font-medium text-gray-600 hover:text-blue-600 focus:outline-none border-b-2 border-transparent hover:border-blue-300 transition" data-tab="compress">
                    <i class="fas fa-compress-alt mr-2"></i> Comprimir
                </button>
                <button class="tab-btn px-6 py-3 font-medium text-gray-600 hover:text-blue-600 focus:outline-none border-b-2 border-transparent hover:border-blue-300 transition" data-tab="sign">
                    <i class="fas fa-signature mr-2"></i> Firmar
                </button>
            </div>

            <!-- Contenido de pestañas -->
            <div class="p-6">
                <!-- Unir PDFs -->
                <div id="merge" class="tab-content active">
                    <h2 class="text-xl font-semibold mb-4 text-gray-800">Unir múltiples archivos PDF en uno solo</h2>
                    <div class="dropzone p-8 mb-4 text-center cursor-pointer" id="merge-dropzone">
                        <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-2"></i>
                        <p class="text-gray-600">Arrastra y suelta archivos PDF aquí o haz clic para seleccionar</p>
                        <input type="file" id="merge-files" class="hidden" accept=".pdf" multiple>
                    </div>
                    <div id="merge-file-list" class="mb-4 space-y-2"></div>
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="merge-number-pages" class="mr-2">
                                <span class="text-gray-700">Numerar páginas</span>
                            </label>
                        </div>
                        <button id="merge-btn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fas fa-object-group mr-2"></i> Unir PDFs
                        </button>
                    </div>
                    <div id="merge-progress" class="hidden">
                        <div class="mb-2 text-sm text-gray-600">Procesando...</div>
                        <div class="progress-bar">
                            <div id="merge-progress-fill" class="progress-fill" style="width: 0%"></div>
                        </div>
                    </div>
                </div>

                <!-- Extraer páginas -->
                <div id="extract" class="tab-content">
                    <h2 class="text-xl font-semibold mb-4 text-gray-800">Extraer páginas de un archivo PDF</h2>
                    <div class="dropzone p-8 mb-4 text-center cursor-pointer" id="extract-dropzone">
                        <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-2"></i>
                        <p class="text-gray-600">Arrastra y suelta un archivo PDF aquí o haz clic para seleccionar</p>
                        <input type="file" id="extract-file" class="hidden" accept=".pdf">
                    </div>
                    <div id="extract-file-info" class="hidden mb-4 p-3 bg-gray-50 rounded-md">
                        <div class="flex justify-between items-center">
                            <span class="font-medium text-gray-700" id="extract-file-name"></span>
                            <span class="text-sm text-gray-500" id="extract-page-count"></span>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Rango de páginas</label>
                            <input type="text" id="extract-range" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ej: 1-3, 5, 7-9">
                            <p class="text-xs text-gray-500 mt-1">Separa con comas los rangos (1-3) o páginas individuales (5)</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">O selecciona páginas</label>
                            <div id="extract-page-selector" class="flex flex-wrap gap-2 max-h-32 overflow-y-auto p-2 border border-gray-300 rounded-md"></div>
                        </div>
                    </div>
                    <div class="flex justify-end">
                        <button id="extract-btn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fas fa-cut mr-2"></i> Extraer páginas
                        </button>
                    </div>
                    <div id="extract-progress" class="hidden mt-4">
                        <div class="mb-2 text-sm text-gray-600">Procesando...</div>
                        <div class="progress-bar">
                            <div id="extract-progress-fill" class="progress-fill" style="width: 0%"></div>
                        </div>
                    </div>
                </div>

                <!-- Comprimir PDF -->
                <div id="compress" class="tab-content">
                    <h2 class="text-xl font-semibold mb-4 text-gray-800">Comprimir archivo PDF</h2>
                    <div class="dropzone p-8 mb-4 text-center cursor-pointer" id="compress-dropzone">
                        <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-2"></i>
                        <p class="text-gray-600">Arrastra y suelta un archivo PDF aquí o haz clic para seleccionar</p>
                        <input type="file" id="compress-file" class="hidden" accept=".pdf">
                    </div>
                    <div id="compress-file-info" class="hidden mb-4 p-3 bg-gray-50 rounded-md">
                        <div class="flex justify-between items-center">
                            <span class="font-medium text-gray-700" id="compress-file-name"></span>
                            <span class="text-sm text-gray-500" id="compress-file-size"></span>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nivel de compresión</label>
                        <div class="flex items-center space-x-4">
                            <input type="range" id="compress-level" min="1" max="10" value="5" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                            <span id="compress-level-value" class="text-sm font-medium text-gray-700 w-8">5</span>
                        </div>
                        <div class="flex justify-between text-xs text-gray-500 mt-1">
                            <span>Baja calidad</span>
                            <span>Alta calidad</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="compress-optimize-images" class="mr-2" checked>
                                <span class="text-gray-700">Optimizar imágenes</span>
                            </label>
                        </div>
                        <button id="compress-btn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fas fa-compress-alt mr-2"></i> Comprimir
                        </button>
                    </div>
                    <div id="compress-progress" class="hidden">
                        <div class="mb-2 text-sm text-gray-600">Comprimiendo...</div>
                        <div class="progress-bar">
                            <div id="compress-progress-fill" class="progress-fill" style="width: 0%"></div>
                        </div>
                    </div>
                    <div id="compress-result" class="hidden mt-4 p-3 bg-green-50 rounded-md border border-green-200">
                        <div class="flex justify-between items-center">
                            <div>
                                <h3 class="font-medium text-green-800">Compresión completada</h3>
                                <p class="text-sm text-green-600">Tamaño original: <span id="original-size" class="font-medium"></span></p>
                            </div>
                            <div class="text-right">
                                <p class="text-sm text-green-600">Tamaño comprimido: <span id="compressed-size" class="font-medium"></span></p>
                                <p class="text-sm text-green-600">Reducción: <span id="reduction-percent" class="font-medium"></span></p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Firmar PDF -->
                <div id="sign" class="tab-content">
                    <h2 class="text-xl font-semibold mb-4 text-gray-800">Firmar documento PDF</h2>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <div class="dropzone p-8 mb-4 text-center cursor-pointer" id="sign-dropzone">
                                <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-2"></i>
                                <p class="text-gray-600">Arrastra y suelta un archivo PDF aquí o haz clic para seleccionar</p>
                                <input type="file" id="sign-file" class="hidden" accept=".pdf">
                            </div>
                            <div id="sign-file-info" class="hidden mb-4 p-3 bg-gray-50 rounded-md">
                                <div class="flex justify-between items-center">
                                    <span class="font-medium text-gray-700" id="sign-file-name"></span>
                                    <span class="text-sm text-gray-500" id="sign-page-count"></span>
                                </div>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Página para firmar</label>
                                <select id="sign-page" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" disabled>
                                    <option value="last">Última página</option>
                                    <option value="first">Primera página</option>
                                    <option value="all">Todas las páginas</option>
                                    <option value="custom">Página específica</option>
                                </select>
                            </div>
                            <div id="sign-custom-page-container" class="hidden mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Número de página</label>
                                <input type="number" id="sign-custom-page" min="1" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Firma digital</label>
                                <div class="flex space-x-2 mb-2">
                                    <button id="sign-upload-btn" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-md text-sm transition">
                                        <i class="fas fa-upload mr-2"></i> Subir imagen
                                    </button>
                                    <button id="sign-draw-btn" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-md text-sm transition">
                                        <i class="fas fa-pen mr-2"></i> Dibujar firma
                                    </button>
                                    <button id="sign-token-btn" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-md text-sm transition">
                                        <i class="fas fa-key mr-2"></i> Usar e-Token
                                    </button>
                                </div>
                                <div class="signature-preview rounded-md mb-2" id="signature-preview">
                                    <p class="text-gray-400">Previsualización de la firma</p>
                                </div>
                                <input type="file" id="sign-image" class="hidden" accept="image/*">
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Posición de la firma</label>
                                <select id="sign-position" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option value="bottom-right">Inferior derecha</option>
                                    <option value="bottom-left">Inferior izquierda</option>
                                    <option value="top-right">Superior derecha</option>
                                    <option value="top-left">Superior izquierda</option>
                                    <option value="center">Centro</option>
                                </select>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tamaño de la firma</label>
                                <input type="range" id="sign-size" min="50" max="200" value="100" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                                <div class="flex justify-between text-xs text-gray-500 mt-1">
                                    <span>Pequeño</span>
                                    <span>Grande</span>
                                </div>
                            </div>
                            <div class="flex justify-end">
                                <button id="sign-btn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                                    <i class="fas fa-signature mr-2"></i> Firmar documento
                                </button>
                            </div>
                        </div>
                    </div>
                    <div id="sign-progress" class="hidden mt-4">
                        <div class="mb-2 text-sm text-gray-600">Firmando documento...</div>
                        <div class="progress-bar">
                            <div id="sign-progress-fill" class="progress-fill" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Modal para dibujar firma -->
    <div id="draw-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
            <div class="p-4 border-b">
                <h3 class="text-lg font-medium text-gray-900">Dibuja tu firma</h3>
            </div>
            <div class="p-4">
                <canvas id="signature-canvas" class="border border-gray-300 w-full" height="200"></canvas>
            </div>
            <div class="p-4 border-t flex justify-between">
                <button id="clear-signature" class="text-gray-600 hover:text-gray-800">
                    <i class="fas fa-eraser mr-2"></i> Limpiar
                </button>
                <div>
                    <button id="cancel-signature" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-md mr-2">
                        Cancelar
                    </button>
                    <button id="save-signature" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md">
                        Guardar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal para e-Token -->
    <div id="token-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
            <div class="p-4 border-b">
                <h3 class="text-lg font-medium text-gray-900">Firma con e-Token</h3>
            </div>
            <div class="p-4">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Seleccionar certificado</label>
                    <select id="token-certificate" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Seleccione un certificado --</option>
                        <option value="cert1">Certificado Digital 1 (Vencimiento: 15/12/2024)</option>
                        <option value="cert2">Certificado Digital 2 (Vencimiento: 30/06/2025)</option>
                    </select>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Contraseña</label>
                    <input type="password" id="token-password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ingrese la contraseña del token">
                </div>
                <div class="flex items-center mb-4">
                    <input type="checkbox" id="token-remember" class="mr-2">
                    <label for="token-remember" class="text-sm text-gray-700">Recordar contraseña durante esta sesión</label>
                </div>
            </div>
            <div class="p-4 border-t flex justify-end">
                <button id="cancel-token" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-md mr-2">
                    Cancelar
                </button>
                <button id="confirm-token" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md">
                    Confirmar
                </button>
            </div>
        </div>
    </div>

    <script>
        // Manejo de pestañas
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const tabId = btn.getAttribute('data-tab');
                
                // Desactivar todas las pestañas
                document.querySelectorAll('.tab-btn').forEach(b => {
                    b.classList.remove('border-blue-600', 'text-blue-600');
                    b.classList.add('border-transparent', 'text-gray-600');
                });
                
                // Activar la pestaña seleccionada
                btn.classList.remove('border-transparent', 'text-gray-600');
                btn.classList.add('border-blue-600', 'text-blue-600');
                
                // Ocultar todos los contenidos
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                
                // Mostrar el contenido seleccionado
                document.getElementById(tabId).classList.add('active');
            });
        });

        // Funcionalidad para Unir PDFs
        const mergeDropzone = document.getElementById('merge-dropzone');
        const mergeFilesInput = document.getElementById('merge-files');
        const mergeFileList = document.getElementById('merge-file-list');
        const mergeBtn = document.getElementById('merge-btn');
        const mergeProgress = document.getElementById('merge-progress');
        const mergeProgressFill = document.getElementById('merge-progress-fill');

        let mergeFiles = [];

        mergeDropzone.addEventListener('click', () => mergeFilesInput.click());
        mergeDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            mergeDropzone.classList.add('active');
        });
        mergeDropzone.addEventListener('dragleave', () => {
            mergeDropzone.classList.remove('active');
        });
        mergeDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            mergeDropzone.classList.remove('active');
            handleMergeFiles(e.dataTransfer.files);
        });

        mergeFilesInput.addEventListener('change', () => {
            handleMergeFiles(mergeFilesInput.files);
        });

        function handleMergeFiles(files) {
            mergeFiles = [];
            mergeFileList.innerHTML = '';
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file.type === 'application/pdf') {
                    mergeFiles.push(file);
                    
                    const fileItem = document.createElement('div');
                    fileItem.className = 'flex items-center justify-between p-2 bg-gray-50 rounded-md';
                    fileItem.innerHTML = `
                        <div class="flex items-center">
                            <i class="fas fa-file-pdf text-red-500 mr-2"></i>
                            <span class="text-sm">${file.name}</span>
                        </div>
                        <span class="text-xs text-gray-500">${formatFileSize(file.size)}</span>
                    `;
                    mergeFileList.appendChild(fileItem);
                }
            }
            
            mergeBtn.disabled = mergeFiles.length < 2;
        }

        mergeBtn.addEventListener('click', async () => {
            if (mergeFiles.length < 2) return;
            
            mergeProgress.classList.remove('hidden');
            mergeProgressFill.style.width = '0%';
            
            try {
                // Crear un nuevo PDF
                const { PDFDocument } = PDFLib;
                const mergedPdf = await PDFDocument.create();
                
                let progress = 0;
                const progressIncrement = 100 / mergeFiles.length;
                
                // Procesar cada archivo PDF
                for (const file of mergeFiles) {
                    const arrayBuffer = await file.arrayBuffer();
                    const pdfDoc = await PDFDocument.load(arrayBuffer);
                    
                    // Copiar páginas al PDF final
                    const pages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
                    pages.forEach(page => mergedPdf.addPage(page));
                    
                    // Actualizar progreso
                    progress += progressIncrement;
                    mergeProgressFill.style.width = `${Math.min(progress, 100)}%`;
                }
                
                // Guardar el PDF unido
                const mergedPdfBytes = await mergedPdf.save();
                const mergedPdfBlob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
                
                // Descargar el PDF
                const mergedName = `documento_unido_${new Date().toISOString().slice(0, 10)}.pdf`;
                download(mergedPdfBlob, mergedName, 'application/pdf');
                
                mergeProgress.classList.add('hidden');
                mergeFiles = [];
                mergeFileList.innerHTML = '';
                mergeBtn.disabled = true;
                
            } catch (error) {
                console.error('Error al unir PDFs:', error);
                mergeProgress.classList.add('hidden');
                alert('Ocurrió un error al unir los PDFs');
            }
        });

        // Funcionalidad para Extraer páginas
        const extractDropzone = document.getElementById('extract-dropzone');
        const extractFileInput = document.getElementById('extract-file');
        const extractFileInfo = document.getElementById('extract-file-info');
        const extractFileName = document.getElementById('extract-file-name');
        const extractPageCount = document.getElementById('extract-page-count');
        const extractRange = document.getElementById('extract-range');
        const extractPageSelector = document.getElementById('extract-page-selector');
        const extractBtn = document.getElementById('extract-btn');
        const extractProgress = document.getElementById('extract-progress');
        const extractProgressFill = document.getElementById('extract-progress-fill');

        let extractFile = null;
        let totalPages = 0;

        extractDropzone.addEventListener('click', () => extractFileInput.click());
        extractDropzone.addEventListener('dragoover', (e) => {
            e.preventDefault();
            extractDropzone.classList.add('active');
        });
        extractDropzone.addEventListener('dragleave', () => {
            extractDropzone.classList.remove('active');
        });
        extractDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            extractDropzone.classList.remove('active');
            handleExtractFile(e.dataTransfer.files[0]);
        });

        extractFileInput.addEventListener('change', () => {
            if (extractFileInput.files.length > 0) {
                handleExtractFile(extractFileInput.files[0]);
            }
        });

        async function handleExtractFile(file) {
            if (file.type !== 'application/pdf') {
                alert('Por favor, selecciona un archivo PDF');
                return;
            }
            
            extractFile = file;
            extractFileName.textContent = file.name;
            
            try {
                // Obtener el número real de páginas del PDF
                const arrayBuffer = await file.arrayBuffer();
                const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
                totalPages = pdfDoc.getPageCount();
                
                extractPageCount.textContent = `${totalPages} páginas`;
                
                // Generar botones de selección de páginas
                extractPageSelector.innerHTML = '';
                for (let i = 1; i <= totalPages; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.className = 'px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded';
                    pageBtn.textContent = i;
                    pageBtn.dataset.page = i;
                    pageBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        pageBtn.classList.toggle('bg-blue-100', !pageBtn.classList.contains('bg-blue-100'));
                        pageBtn.classList.toggle('text-blue-700', !pageBtn.classList.contains('text-blue-700'));
                        updateExtractRange();
                    });
                    extractPageSelector.appendChild(pageBtn);
                }
                
                extractFileInfo.classList.remove('hidden');
                extractBtn.disabled = false;
                
            } catch (error) {
                console.error('Error al cargar PDF:', error);
                alert('No se pudo cargar el archivo PDF');
            }
        }

        function updateExtractRange() {
            const selectedPages = Array.from(extractPageSelector.querySelectorAll('.bg-blue-100'))
                .map(btn => parseInt(btn.dataset.page))
                .sort((a, b) => a - b);
            
            if (selectedPages.length === 0) {
                extractRange.value = '';
                return;
            }
            
            // Convertir a rangos (ej: 1,2,3,5,6,7 -> 1-3,5-7)
            let ranges = [];
            let start = selectedPages[0];
            let prev = start;
            
            for (let i = 1; i < selectedPages.length; i++) {
                if (selectedPages[i] === prev + 1) {
                    prev = selectedPages[i];
                } else {
                    ranges.push(start === prev ? start : `${start}-${prev}`);
                    start = selectedPages[i];
                    prev = start;
                }
            }
            ranges.push(start === prev ? start : `${start}-${prev}`);
            
            extractRange.value = ranges.join(', ');
        }

        extractRange.addEventListener('input', () => {
            // Limpiar selección de botones
            extractPageSelector.querySelectorAll('button').forEach(btn => {
                btn.classList.remove('bg-blue-100', 'text-blue-700');
            });
            
            // Procesar el rango ingresado
            const ranges = extractRange.value.split(',').map(r => r.trim());
            
            for (const range of ranges) {
                if (range.includes('-')) {
                    const [start, end] = range.split('-').map(n => parseInt(n));
                    if (!isNaN(start) && !isNaN(end) && start <= end && start >= 1 && end <= totalPages) {
                        for (let i = start; i <= end; i++) {
                            const btn = extractPageSelector.querySelector(`button[data-page="${i}"]`);
                            if (btn) {
                                btn.classList.add('bg-blue-100', 'text-blue-700');
                            }
                        }
                    }
                } else {
                    const page = parseInt(range);
                    if (!isNaN(page) && page >= 1 && page <= totalPages) {
                        const btn = extractPageSelector.querySelector(`button[data-page="${page}"]`);
                        if (btn) {
                            btn.classList.add('bg-blue-100', 'text-blue-700');
                        }
                    }
                }
            }
        });

        extractBtn.addEventListener('click', async () => {
            if (!extractFile) return;
            
            extractProgress.classList.remove('hidden');
            extractProgressFill.style.width = '0%';
            
            try {
                // Obtener las páginas seleccionadas
                const selectedPages = Array.from(extractPageSelector.querySelectorAll('.bg-blue-100'))
                    .map(btn => parseInt(btn.dataset.page) - 1); // pdf-lib usa índices base 0
                
                if (selectedPages.length === 0) {
                    alert('Por favor, selecciona al menos una página');
                    extractProgress.classList.add('hidden');
                    return;
                }
                
                // Cargar el PDF original
                const arrayBuffer = await extractFile.arrayBuffer();
                const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
                
                // Crear un nuevo PDF con las páginas seleccionadas
                const newPdf = await PDFLib.PDFDocument.create();
                const pages = await newPdf.copyPages(pdfDoc, selectedPages);
                pages.forEach(page => newPdf.addPage(page));
                
                // Guardar el nuevo PDF
                const pdfBytes = await newPdf.save();
                const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });
                
                // Descargar el PDF
                const extractedName = `paginas_extraidas_${new Date().toISOString().slice(0, 10)}.pdf`;
                download(pdfBlob, extractedName, 'application/pdf');
                
                extractProgressFill.style.width = '100%';
                setTimeout(() => {
                    extractProgress.classList.add('hidden');
                }, 500);
                
            } catch (error) {
                console.error('Error al extraer páginas:', error);
                extractProgress.classList.add('hidden');
                alert('Ocurrió un error al extraer las páginas');
            }
        });

        // Funcionalidad para Comprimir PDF
        const compressDropzone = document.getElementById('compress-dropzone');
        const compressFileInput = document.getElementById('compress-file');
        const compressFileInfo = document.getElementById('compress-file-info');
        const compressFileName = document.getElementById('compress-file-name');
        const compressFileSize = document.getElementById('compress-file-size');
        const compressLevel = document.getElementById('compress-level');
        const compressLevelValue = document.getElementById('compress-level-value');
        const compressBtn = document.getElementById('compress-btn');
        const compressProgress = document.getElementById('compress-progress');
        const compressProgressFill = document.getElementById('compress-progress-fill');
        const compressResult = document.getElementById('compress-result');
        const originalSize = document.getElementById('original-size');
        const compressedSize = document.getElementById('compressed-size');
        const reductionPercent = document.getElementById('reduction-percent');

        let compressFile = null;

        compressDropzone.addEventListener('click', () => compressFileInput.click());
        compressDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            compressDropzone.classList.add('active');
        });
        compressDropzone.addEventListener('dragleave', () => {
            compressDropzone.classList.remove('active');
        });
        compressDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            compressDropzone.classList.remove('active');
            handleCompressFile(e.dataTransfer.files[0]);
        });

        compressFileInput.addEventListener('change', () => {
            if (compressFileInput.files.length > 0) {
                handleCompressFile(compressFileInput.files[0]);
            }
        });

        compressLevel.addEventListener('input', () => {
            compressLevelValue.textContent = compressLevel.value;
        });

        function handleCompressFile(file) {
            if (file.type !== 'application/pdf') {
                alert('Por favor, selecciona un archivo PDF');
                return;
            }
            
            compressFile = file;
            compressFileName.textContent = file.name;
            compressFileSize.textContent = formatFileSize(file.size);
            
            compressFileInfo.classList.remove('hidden');
            compressBtn.disabled = false;
            compressResult.classList.add('hidden');
        }

        compressBtn.addEventListener('click', async () => {
            if (!compressFile) return;
            
            compressProgress.classList.remove('hidden');
            compressProgressFill.style.width = '0%';
            
            try {
                // Cargar el PDF original
                const arrayBuffer = await compressFile.arrayBuffer();
                const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
                
                // Simular compresión (en un entorno real usarías optimización real)
                // Aquí simplemente re-guardamos el PDF con diferentes opciones
                const level = parseInt(compressLevel.value);
                const optimizeImages = document.getElementById('compress-optimize-images').checked;
                
                // Actualizar progreso
                compressProgressFill.style.width = '50%';
                
                // Simular tiempo de procesamiento
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // Guardar con diferentes opciones según el nivel de compresión
                const saveOptions = {
                    useObjectStreams: true, // Reduce tamaño
                    // En un entorno real, aquí aplicarías optimizaciones reales
                };
                
                const pdfBytes = await pdfDoc.save(saveOptions);
                const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });
                
                // Calcular resultados
                const original = compressFile.size;
                const compressed = pdfBlob.size;
                
                // Mostrar resultados
                originalSize.textContent = formatFileSize(original);
                compressedSize.textContent = formatFileSize(compressed);
                reductionPercent.textContent = `${Math.round((1 - compressed/original) * 100)}%`;
                
                // Descargar el PDF comprimido
                const compressedName = `documento_comprimido_${new Date().toISOString().slice(0, 10)}.pdf`;
                download(pdfBlob, compressedName, 'application/pdf');
                
                compressProgressFill.style.width = '100%';
                compressResult.classList.remove('hidden');
                
                setTimeout(() => {
                    compressProgress.classList.add('hidden');
                }, 500);
                
            } catch (error) {
                console.error('Error al comprimir PDF:', error);
                compressProgress.classList.add('hidden');
                alert('Ocurrió un error al comprimir el PDF');
            }
        });

        // Funcionalidad para Firmar PDF
        const signDropzone = document.getElementById('sign-dropzone');
        const signFileInput = document.getElementById('sign-file');
        const signFileInfo = document.getElementById('sign-file-info');
        const signFileName = document.getElementById('sign-file-name');
        const signPageCount = document.getElementById('sign-page-count');
        const signPage = document.getElementById('sign-page');
        const signCustomPageContainer = document.getElementById('sign-custom-page-container');
        const signCustomPage = document.getElementById('sign-custom-page');
        const signUploadBtn = document.getElementById('sign-upload-btn');
        const signDrawBtn = document.getElementById('sign-draw-btn');
        const signTokenBtn = document.getElementById('sign-token-btn');
        const signImageInput = document.getElementById('sign-image');
        const signaturePreview = document.getElementById('signature-preview');
        const signPosition = document.getElementById('sign-position');
        const signSize = document.getElementById('sign-size');
        const signBtn = document.getElementById('sign-btn');
        const signProgress = document.getElementById('sign-progress');
        const signProgressFill = document.getElementById('sign-progress-fill');
        const drawModal = document.getElementById('draw-modal');
        const signatureCanvas = document.getElementById('signature-canvas');
        const clearSignature = document.getElementById('clear-signature');
        const cancelSignature = document.getElementById('cancel-signature');
        const saveSignature = document.getElementById('save-signature');
        const tokenModal = document.getElementById('token-modal');
        const cancelToken = document.getElementById('cancel-token');
        const confirmToken = document.getElementById('confirm-token');

        let signFile = null;
        let signatureImage = null;
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        const ctx = signatureCanvas.getContext('2d');

        // Configurar canvas
        function setupCanvas() {
            const rect = signatureCanvas.getBoundingClientRect();
            signatureCanvas.width = rect.width;
            signatureCanvas.height = rect.height;
            
            ctx.strokeStyle = '#000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, signatureCanvas.width, signatureCanvas.height);
        }

        // Eventos para dibujar en el canvas
        signatureCanvas.addEventListener('mousedown', startDrawing);
        signatureCanvas.addEventListener('touchstart', startDrawing);
        signatureCanvas.addEventListener('mousemove', draw);
        signatureCanvas.addEventListener('touchmove', draw);
        signatureCanvas.addEventListener('mouseup', stopDrawing);
        signatureCanvas.addEventListener('touchend', stopDrawing);
        signatureCanvas.addEventListener('mouseout', stopDrawing);

        function startDrawing(e) {
            isDrawing = true;
            const pos = getPosition(e);
            lastX = pos.x;
            lastY = pos.y;
        }

        function draw(e) {
            if (!isDrawing) return;
            
            const pos = getPosition(e);
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(pos.x, pos.y);
            ctx.stroke();
            
            lastX = pos.x;
            lastY = pos.y;
        }

        function stopDrawing() {
            isDrawing = false;
        }

        function getPosition(e) {
            const rect = signatureCanvas.getBoundingClientRect();
            return {
                x: (e.clientX || e.touches[0].clientX) - rect.left,
                y: (e.clientY || e.touches[0].clientY) - rect.top
            };
        }

        // Manejo de archivo PDF para firmar
        signDropzone.addEventListener('click', () => signFileInput.click());
        signDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            signDropzone.classList.add('active');
        });
        signDropzone.addEventListener('dragleave', () => {
            signDropzone.classList.remove('active');
        });
        signDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            signDropzone.classList.remove('active');
            handleSignFile(e.dataTransfer.files[0]);
        });

        signFileInput.addEventListener('change', () => {
            if (signFileInput.files.length > 0) {
                handleSignFile(signFileInput.files[0]);
            }
        });

        async function handleSignFile(file) {
            if (file.type !== 'application/pdf') {
                alert('Por favor, selecciona un archivo PDF');
                return;
            }
            
            signFile = file;
            signFileName.textContent = file.name;
            
            try {
                // Obtener el número real de páginas del PDF
                const arrayBuffer = await file.arrayBuffer();
                const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
                const pages = pdfDoc.getPageCount();
                
                signPageCount.textContent = `${pages} páginas`;
                
                // Actualizar opción de página personalizada
                signCustomPage.max = pages;
                
                signFileInfo.classList.remove('hidden');
                signPage.disabled = false;
                updateSignBtnState();
                
            } catch (error) {
                console.error('Error al cargar PDF:', error);
                alert('No se pudo cargar el archivo PDF');
            }
        }

        // Manejo de selección de página
        signPage.addEventListener('change', () => {
            if (signPage.value === 'custom') {
                signCustomPageContainer.classList.remove('hidden');
            } else {
                signCustomPageContainer.classList.add('hidden');
            }
        });

        // Manejo de firma (subir imagen)
        signUploadBtn.addEventListener('click', () => signImageInput.click());
        signImageInput.addEventListener('change', () => {
            if (signImageInput.files.length > 0) {
                const file = signImageInput.files[0];
                const reader = new FileReader();
                
                reader.onload = (e) => {
                    signatureImage = e.target.result;
                    signaturePreview.innerHTML = `<img src="${signatureImage}" alt="Firma" class="max-w-full max-h-32">`;
                    updateSignBtnState();
                };
                
                reader.readAsDataURL(file);
            }
        });

        // Manejo de firma (dibujar)
        signDrawBtn.addEventListener('click', () => {
            setupCanvas();
            drawModal.classList.remove('hidden');
        });

        clearSignature.addEventListener('click', () => {
            ctx.clearRect(0, 0, signatureCanvas.width, signatureCanvas.height);
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, signatureCanvas.width, signatureCanvas.height);
        });

        cancelSignature.addEventListener('click', () => {
            drawModal.classList.add('hidden');
        });

        saveSignature.addEventListener('click', () => {
            const dataUrl = signatureCanvas.toDataURL('image/png');
            signatureImage = dataUrl;
            signaturePreview.innerHTML = `<img src="${dataUrl}" alt="Firma dibujada" class="max-w-full max-h-32">`;
            drawModal.classList.add('hidden');
            updateSignBtnState();
        });

        // Manejo de firma (e-Token)
        signTokenBtn.addEventListener('click', () => {
            tokenModal.classList.remove('hidden');
        });

        cancelToken.addEventListener('click', () => {
            tokenModal.classList.add('hidden');
        });

        confirmToken.addEventListener('click', () => {
            const cert = document.getElementById('token-certificate').value;
            const password = document.getElementById('token-password').value;
            
            if (!cert || !password) {
                alert('Por favor, selecciona un certificado e ingresa la contraseña');
                return;
            }
            
            // Simular firma con token
            signatureImage = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMDAgMTAwIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjEwMCIgZmlsbD0iI2VlZSIvPjx0ZXh0IHg9IjEwMCIgeT0iNTUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIyMCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0iIzAwMCI+RmlybWEgRGlnaXRhbDwvdGV4dD48L3N2Zz4=';
            signaturePreview.innerHTML = `<img src="${signatureImage}" alt="Firma digital" class="max-w-full max-h-32">`;
            
            tokenModal.classList.add('hidden');
            updateSignBtnState();
        });

        // Actualizar estado del botón de firma
        function updateSignBtnState() {
            signBtn.disabled = !(signFile && signatureImage);
        }

        // Firmar documento
        signBtn.addEventListener('click', async () => {
            if (!signFile || !signatureImage) return;
            
            signProgress.classList.remove('hidden');
            signProgressFill.style.width = '0%';
            
            try {
                // Cargar el PDF original
                const arrayBuffer = await signFile.arrayBuffer();
                const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
                
                // Determinar qué páginas firmar
                let pagesToSign = [];
                const pageOption = signPage.value;
                
                if (pageOption === 'first') {
                    pagesToSign = [0];
                } else if (pageOption === 'last') {
                    pagesToSign = [pdfDoc.getPageCount() - 1];
                } else if (pageOption === 'all') {
                    pagesToSign = Array.from({ length: pdfDoc.getPageCount() }, (_, i) => i);
                } else if (pageOption === 'custom') {
                    const customPage = parseInt(signCustomPage.value) - 1; // Convertir a índice base 0
                    if (customPage >= 0 && customPage < pdfDoc.getPageCount()) {
                        pagesToSign = [customPage];
                    } else {
                        throw new Error('Número de página inválido');
                    }
                }
                
                // Cargar la imagen de firma
                let signatureImageBytes;
                if (signatureImage.startsWith('data:image/svg')) {
                    // Usar la firma SVG del token (simulación)
                    signatureImageBytes = await fetch(signatureImage).then(res => res.arrayBuffer());
                } else {
                    // Convertir imagen de firma a bytes
                    const response = await fetch(signatureImage);
                    signatureImageBytes = await response.arrayBuffer();
                }
                
                // Embed la imagen en el PDF
                let signatureImageObj;
                if (signatureImage.includes('png')) {
                    signatureImageObj = await pdfDoc.embedPng(signatureImageBytes);
                } else if (signatureImage.includes('jpeg') || signatureImage.includes('jpg')) {
                    signatureImageObj = await pdfDoc.embedJpg(signatureImageBytes);
                } else {
                    // Intentar como PNG por defecto
                    signatureImageObj = await pdfDoc.embedPng(signatureImageBytes);
                }
                
                const sizeFactor = signSize.value / 100;
                const signatureDims = signatureImageObj.scale(sizeFactor);
                
                // Aplicar firma a cada página seleccionada
                for (const pageIndex of pagesToSign) {
                    const page = pdfDoc.getPage(pageIndex);
                    const { width, height } = page.getSize();
                    
                    // Determinar posición según selección
                    let x, y;
                    const position = signPosition.value;
                    
                    // Margen de 20 puntos desde los bordes
                    const margin = 20;
                    
                    if (position === 'bottom-right') {
                        x = width - signatureDims.width - margin;
                        y = margin;
                    } else if (position === 'bottom-left') {
                        x = margin;
                        y = margin;
                    } else if (position === 'top-right') {
                        x = width - signatureDims.width - margin;
                        y = height - signatureDims.height - margin;
                    } else if (position === 'top-left') {
                        x = margin;
                        y = height - signatureDims.height - margin;
                    } else { // center
                        x = (width - signatureDims.width) / 2;
                        y = (height - signatureDims.height) / 2;
                    }
                    
                    // Dibujar firma
                    page.drawImage(signatureImageObj, {
                        x,
                        y,
                        width: signatureDims.width,
                        height: signatureDims.height,
                    });
                }
                
                // Actualizar progreso
                signProgressFill.style.width = '80%';
                
                // Guardar el PDF firmado
                const pdfBytes = await pdfDoc.save();
                const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });
                
                // Descargar el PDF
                const signedName = `documento_firmado_${new Date().toISOString().slice(0, 10)}.pdf`;
                download(pdfBlob, signedName, 'application/pdf');
                
                signProgressFill.style.width = '100%';
                
                setTimeout(() => {
                    signProgress.classList.add('hidden');
                }, 500);
                
            } catch (error) {
                console.error('Error al firmar PDF:', error);
                signProgress.classList.add('hidden');
                alert('Ocurrió un error al firmar el PDF. Por favor, verifica que la imagen de firma sea válida.');
            }
        });

        // Función auxiliar para formatear tamaño de archivo
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // Inicializar canvas al cargar
        window.addEventListener('load', setupCanvas);
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=luzu67/aigde" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>