File size: 28,582 Bytes
8265afc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8a04f7
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

<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Checklist Offline</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>
    .sidebar {
      transition: transform 0.3s ease;
    }
    .photo-actions {
      opacity: 0;
      transition: opacity 0.2s ease;
    }
    .photo-container:hover .photo-actions {
      opacity: 1;
    }
    .status-btn {
      transition: all 0.2s ease;
    }
    .fullscreen-overlay {
      transition: opacity 0.3s ease;
    }
  </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col items-center p-4">
  <!-- Main Container -->
  <div class="w-full max-w-2xl bg-white rounded-lg shadow-md mb-4 overflow-hidden">
    <!-- Header -->
    <div class="bg-green-500 text-white p-4 relative">
      <button onclick="toggleSidebar()" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-xl">
        <i class="fas fa-bars"></i>
      </button>
      <h1 class="text-xl font-bold text-center">Checklist 2025</h1>
    </div>
    
    <h2 class="bg-gray-200 text-gray-800 p-3 text-center border-b border-gray-300 font-semibold">
      NOME DO CHECKLIST
    </h2>
    
    <!-- Checklist Table -->
    <div id="checklist-output" class="p-4">
      <table class="w-full border-collapse">
        <thead>
          <tr class="bg-blue-500 text-white">
            <th class="p-3 border border-gray-300 text-left">Pergunta</th>
            <th class="p-3 border border-gray-300">Status</th>
            <th class="p-3 border border-gray-300">Foto</th>
          </tr>
        </thead>
        <tbody id="checklist-body"></tbody>
      </table>
    </div>
    
    <!-- Save Button -->
    <button onclick="saveResults()" class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-4 rounded-b-lg transition relative z-50">
      Salvar Checklist
    </button>
    
    <!-- Observation Section -->
    <div class="p-4 border-t border-gray-200">
      <label class="block text-gray-700 font-bold mb-2">OBSERVAÇÃO GERAL</label>
      <textarea id="observation" class="w-full p-3 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500" rows="3" placeholder="Digite uma observação geral..."></textarea>
    </div>
  </div>
  
  <!-- File Upload Section -->
  <div class="w-full max-w-2xl mb-4 grid grid-cols-3 gap-4">
    <div>
      <input type="file" id="csvFile" accept=".csv" class="hidden" onchange="loadChecklistFromCSV(this)">
      <button onclick="document.getElementById('csvFile').click()" class="w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-4 rounded-lg transition flex items-center justify-center">
        <i class="fas fa-file-csv mr-2"></i> Escolher CSV
      </button>
    </div>
    <div>
      <button onclick="downloadTemplate()" class="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-4 rounded-lg transition flex items-center justify-center">
        <i class="fas fa-download mr-2"></i> Baixar Template
      </button>
    </div>
    <div>
      <button onclick="showExportModal()" class="w-full bg-purple-500 hover:bg-purple-600 text-white font-bold py-3 px-4 rounded-lg transition flex items-center justify-center">
        <i class="fas fa-file-export mr-2"></i> Exportar
      </button>
    </div>

    <!-- Export Modal -->
    <div id="exportModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
      <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <h3 class="text-lg font-bold mb-4">Exportar Checklists</h3>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Data Inicial:</label>
            <input type="date" id="exportStartDate" class="w-full p-2 border border-gray-300 rounded">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Data Final:</label>
            <input type="date" id="exportEndDate" class="w-full p-2 border border-gray-300 rounded">
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-6">
          <button onclick="hideExportModal()" class="px-4 py-2 border border-gray-300 rounded hover:bg-gray-100">Cancelar</button>
          <button onclick="exportChecklistsByDateRange()" class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600">Exportar</button>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Fullscreen Photo Viewer -->
  <div id="fullscreenOverlay" class="fixed inset-0 bg-black bg-opacity-90 z-40 flex items-center justify-center hidden opacity-0">
    <div class="relative max-w-4xl w-full p-4 mb-16">
      <button onclick="closeFullscreen()" class="absolute -top-12 right-0 text-white text-2xl hover:text-gray-300">
        <i class="fas fa-times"></i>
      </button>
      <img id="fullscreenImage" class="max-w-full max-h-screen mx-auto" src="" alt="Foto ampliada">
      <div class="flex justify-center mt-4">
        <button onclick="replacePhoto()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg mr-2">
          <i class="fas fa-sync-alt mr-2"></i>Substituir
        </button>
        <button onclick="deletePhoto()" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg">
          <i class="fas fa-trash-alt mr-2"></i>Excluir
        </button>
      </div>
    </div>
  </div>
  
  <!-- Sidebar -->
  <div id="sidebar" class="fixed top-0 left-0 h-full w-64 bg-white shadow-lg z-40 transform -translate-x-full flex flex-col">
    <div class="p-4 border-b border-gray-200 flex justify-between items-center">
      <h3 class="text-lg font-bold">Histórico</h3>
      <button onclick="closeSidebar()" class="text-gray-500 hover:text-gray-700">
        <i class="fas fa-times"></i>
      </button>
    </div>
    
    <div class="p-4 border-b border-gray-200">
      <label for="filterDate" class="block text-sm font-medium text-gray-700 mb-1">Filtrar por data:</label>
      <input type="date" id="filterDate" onchange="loadHistory(this.value)" class="w-full p-2 border border-gray-300 rounded">
    </div>
    <div class="p-4 border-b border-gray-200">
      <button onclick="showStatistics()" class="w-full text-left text-blue-600 hover:text-blue-800">
        <i class="fas fa-chart-pie mr-2"></i> Estatísticas
      </button>
    </div>
    
    <ul id="historyList" class="flex-1 overflow-y-auto p-2"></ul>
  </div>
  
  <!-- Overlay -->
  <div id="overlay" onclick="closeSidebar()" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden"></div>

  <!-- Statistics Modal -->
  <div id="statisticsModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
      <h3 class="text-lg font-bold mb-4">Estatísticas dos Checklists</h3>
      <div class="space-y-4">
        <div class="bg-gray-100 p-4 rounded-lg">
          <div class="text-sm font-medium text-gray-700">Total de Checklists</div>
          <div id="totalChecklists" class="text-2xl font-bold">0</div>
        </div>
        <div class="bg-green-100 p-4 rounded-lg">
          <div class="text-sm font-medium text-gray-700">Checklists Completos (100%)</div>
          <div id="completeChecklists" class="text-2xl font-bold">0</div>
        </div>
        <div class="bg-blue-100 p-4 rounded-lg">
          <div class="text-sm font-medium text-gray-700">Faltam para completar</div>
          <div id="remainingChecklists" class="text-2xl font-bold">0</div>
        </div>
      </div>
      <div class="flex justify-end mt-6">
        <button onclick="hideStatistics()" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">Fechar</button>
      </div>
    </div>
  </div>

  <script>
    // Global variables
    let currentPhotoRow = null;
    let currentPhotoCell = null;
    
    // Toggle sidebar
    function toggleSidebar() {
      document.getElementById('sidebar').classList.toggle('-translate-x-full');
      document.getElementById('overlay').classList.toggle('hidden');
    }
    
    // Close sidebar
    function closeSidebar() {
      document.getElementById('sidebar').classList.add('-translate-x-full');
      document.getElementById('overlay').classList.add('hidden');
    }
    
    // Select status
    function selectStatus(btn) {
      const buttons = btn.parentElement.querySelectorAll('.status-btn');
      buttons.forEach(b => {
        b.classList.remove(
          'bg-green-100', 'bg-red-100', 'bg-blue-100', 
          'text-green-800', 'text-red-800', 'text-blue-800', 
          'border-green-300', 'border-red-300', 'border-blue-300'
        );
      });
      
      if (btn.classList.contains('ok')) {
        btn.classList.add('bg-green-100', 'text-green-800', 'border-green-300');
      } else if (btn.classList.contains('nao-ok')) {
        btn.classList.add('bg-red-100', 'text-red-800', 'border-red-300');
      } else if (btn.classList.contains('nao-aplica')) {
        btn.classList.add('bg-blue-100', 'text-blue-800', 'border-blue-300');
      }
    }
    
    // Trigger camera/photo upload
    function triggerCamera(cell) {
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';
      fileInput.capture = 'environment';
      fileInput.style.display = 'none';
      
      fileInput.onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = function(ev) {
            updatePhotoCell(cell, ev.target.result);
          };
          reader.readAsDataURL(file);
        }
      };
      
      document.body.appendChild(fileInput);
      fileInput.click();
      document.body.removeChild(fileInput);
    }
    
    // Update photo cell with new image
    function updatePhotoCell(cell, photoData) {
      const td = cell.closest('td');
      const preview = td.querySelector('.photo-preview');
      const icon = td.querySelector('.photo-icon');
      
      preview.src = photoData;
      preview.classList.remove('hidden');
      icon.classList.add('hidden');
      
      // Add edit and delete buttons
      const actionsDiv = td.querySelector('.photo-actions') || document.createElement('div');
      if (!td.querySelector('.photo-actions')) {
        actionsDiv.className = 'photo-actions absolute inset-0 flex justify-center items-center bg-black bg-opacity-50 rounded';
        actionsDiv.innerHTML = `
          <button onclick="editPhoto(this)" class="bg-blue-500 hover:bg-blue-600 text-white p-1 rounded-full mx-1">
            <i class="fas fa-edit text-xs"></i>
          </button>
          <button onclick="deletePhotoCell(this)" class="bg-red-500 hover:bg-red-600 text-white p-1 rounded-full mx-1">
            <i class="fas fa-trash-alt text-xs"></i>
          </button>
        `;
        td.appendChild(actionsDiv);
      }
    }
    
    // Edit photo (opens fullscreen with options)
    function editPhoto(btn) {
      const td = btn.closest('td');
      const img = td.querySelector('.photo-preview');
      
      currentPhotoRow = td.closest('tr');
      currentPhotoCell = td;
      
      document.getElementById('fullscreenImage').src = img.src;
      document.getElementById('fullscreenOverlay').classList.remove('hidden');
      setTimeout(() => {
        document.getElementById('fullscreenOverlay').classList.add('opacity-100');
      }, 10);
    }
    
    // Replace photo in fullscreen view
    function replacePhoto() {
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';
      fileInput.style.display = 'none';
      
      fileInput.onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = function(ev) {
            document.getElementById('fullscreenImage').src = ev.target.result;
            updatePhotoCell(currentPhotoCell, ev.target.result);
          };
          reader.readAsDataURL(file);
        }
      };
      
      document.body.appendChild(fileInput);
      fileInput.click();
      document.body.removeChild(fileInput);
    }
    
    // Delete photo from fullscreen view
    function deletePhoto() {
      if (confirm('Tem certeza que deseja excluir esta foto?')) {
        const preview = currentPhotoCell.querySelector('.photo-preview');
        const icon = currentPhotoCell.querySelector('.photo-icon');
        const actions = currentPhotoCell.querySelector('.photo-actions');
        
        preview.src = '';
        preview.classList.add('hidden');
        icon.classList.remove('hidden');
        if (actions) actions.remove();
        
        closeFullscreen();
      }
    }
    
    // Delete photo from cell directly
    function deletePhotoCell(btn) {
      if (confirm('Tem certeza que deseja excluir esta foto?')) {
        const td = btn.closest('td');
        const preview = td.querySelector('.photo-preview');
        const icon = td.querySelector('.photo-icon');
        const actions = td.querySelector('.photo-actions');
        
        preview.src = '';
        preview.classList.add('hidden');
        icon.classList.remove('hidden');
        actions.remove();
      }
    }
    
    // Show fullscreen image
    function showFullscreenImage(src, cell) {
      currentPhotoRow = cell ? cell.closest('tr') : null;
      currentPhotoCell = cell;
      
      document.getElementById('fullscreenImage').src = src;
      document.getElementById('fullscreenOverlay').classList.remove('hidden');
      setTimeout(() => {
        document.getElementById('fullscreenOverlay').classList.add('opacity-100');
      }, 10);
    }
    
    // Close fullscreen view
    function closeFullscreen() {
      document.getElementById('fullscreenOverlay').classList.remove('opacity-100');
      setTimeout(() => {
        document.getElementById('fullscreenOverlay').classList.add('hidden');
      }, 300);
      currentPhotoRow = null;
      currentPhotoCell = null;
    }
    
    // Load checklist from CSV
    function loadChecklistFromCSV(input) {
      const file = input.files[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = function(event) {
        const csv = event.target.result;
        const lines = csv.split('\n').map(line => line.trim()).filter(Boolean);
        const headers = lines[0].split(',');
        
        if (headers.length !== 2 || headers[0] !== 'Nome do Checklist' || headers[1] !== 'Data e Horário') {
          alert('Formato do CSV inválido. O arquivo deve ter cabeçalhos "Nome do Checklist,Data e Horário"');
          return;
        }
        
        let html = '';
        for (let i = 1; i < lines.length; i++) {
          const [pergunta] = lines[i].split(',');
          html += `
            <tr class="border-b border-gray-200 hover:bg-gray-50">
              <td class="p-3 border border-gray-300">${pergunta}</td>
              <td class="p-3 border border-gray-300">
                <div class="flex gap-2 justify-between">
                  <button class="status-btn ok flex-1 py-1 px-2 border rounded text-sm" onclick="selectStatus(this)">OK</button>
                  <button class="status-btn nao-ok flex-1 py-1 px-2 border rounded text-sm" onclick="selectStatus(this)">NÃO OK</button>
                  <button class="status-btn nao-aplica flex-1 py-1 px-2 border rounded text-sm" onclick="selectStatus(this)">NA</button>
                </div>
              </td>
              <td class="p-3 border border-gray-300 relative">
                <img class="photo-preview hidden w-10 h-10 object-cover border-2 border-dashed border-blue-500 rounded cursor-pointer mx-auto" />
                <span class="photo-icon text-2xl cursor-pointer text-gray-500 hover:text-gray-700 flex justify-center" onclick="triggerCamera(this)" title="Adicionar foto">
                  <i class="fas fa-camera"></i>
                </span>
              </td>
            </tr>`;
        }
        
        document.getElementById('checklist-body').innerHTML = html;
      };
      reader.readAsText(file);
    }
    
    // Save results to localStorage
    function saveResults() {
      const rows = document.querySelectorAll('#checklist-body tr');
      const obsGeral = document.getElementById('observation').value.trim();
      const results = [];
      
      rows.forEach(row => {
        const pergunta = row.querySelector('td:first-child').textContent.trim();
        const statusBtn = row.querySelector('.status-btn.bg-green-100, .status-btn.bg-red-100, .status-btn.bg-blue-100');
        const imgElement = row.querySelector('.photo-preview');
        const foto = imgElement && !imgElement.classList.contains('hidden') ? imgElement.src : null;
        
        const status = statusBtn ? 
          (statusBtn.classList.contains('ok') ? 'OK' : 
           statusBtn.classList.contains('nao-ok') ? 'NÃO OK' : 'NA') : '';
        
        results.push({
          pergunta,
          status,
          foto
        });
      });
      
      const now = new Date().toLocaleString('pt-BR');
      const key = `checklist_${Date.now()}`;
      const dataToSave = {
        timestamp: now,
        matricula: "Exemplo123",
        data: results,
        observacao: obsGeral
      };
      
      localStorage.setItem(key, JSON.stringify(dataToSave));
      alert(`Checklist salvo às ${now}`);
      loadHistory(); // Atualiza histórico imediatamente
    }
    
    // Load history from localStorage
    function loadHistory(dateFilter = '') {
      const historyList = document.getElementById('historyList');
      const filterInput = document.getElementById('filterDate');
      const selectedDate = dateFilter || filterInput?.value || '';
      historyList.innerHTML = '';
      
      const keys = Object.keys(localStorage).filter(k => k.startsWith('checklist_'));
      const items = keys.map(k => {
        try {
          return JSON.parse(localStorage.getItem(k));
        } catch {
          return null;
        }
      }).filter(i => i && Array.isArray(i.data));
      
      const filteredItems = items.filter(item => {
        if (!item.timestamp) return false;
        
        const itemDateStr = item.timestamp.split(',')[0]; // Ex: "14/06/2025"
        const [dia, mes, ano] = itemDateStr.split('/');
        const itemDateISO = `${ano}-${mes.padStart(2, '0')}-${dia.padStart(2, '0')}`;
        
        if (selectedDate && itemDateISO !== selectedDate) return false;
        return true;
      });
      
      // Ordenar do mais recente para o mais antigo
      filteredItems.sort((a, b) => {
        return new Date(b.timestamp) - new Date(a.timestamp);
      });
      
      filteredItems.forEach(item => {
        const total = item.data.length;
        const respostas = item.data.filter(d => d.status).length;
        const percent = Math.round((respostas / total) * 100);
        
        const li = document.createElement('li');
        li.className = `p-3 mb-2 rounded cursor-pointer transition ${percent === 100 ? 
          'bg-green-50 border-l-4 border-green-500 text-green-800 hover:bg-green-100' : 
          'bg-red-50 border-l-4 border-red-500 text-red-800 hover:bg-red-100'}`;
        
        li.innerHTML = `
          <div class="flex justify-between items-center">
            <span class="font-medium">${item.timestamp}</span>
            <span class="bg-${percent === 100 ? 'green' : 'red'}-500 text-white text-xs font-bold px-2 py-1 rounded-full">
              ${percent}%
            </span>
          </div>
          <div class="text-sm text-gray-600 mt-1 truncate">
            ${item.observacao || 'Sem observação'}
          </div>
        `;
        
        li.onclick = () => loadSavedChecklist(item.data, item.observacao, item.timestamp);
        historyList.appendChild(li);
      });
      
      if (filteredItems.length === 0) {
        const li = document.createElement('li');
        li.className = 'text-center text-gray-500 py-4';
        li.textContent = 'Nenhum checklist encontrado.';
        historyList.appendChild(li);
      }
    }
    
    // Load saved checklist into the form
    function loadSavedChecklist(savedData, obsGeral, timestamp) {
      closeSidebar();
      
      let html = '';
      savedData.forEach(reg => {
        const okSelected = reg.status === 'OK' ? 'bg-green-100 text-green-800 border-green-300' : '';
        const naoOkSelected = reg.status === 'NÃO OK' ? 'bg-red-100 text-red-800 border-red-300' : '';
        const naoAplicaSelected = reg.status === 'NA' ? 'bg-blue-100 text-blue-800 border-blue-300' : '';
        
        const hasPhoto = reg.foto ? 'block' : 'hidden';
        const hasIcon = reg.foto ? 'hidden' : 'flex';
        
        html += `
          <tr class="border-b border-gray-200 hover:bg-gray-50">
            <td class="p-3 border border-gray-300">${reg.pergunta}</td>
            <td class="p-3 border border-gray-300">
              <div class="flex gap-2 justify-between">
                <button class="status-btn ok flex-1 py-1 px-2 border rounded text-sm ${okSelected}" onclick="selectStatus(this)">OK</button>
                <button class="status-btn nao-ok flex-1 py-1 px-2 border rounded text-sm ${naoOkSelected}" onclick="selectStatus(this)">NÃO OK</button>
                <button class="status-btn nao-aplica flex-1 py-1 px-2 border rounded text-sm ${naoAplicaSelected}" onclick="selectStatus(this)">NA</button>
              </div>
            </td>
            <td class="p-3 border border-gray-300 relative">
              <img class="photo-preview w-10 h-10 object-cover border-2 border-dashed border-blue-500 rounded cursor-pointer mx-auto ${hasPhoto}" 
                   src="${reg.foto || ''}" 
                   onclick="event.stopPropagation(); showFullscreenImage('${reg.foto}', this.parentElement)"/>
              <span class="photo-icon text-2xl cursor-pointer text-gray-500 hover:text-gray-700 ${hasIcon} justify-center" 
                    onclick="triggerCamera(this)" title="Adicionar foto">
                <i class="fas fa-camera"></i>
              </span>
              ${reg.foto ? `
                <div class="photo-actions absolute inset-0 flex justify-center items-center bg-black bg-opacity-50 rounded">
                  <button onclick="editPhoto(this)" class="bg-blue-500 hover:bg-blue-600 text-white p-1 rounded-full mx-1">
                    <i class="fas fa-edit text-xs"></i>
                  </button>
                  <button onclick="deletePhotoCell(this)" class="bg-red-500 hover:bg-red-600 text-white p-1 rounded-full mx-1">
                    <i class="fas fa-trash-alt text-xs"></i>
                  </button>
                </div>
              ` : ''}
            </td>
          </tr>`;
      });
      
      document.getElementById('checklist-body').innerHTML = html;
      document.getElementById('observation').value = obsGeral || '';
    }
    
    // Show export modal
    function showExportModal() {
      const today = new Date();
      const formattedDate = today.toISOString().split('T')[0];
      document.getElementById('exportStartDate').value = formattedDate;
      document.getElementById('exportEndDate').value = formattedDate;
      document.getElementById('exportModal').classList.remove('hidden');
    }

    // Hide export modal
    function hideExportModal() {
      document.getElementById('exportModal').classList.add('hidden');
    }

    // Show statistics modal
    function showStatistics() {
      closeSidebar();
      
      const keys = Object.keys(localStorage).filter(k => k.startsWith('checklist_'));
      const total = keys.length;
      
      let complete = 0;
      keys.forEach(k => {
        try {
          const data = JSON.parse(localStorage.getItem(k));
          if (data && Array.isArray(data.data)) {
            const answered = data.data.filter(d => d.status).length;
            if (answered === data.data.length) complete++;
          }
        } catch {}
      });
      
      const remaining = total - complete;
      
      document.getElementById('totalChecklists').textContent = total;
      document.getElementById('completeChecklists').textContent = complete;
      document.getElementById('remainingChecklists').textContent = remaining;
      
      
      document.getElementById('statisticsModal').classList.remove('hidden');
    }

    // Hide statistics modal
    function hideStatistics() {
      document.getElementById('statisticsModal').classList.add('hidden');
    }

    // Export checklists by date range
    function exportChecklistsByDateRange() {
      const startDate = document.getElementById('exportStartDate').value;
      const endDate = document.getElementById('exportEndDate').value;
      
      if (!startDate || !endDate) {
        alert('Selecione ambas as datas');
        return;
      }
      
      if (new Date(startDate) > new Date(endDate)) {
        alert('Data inicial não pode ser maior que data final');
        return;
      }

      const keys = Object.keys(localStorage).filter(k => k.startsWith('checklist_'));
      const items = keys.map(k => {
        try {
          return { key: k, data: JSON.parse(localStorage.getItem(k)) };
        } catch {
          return null;
        }
      }).filter(i => i && i.data && Array.isArray(i.data.data));

      // Filter items by date range
      const filteredItems = items.filter(item => {
        if (!item.data.timestamp) return false;
        
        const itemDateStr = item.data.timestamp.split(',')[0]; // Ex: "14/06/2025"
        const [dia, mes, ano] = itemDateStr.split('/');
        const itemDateISO = `${ano}-${mes.padStart(2, '0')}-${dia.padStart(2, '0')}`;
        
        const itemDate = new Date(itemDateISO);
        const start = new Date(startDate);
        const end = new Date(endDate);
        
        return itemDate >= start && itemDate <= end;
      });

      if (filteredItems.length === 0) {
        alert('Nenhum checklist encontrado para este período');
        return;
      }

      // Create CSV content
      let csvContent = "Data,Hora,Checklist,Status,Observação\n";
      
      filteredItems.forEach(item => {
        const [date, time] = item.data.timestamp.split(', ');
        const checklistName = document.querySelector('h1').textContent;
        const observation = item.data.observacao || '';
        
        item.data.data.forEach(entry => {
          csvContent += `"${date}","${time}","${entry.pergunta}","${entry.status}","${observation}"\n`;
        });
      });

      // Download CSV file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', `checklist_export_${startDate}_to_${endDate}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      hideExportModal();
    }

    // Download CSV template
    function downloadTemplate() {
      const csvContent = "Nome do Checklist,Data e Horário\n" +
        "Verificar se todos os equipamentos estão ligados,\n" +
        "Conferir temperatura ambiente,\n" +
        "Verificar conexão com a internet,\n" +
        "Conferir nível de bateria,\n" +
        "Verificar atualizações pendentes,\n" +
        "Testar funcionalidade básica";
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', 'template_checklist.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    // Initialize on page load
    window.addEventListener('DOMContentLoaded', () => {
      loadHistory();
      
      // Set today's date as default filter
      const today = new Date();
      const formattedDate = today.toISOString().split('T')[0];
      document.getElementById('filterDate').value = formattedDate;
    });
  </script>
</body>
</html>