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
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
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Urna Eletrônica</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">
    <style>
        @keyframes blink {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        .blink {
            animation: blink 1s infinite;
        }
        .urna-screen {
            background-color: #e0e0e0;
            border-radius: 10px;
            box-shadow: inset 0 0 20px rgba(0,0,0,0.5);
        }
        .urna-key {
            background-color: #333;
            color: white;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            cursor: pointer;
            user-select: none;
            box-shadow: 0 4px 0 #111;
        }
        .urna-key:active {
            transform: translateY(2px);
            box-shadow: 0 2px 0 #111;
        }
        .urna-key-white {
            background-color: white;
            color: #333;
        }
        .urna-key-orange {
            background-color: #ff8c00;
        }
        .urna-key-green {
            background-color: #4CAF50;
        }
        .screen-text {
            font-family: 'Courier New', monospace;
        }
        .candidate-photo {
            border: 3px solid #333;
            background-color: #fff;
        }
        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            transition: width 0.3s;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- Admin Panel (hidden by default) -->
        <div id="adminPanel" class="hidden bg-white rounded-lg shadow-lg p-6 mb-8">
            <h2 class="text-2xl font-bold mb-6 text-center">Painel de Administração</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Voter Registration -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h3 class="text-lg font-semibold mb-4">Cadastrar Eleitor</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Matrícula</label>
                            <input type="text" id="voterId" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Nome</label>
                            <input type="text" id="voterName" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Senha</label>
                            <input type="password" id="voterPassword" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <button onclick="registerVoter()" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                            Cadastrar Eleitor
                        </button>
                    </div>
                </div>
                
                <!-- Position Management -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h3 class="text-lg font-semibold mb-4">Gerenciar Cargos</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Nome do Cargo</label>
                            <input type="text" id="positionName" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Número (até 3 dígitos)</label>
                            <input type="number" min="1" max="999" id="positionNumber" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <button onclick="addPosition()" class="w-full bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
                            Adicionar Cargo
                        </button>
                    </div>
                </div>
                
                <!-- Candidate Registration -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h3 class="text-lg font-semibold mb-4">Cadastrar Candidato</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Cargo</label>
                            <select id="candidatePosition" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <!-- Options will be added dynamically -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Número do Candidato</label>
                            <input type="number" min="1" max="999" id="candidateNumber" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Nome do Candidato</label>
                            <input type="text" id="candidateName" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Foto (URL)</label>
                            <input type="text" id="candidatePhoto" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500" placeholder="https://exemplo.com/foto.jpg">
                        </div>
                        <button onclick="registerCandidate()" class="w-full bg-purple-600 text-white py-2 px-4 rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2">
                            Cadastrar Candidato
                        </button>
                    </div>
                </div>
                
                <!-- Election Control -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h3 class="text-lg font-semibold mb-4">Controle da Eleição</h3>
                    <div class="space-y-4">
                        <div class="flex space-x-4">
                            <button onclick="startElection()" class="flex-1 bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
                                Iniciar Eleição
                            </button>
                            <button onclick="endElection()" class="flex-1 bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
                                Encerrar Eleição
                            </button>
                        </div>
                        <div>
                            <button onclick="showResults()" class="w-full bg-yellow-600 text-white py-2 px-4 rounded-md hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2">
                                Mostrar Resultados
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Admin Login -->
            <div id="adminLogin" class="mt-8 bg-gray-50 p-4 rounded-lg max-w-md mx-auto">
                <h3 class="text-lg font-semibold mb-4">Acesso do Administrador</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Senha do Administrador</label>
                        <input type="password" id="adminPassword" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <button onclick="loginAdmin()" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        Acessar Painel
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Voter Login -->
        <div id="voterLogin" class="bg-white rounded-lg shadow-lg p-6 mb-8 max-w-md mx-auto">
            <h2 class="text-2xl font-bold mb-6 text-center">Login do Eleitor</h2>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Matrícula</label>
                    <input type="text" id="loginVoterId" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Senha</label>
                    <input type="password" id="loginVoterPassword" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                <button onclick="loginVoter()" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                    Acessar Urna
                </button>
                <button onclick="showAdminPanel()" class="w-full bg-gray-600 text-white py-2 px-4 rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                    Acesso Administrativo
                </button>
            </div>
        </div>
        
        <!-- Voting Machine -->
        <div id="votingMachine" class="hidden bg-gray-800 rounded-lg shadow-xl p-6 max-w-4xl mx-auto">
            <div class="flex flex-col md:flex-row gap-6">
                <!-- Screen -->
                <div class="flex-1">
                    <div class="urna-screen p-4 h-96 mb-4">
                        <div id="screenContent" class="h-full flex flex-col">
                            <!-- Content will be dynamically updated -->
                            <div class="flex-1 flex items-center justify-center">
                                <p class="text-xl font-bold">Bem-vindo à Urna Eletrônica</p>
                            </div>
                        </div>
                    </div>
                    <div class="flex justify-between items-center bg-gray-700 text-white p-2 rounded">
                        <div id="currentPosition" class="font-bold">Selecione um cargo</div>
                        <div id="typedNumbers" class="text-xl font-mono">_ _ _</div>
                    </div>
                </div>
                
                <!-- Keyboard -->
                <div class="w-full md:w-64">
                    <div class="grid grid-cols-3 gap-3 mb-3">
                        <div class="urna-key" onclick="pressKey(1)">1</div>
                        <div class="urna-key" onclick="pressKey(2)">2</div>
                        <div class="urna-key" onclick="pressKey(3)">3</div>
                        <div class="urna-key" onclick="pressKey(4)">4</div>
                        <div class="urna-key" onclick="pressKey(5)">5</div>
                        <div class="urna-key" onclick="pressKey(6)">6</div>
                        <div class="urna-key" onclick="pressKey(7)">7</div>
                        <div class="urna-key" onclick="pressKey(8)">8</div>
                        <div class="urna-key" onclick="pressKey(9)">9</div>
                        <div class="urna-key urna-key-white" onclick="pressKey(0)">0</div>
                        <div class="urna-key urna-key-white" onclick="clearNumbers()">
                            <i class="fas fa-backspace"></i>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div class="urna-key urna-key-orange" onclick="blankVote()">BRANCO</div>
                        <div class="urna-key urna-key-green" onclick="confirmVote()">CONFIRMA</div>
                        <div class="urna-key urna-key-white" onclick="correctVote()">CORRIGE</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Results Panel -->
        <div id="resultsPanel" class="hidden bg-white rounded-lg shadow-lg p-6 mb-8">
            <h2 class="text-2xl font-bold mb-6 text-center">Resultados da Eleição</h2>
            
            <div id="resultsContent" class="space-y-8">
                <!-- Results will be added dynamically -->
            </div>
            
            <div class="mt-8">
                <button onclick="hideResults()" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                    Voltar
                </button>
            </div>
        </div>
    </div>

    <script>
        // Database simulation
        let voters = [];
        let positions = [];
        let candidates = [];
        let votes = [];
        let electionActive = false;
        let currentUser = null;
        let isAdmin = false;
        
        // Voting machine state
        let currentPositionIndex = 0;
        let typedNumbers = [];
        let votedPositions = [];
        
        // Admin password (in a real app, this should be hashed and stored securely)
        const ADMIN_PASSWORD = "admin123";
        
        // Initialize with some sample data
        function initializeSampleData() {
            if (localStorage.getItem('electionInitialized')) return;
            
            // Sample positions
            positions = [
                { id: 1, name: "Presidente", number: 100 },
                { id: 2, name: "Vice-Presidente", number: 200 },
                { id: 3, name: "1º Secretário", number: 300 },
                { id: 4, name: "2º Secretário", number: 400 },
                { id: 5, name: "Tesoureiro", number: 500 },
                { id: 6, name: "Secretário Executivo", number: 600 },
                { id: 7, name: "1º Titular", number: 700 },
                { id: 8, name: "2º Titular", number: 800 },
                { id: 9, name: "3º Titular", number: 900 },
                { id: 10, name: "1º Suplente", number: 110 },
                { id: 11, name: "2º Suplente", number: 220 },
                { id: 12, name: "3º Suplente", number: 330 }
            ];
            
            // Sample candidates
            candidates = [
                { id: 1, positionId: 1, number: 101, name: "João Silva", photo: "https://randomuser.me/api/portraits/men/1.jpg" },
                { id: 2, positionId: 1, number: 102, name: "Maria Souza", photo: "https://randomuser.me/api/portraits/women/1.jpg" },
                { id: 3, positionId: 2, number: 201, name: "Carlos Oliveira", photo: "https://randomuser.me/api/portraits/men/2.jpg" },
                { id: 4, positionId: 2, number: 202, name: "Ana Santos", photo: "https://randomuser.me/api/portraits/women/2.jpg" }
            ];
            
            // Sample voters
            voters = [
                { id: "1001", name: "Eleitor Exemplo 1", password: "123456", voted: false },
                { id: "1002", name: "Eleitor Exemplo 2", password: "123456", voted: false }
            ];
            
            localStorage.setItem('electionInitialized', 'true');
            saveData();
        }
        
        // Load data from localStorage
        function loadData() {
            const savedVoters = localStorage.getItem('voters');
            const savedPositions = localStorage.getItem('positions');
            const savedCandidates = localStorage.getItem('candidates');
            const savedVotes = localStorage.getItem('votes');
            const savedElectionActive = localStorage.getItem('electionActive');
            
            if (savedVoters) voters = JSON.parse(savedVoters);
            if (savedPositions) positions = JSON.parse(savedPositions);
            if (savedCandidates) candidates = JSON.parse(savedCandidates);
            if (savedVotes) votes = JSON.parse(savedVotes);
            if (savedElectionActive) electionActive = savedElectionActive === 'true';
        }
        
        // Save data to localStorage
        function saveData() {
            localStorage.setItem('voters', JSON.stringify(voters));
            localStorage.setItem('positions', JSON.stringify(positions));
            localStorage.setItem('candidates', JSON.stringify(candidates));
            localStorage.setItem('votes', JSON.stringify(votes));
            localStorage.setItem('electionActive', electionActive);
        }
        
        // Register a new voter
        function registerVoter() {
            const voterId = document.getElementById('voterId').value;
            const voterName = document.getElementById('voterName').value;
            const voterPassword = document.getElementById('voterPassword').value;
            
            if (!voterId || !voterName || !voterPassword) {
                alert("Por favor, preencha todos os campos!");
                return;
            }
            
            if (voters.some(v => v.id === voterId)) {
                alert("Já existe um eleitor com esta matrícula!");
                return;
            }
            
            voters.push({
                id: voterId,
                name: voterName,
                password: voterPassword,
                voted: false
            });
            
            saveData();
            alert("Eleitor cadastrado com sucesso!");
            document.getElementById('voterId').value = '';
            document.getElementById('voterName').value = '';
            document.getElementById('voterPassword').value = '';
        }
        
        // Add a new position
        function addPosition() {
            const positionName = document.getElementById('positionName').value;
            const positionNumber = parseInt(document.getElementById('positionNumber').value);
            
            if (!positionName || isNaN(positionNumber)) {
                alert("Por favor, preencha todos os campos corretamente!");
                return;
            }
            
            if (positionNumber < 1 || positionNumber > 999) {
                alert("O número do cargo deve ter até 3 dígitos (1-999)!");
                return;
            }
            
            if (positions.some(p => p.number === positionNumber)) {
                alert("Já existe um cargo com este número!");
                return;
            }
            
            const newId = positions.length > 0 ? Math.max(...positions.map(p => p.id)) + 1 : 1;
            
            positions.push({
                id: newId,
                name: positionName,
                number: positionNumber
            });
            
            saveData();
            alert("Cargo adicionado com sucesso!");
            document.getElementById('positionName').value = '';
            document.getElementById('positionNumber').value = '';
            updatePositionSelects();
        }
        
        // Register a new candidate
        function registerCandidate() {
            const positionId = parseInt(document.getElementById('candidatePosition').value);
            const candidateNumber = parseInt(document.getElementById('candidateNumber').value);
            const candidateName = document.getElementById('candidateName').value;
            const candidatePhoto = document.getElementById('candidatePhoto').value;
            
            if (isNaN(positionId) || isNaN(candidateNumber) || !candidateName) {
                alert("Por favor, preencha todos os campos obrigatórios!");
                return;
            }
            
            if (candidateNumber < 1 || candidateNumber > 999) {
                alert("O número do candidato deve ter até 3 dígitos (1-999)!");
                return;
            }
            
            const position = positions.find(p => p.id === positionId);
            if (!position) {
                alert("Cargo inválido!");
                return;
            }
            
            // Check if candidate number matches position number (first digit)
            if (Math.floor(candidateNumber / 100) !== Math.floor(position.number / 100)) {
                alert(`O número do candidato deve começar com ${Math.floor(position.number / 100)} para este cargo!`);
                return;
            }
            
            if (candidates.some(c => c.positionId === positionId && c.number === candidateNumber)) {
                alert("Já existe um candidato com este número para este cargo!");
                return;
            }
            
            const newId = candidates.length > 0 ? Math.max(...candidates.map(c => c.id)) + 1 : 1;
            
            candidates.push({
                id: newId,
                positionId: positionId,
                number: candidateNumber,
                name: candidateName,
                photo: candidatePhoto || "https://via.placeholder.com/150?text=Sem+Foto"
            });
            
            saveData();
            alert("Candidato cadastrado com sucesso!");
            document.getElementById('candidateNumber').value = '';
            document.getElementById('candidateName').value = '';
            document.getElementById('candidatePhoto').value = '';
        }
        
        // Update position selects in forms
        function updatePositionSelects() {
            const positionSelect = document.getElementById('candidatePosition');
            positionSelect.innerHTML = '';
            
            positions.forEach(position => {
                const option = document.createElement('option');
                option.value = position.id;
                option.textContent = `${position.number} - ${position.name}`;
                positionSelect.appendChild(option);
            });
        }
        
        // Start election
        function startElection() {
            if (electionActive) {
                alert("A eleição já está em andamento!");
                return;
            }
            
            if (positions.length === 0) {
                alert("Não há cargos cadastrados para iniciar a eleição!");
                return;
            }
            
            electionActive = true;
            saveData();
            alert("Eleição iniciada com sucesso!");
        }
        
        // End election
        function endElection() {
            if (!electionActive) {
                alert("Não há eleição em andamento!");
                return;
            }
            
            electionActive = false;
            saveData();
            alert("Eleição encerrada com sucesso!");
        }
        
        // Show admin panel
        function showAdminPanel() {
            document.getElementById('voterLogin').classList.add('hidden');
            document.getElementById('adminPanel').classList.remove('hidden');
            document.getElementById('adminLogin').classList.remove('hidden');
            document.getElementById('votingMachine').classList.add('hidden');
            document.getElementById('resultsPanel').classList.add('hidden');
        }
        
        // Admin login
        function loginAdmin() {
            const password = document.getElementById('adminPassword').value;
            
            if (password === ADMIN_PASSWORD) {
                isAdmin = true;
                document.getElementById('adminLogin').classList.add('hidden');
                updatePositionSelects();
                alert("Acesso administrativo concedido!");
            } else {
                alert("Senha incorreta!");
            }
            
            document.getElementById('adminPassword').value = '';
        }
        
        // Voter login
        function loginVoter() {
            const voterId = document.getElementById('loginVoterId').value;
            const voterPassword = document.getElementById('loginVoterPassword').value;
            
            const voter = voters.find(v => v.id === voterId && v.password === voterPassword);
            
            if (!voter) {
                alert("Matrícula ou senha incorretos!");
                return;
            }
            
            if (!electionActive) {
                alert("Não há eleição em andamento no momento!");
                return;
            }
            
            if (voter.voted) {
                alert("Este eleitor já votou!");
                return;
            }
            
            currentUser = voter;
            document.getElementById('voterLogin').classList.add('hidden');
            document.getElementById('votingMachine').classList.remove('hidden');
            
            // Start voting process
            currentPositionIndex = 0;
            typedNumbers = [];
            votedPositions = [];
            updateScreen();
        }
        
        // Press key on voting machine
        function pressKey(number) {
            if (typedNumbers.length < 3) {
                typedNumbers.push(number);
                updateScreen();
            }
        }
        
        // Clear typed numbers
        function clearNumbers() {
            typedNumbers = [];
            updateScreen();
        }
        
        // Blank vote
        function blankVote() {
            if (typedNumbers.length > 0) {
                if (!confirm("Deseja realmente votar em BRANCO? Os números digitados serão descartados.")) {
                    return;
                }
            }
            
            registerVote(null);
        }
        
        // Confirm vote
        function confirmVote() {
            if (typedNumbers.length === 0) {
                alert("Digite um número antes de confirmar!");
                return;
            }
            
            const candidateNumber = parseInt(typedNumbers.join(''));
            const position = positions[currentPositionIndex];
            
            // Find candidate for this position with this number
            const candidate = candidates.find(c => 
                c.positionId === position.id && c.number === candidateNumber
            );
            
            if (!candidate) {
                if (!confirm(`Nenhum candidato encontrado com o número ${candidateNumber}. Deseja votar NULO?`)) {
                    return;
                }
            }
            
            registerVote(candidateNumber);
        }
        
        // Correct vote
        function correctVote() {
            typedNumbers = [];
            updateScreen();
        }
        
        // Register vote
        function registerVote(candidateNumber) {
            const position = positions[currentPositionIndex];
            
            votes.push({
                positionId: position.id,
                voterId: currentUser.id,
                candidateNumber: candidateNumber,
                timestamp: new Date().toISOString()
            });
            
            votedPositions.push(position.id);
            
            // Move to next position or finish voting
            currentPositionIndex++;
            typedNumbers = [];
            
            if (currentPositionIndex >= positions.length) {
                finishVoting();
            } else {
                // Skip positions that have already been voted (in case of multiple positions with same number)
                while (currentPositionIndex < positions.length && 
                       votedPositions.includes(positions[currentPositionIndex].id)) {
                    currentPositionIndex++;
                }
                
                if (currentPositionIndex >= positions.length) {
                    finishVoting();
                } else {
                    updateScreen();
                }
            }
        }
        
        // Finish voting process
        function finishVoting() {
            // Mark voter as voted
            const voterIndex = voters.findIndex(v => v.id === currentUser.id);
            if (voterIndex !== -1) {
                voters[voterIndex].voted = true;
                saveData();
            }
            
            // Show confirmation
            document.getElementById('screenContent').innerHTML = `
                <div class="h-full flex flex-col items-center justify-center text-center">
                    <div class="text-2xl font-bold mb-4">VOTO CONFIRMADO</div>
                    <div class="text-lg mb-6">Obrigado por votar!</div>
                    <div class="text-sm">Sua participação é fundamental para a democracia.</div>
                </div>
            `;
            
            // Return to login after 5 seconds
            setTimeout(() => {
                document.getElementById('votingMachine').classList.add('hidden');
                document.getElementById('voterLogin').classList.remove('hidden');
                document.getElementById('loginVoterId').value = '';
                document.getElementById('loginVoterPassword').value = '';
                currentUser = null;
            }, 5000);
        }
        
        // Update voting machine screen
        function updateScreen() {
            const position = positions[currentPositionIndex];
            const typedNumberStr = typedNumbers.join('');
            
            // Update typed numbers display
            const typedDisplay = document.getElementById('typedNumbers');
            typedDisplay.innerHTML = '';
            
            for (let i = 0; i < 3; i++) {
                const digit = document.createElement('span');
                digit.className = 'inline-block w-6 text-center';
                digit.textContent = typedNumbers[i] !== undefined ? typedNumbers[i] : '_';
                
                if (i === typedNumbers.length) {
                    digit.classList.add('blink');
                }
                
                typedDisplay.appendChild(digit);
            }
            
            // Update current position display
            document.getElementById('currentPosition').textContent = position 
                ? `${position.number} - ${position.name}`
                : "Selecione um cargo";
            
            // Update screen content
            const screenContent = document.getElementById('screenContent');
            
            if (!position) {
                screenContent.innerHTML = `
                    <div class="h-full flex items-center justify-center">
                        <p class="text-xl font-bold">Nenhum cargo disponível</p>
                    </div>
                `;
                return;
            }
            
            if (typedNumbers.length === 0) {
                // Show position info
                screenContent.innerHTML = `
                    <div class="h-full flex flex-col">
                        <div class="text-center py-2 bg-blue-800 text-white font-bold">
                            ${position.number} - ${position.name}
                        </div>
                        <div class="flex-1 flex items-center justify-center">
                            <div class="text-center">
                                <div class="text-xl font-bold mb-2">Digite o número</div>
                                <div class="text-lg">do candidato e confirme</div>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                // Show candidate info
                const candidateNumber = parseInt(typedNumberStr.padEnd(3, '0'));
                const candidate = candidates.find(c => 
                    c.positionId === position.id && c.number === candidateNumber
                );
                
                if (candidate) {
                    // Show candidate info
                    screenContent.innerHTML = `
                        <div class="h-full flex flex-col">
                            <div class="text-center py-2 bg-blue-800 text-white font-bold">
                                ${position.number} - ${position.name}
                            </div>
                            <div class="flex-1 flex flex-col md:flex-row items-center justify-center p-4">
                                <div class="candidate-photo w-24 h-24 md:w-32 md:h-32 mb-4 md:mb-0 md:mr-6 flex items-center justify-center overflow-hidden">
                                    <img src="${candidate.photo}" alt="Foto" class="w-full h-full object-cover">
                                </div>
                                <div class="text-center md:text-left">
                                    <div class="text-xl font-bold">${candidate.name}</div>
                                    <div class="text-lg">${candidate.number}</div>
                                    <div class="mt-2 text-sm">Confirme seu voto</div>
                                </div>
                            </div>
                        </div>
                    `;
                } else {
                    // Show number with no candidate
                    screenContent.innerHTML = `
                        <div class="h-full flex flex-col">
                            <div class="text-center py-2 bg-blue-800 text-white font-bold">
                                ${position.number} - ${position.name}
                            </div>
                            <div class="flex-1 flex flex-col items-center justify-center p-4">
                                <div class="text-4xl font-bold mb-4">${typedNumberStr}</div>
                                <div class="text-lg">Nenhum candidato encontrado</div>
                                <div class="mt-2 text-sm">Voto NULO - Confirme se deseja</div>
                            </div>
                        </div>
                    `;
                }
            }
        }
        
        // Show election results
        function showResults() {
            if (!isAdmin) {
                alert("Acesso restrito ao administrador!");
                return;
            }
            
            document.getElementById('adminPanel').classList.add('hidden');
            document.getElementById('resultsPanel').classList.remove('hidden');
            
            const resultsContent = document.getElementById('resultsContent');
            resultsContent.innerHTML = '';
            
            if (votes.length === 0) {
                resultsContent.innerHTML = '<p class="text-center">Nenhum voto registrado ainda.</p>';
                return;
            }
            
            // Calculate results for each position
            positions.forEach(position => {
                const positionVotes = votes.filter(v => v.positionId === position.id);
                const totalVotes = positionVotes.length;
                
                if (totalVotes === 0) return;
                
                // Group votes by candidate
                const voteCounts = {};
                let blankVotes = 0;
                let nullVotes = 0;
                
                positionVotes.forEach(vote => {
                    if (vote.candidateNumber === null) {
                        blankVotes++;
                    } else {
                        const candidate = candidates.find(c => 
                            c.positionId === position.id && c.number === vote.candidateNumber
                        );
                        
                        if (candidate) {
                            voteCounts[candidate.number] = (voteCounts[candidate.number] || 0) + 1;
                        } else {
                            nullVotes++;
                        }
                    }
                });
                
                // Create results card
                const card = document.createElement('div');
                card.className = 'bg-gray-50 p-4 rounded-lg';
                
                // Position title
                const title = document.createElement('h3');
                title.className = 'text-lg font-semibold mb-2';
                title.textContent = `${position.number} - ${position.name}`;
                card.appendChild(title);
                
                // Total votes
                const totalText = document.createElement('p');
                totalText.className = 'text-sm text-gray-600 mb-3';
                totalText.textContent = `Total de votos: ${totalVotes}`;
                card.appendChild(totalText);
                
                // Blank and null votes
                const blankNullDiv = document.createElement('div');
                blankNullDiv.className = 'grid grid-cols-2 gap-4 mb-4';
                
                const blankDiv = document.createElement('div');
                blankDiv.className = 'bg-white p-2 rounded';
                blankDiv.innerHTML = `
                    <div class="font-medium">Votos em Branco</div>
                    <div class="flex items-center mt-1">
                        <div class="w-16 font-bold">${blankVotes}</div>
                        <div class="flex-1">
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${(blankVotes / totalVotes) * 100}%"></div>
                            </div>
                        </div>
                        <div class="w-16 text-right">${Math.round((blankVotes / totalVotes) * 100)}%</div>
                    </div>
                `;
                blankNullDiv.appendChild(blankDiv);
                
                const nullDiv = document.createElement('div');
                nullDiv.className = 'bg-white p-2 rounded';
                nullDiv.innerHTML = `
                    <div class="font-medium">Votos Nulos</div>
                    <div class="flex items-center mt-1">
                        <div class="w-16 font-bold">${nullVotes}</div>
                        <div class="flex-1">
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${(nullVotes / totalVotes) * 100}%"></div>
                            </div>
                        </div>
                        <div class="w-16 text-right">${Math.round((nullVotes / totalVotes) * 100)}%</div>
                    </div>
                `;
                blankNullDiv.appendChild(nullDiv);
                
                card.appendChild(blankNullDiv);
                
                // Candidates results
                const candidatesResults = document.createElement('div');
                candidatesResults.className = 'space-y-2';
                
                // Get candidates sorted by votes
                const positionCandidates = candidates.filter(c => c.positionId === position.id);
                const sortedCandidates = [...positionCandidates].sort((a, b) => {
                    return (voteCounts[b.number] || 0) - (voteCounts[a.number] || 0);
                });
                
                sortedCandidates.forEach(candidate => {
                    const candidateVotes = voteCounts[candidate.number] || 0;
                    const percentage = (candidateVotes / totalVotes) * 100;
                    
                    const candidateDiv = document.createElement('div');
                    candidateDiv.className = 'bg-white p-3 rounded-lg';
                    candidateDiv.innerHTML = `
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full overflow-hidden mr-3">
                                <img src="${candidate.photo}" alt="Foto" class="w-full h-full object-cover">
                            </div>
                            <div class="flex-1">
                                <div class="font-bold">${candidate.name}</div>
                                <div class="text-sm text-gray-600">${candidate.number}</div>
                            </div>
                            <div class="text-right">
                                <div class="font-bold">${candidateVotes} votos</div>
                                <div class="text-sm">${Math.round(percentage)}%</div>
                            </div>
                        </div>
                        <div class="mt-2">
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${percentage}%"></div>
                            </div>
                        </div>
                    `;
                    
                    // Highlight elected candidate (if majority)
                    if (candidateVotes > totalVotes / 2) {
                        candidateDiv.classList.add('border-2', 'border-green-500');
                        const electedBadge = document.createElement('div');
                        electedBadge.className = 'text-xs font-bold text-green-600 mt-1';
                        electedBadge.textContent = 'ELEITO(A)';
                        candidateDiv.appendChild(electedBadge);
                    }
                    
                    candidatesResults.appendChild(candidateDiv);
                });
                
                card.appendChild(candidatesResults);
                resultsContent.appendChild(card);
            });
        }
        
        // Hide results panel
        function hideResults() {
            document.getElementById('resultsPanel').classList.add('hidden');
            document.getElementById('adminPanel').classList.remove('hidden');
        }
        
        // Initialize app
        function init() {
            initializeSampleData();
            loadData();
            
            // Check if admin is already logged in (for demo purposes)
            // In a real app, this would be handled with proper session management
            if (window.location.hash === '#admin') {
                showAdminPanel();
            }
        }
        
        // Start the app when page loads
        window.onload = init;
    </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=MFBarreto/https-enzostvs-deepsite-hf-space" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>