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+ constructor() {
8
+ this.selectedDevice = null;
9
+ this.selectedOS = null;
10
+ this.flashingProgress = null;
11
+ this.flashingInterval = null;
12
+ this.currentTab = 'recommended';
13
+
14
+ // Mock data for demonstration
15
+ this.mockDevices = [
16
+ {
17
+ id: 'sdb',
18
+ name: 'SanDisk Ultra 32GB',
19
+ path: '/dev/sdb',
20
+ size: '29.8GB',
21
+ sizeBytes: 32000000000,
22
+ type: 'sd'
23
+ },
24
+ {
25
+ id: 'sdc',
26
+ name: 'Samsung EVO 64GB',
27
+ path: '/dev/sdc',
28
+ size: '59.5GB',
29
+ sizeBytes: 64000000000,
30
+ type: 'sd'
31
+ },
32
+ {
33
+ id: 'sdd',
34
+ name: 'Kingston Canvas 16GB',
35
+ path: '/dev/sdd',
36
+ size: '14.9GB',
37
+ sizeBytes: 16000000000,
38
+ type: 'usb'
39
+ }
40
+ ];
41
+
42
+ this.osImages = {
43
+ recommended: [
44
+ {
45
+ id: 'rpi-os-64',
46
+ name: 'Raspberry Pi OS (64-bit)',
47
+ description: 'Recommended for most users',
48
+ version: 'v2023-05-03',
49
+ size: '1.2GB',
50
+ sizeBytes: 1200000000,
51
+ category: 'official',
52
+ image: 'https://www.raspberrypi.com/app/uploads/2022/02/COLOUR-Raspberry-Pi-Symbol-Registered.png'
53
+ },
54
+ {
55
+ id: 'rpi-os-lite-32',
56
+ name: 'Raspberry Pi OS Lite (32-bit)',
57
+ description: 'Minimal image for headless setups',
58
+ version: 'v2023-05-03',
59
+ size: '450MB',
60
+ sizeBytes: 450000000,
61
+ category: 'official',
62
+ image: 'https://www.raspberrypi.com/app/uploads/2022/02/COLOUR-Raspberry-Pi-Symbol-Registered.png'
63
+ },
64
+ {
65
+ id: 'ubuntu-server',
66
+ name: 'Ubuntu Server 22.04 LTS',
67
+ description: 'Official Ubuntu for Raspberry Pi',
68
+ version: 'v22.04.2',
69
+ size: '1.8GB',
70
+ sizeBytes: 1800000000,
71
+ category: 'ubuntu',
72
+ image: 'https://assets.ubuntu.com/v1/29985a98-ubuntu-logo32.png'
73
+ }
74
+ ],
75
+ all: [
76
+ {
77
+ id: 'rpi-os-64',
78
+ name: 'Raspberry Pi OS (64-bit)',
79
+ description: 'Recommended for most users',
80
+ version: 'v2023-05-03',
81
+ size: '1.2GB',
82
+ sizeBytes: 1200000000,
83
+ category: 'official',
84
+ image: 'https://www.raspberrypi.com/app/uploads/2022/02/COLOUR-Raspberry-Pi-Symbol-Registered.png'
85
+ },
86
+ {
87
+ id: 'rpi-os-lite-32',
88
+ name: 'Raspberry Pi OS Lite (32-bit)',
89
+ description: 'Minimal image for headless setups',
90
+ version: 'v2023-05-03',
91
+ size: '450MB',
92
+ sizeBytes: 450000000,
93
+ category: 'official',
94
+ image: 'https://www.raspberrypi.com/app/uploads/2022/02/COLOUR-Raspberry-Pi-Symbol-Registered.png'
95
+ },
96
+ {
97
+ id: 'ubuntu-server',
98
+ name: 'Ubuntu Server 22.04 LTS',
99
+ description: 'Official Ubuntu for Raspberry Pi',
100
+ version: 'v22.04.2',
101
+ size: '1.8GB',
102
+ sizeBytes: 1800000000,
103
+ category: 'ubuntu',
104
+ image: 'https://assets.ubuntu.com/v1/29985a98-ubuntu-logo32.png'
105
+ },
106
+ {
107
+ id: 'retropie',
108
+ name: 'RetroPie 4.8',
109
+ description: 'Turn your Pi into a retro gaming machine',
110
+ version: 'v4.8',
111
+ size: '2.5GB',
112
+ sizeBytes: 2500000000,
113
+ category: 'gaming',
114
+ image: 'https://retropie.org.uk/wp-content/uploads/2017/07/cropped-RetroPieLogo-32x32.png'
115
+ },
116
+ {
117
+ id: 'libreelec',
118
+ name: 'LibreELEC 11.0',
119
+ description: 'Kodi media center OS',
120
+ version: 'v11.0.3',
121
+ size: '350MB',
122
+ sizeBytes: 350000000,
123
+ category: 'media',
124
+ image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiByeD0iOCIgZmlsbD0iIzAwN0ZGRiIvPgo8cGF0aCBkPSJNMTAgMTBoMjB2MjBIMTBWMTB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K'
125
+ },
126
+ {
127
+ id: 'kali-linux',
128
+ name: 'Kali Linux 2023.2',
129
+ description: 'Security testing and penetration testing',
130
+ version: 'v2023.2',
131
+ size: '3.1GB',
132
+ sizeBytes: 3100000000,
133
+ category: 'security',
134
+ image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiByeD0iOCIgZmlsbD0iIzAwMDAwMCIvPgo8cGF0aCBkPSJNMTAgMTBoMjB2MjBIMTBWMTB6IiBmaWxsPSIjRkYwMDAwIi8+Cjwvc3ZnPgo='
135
+ }
136
+ ],
137
+ other: []
138
+ };
139
+
140
+ this.init();
141
+ }
142
+
143
+ /**
144
+ * Initialize the application
145
+ */
146
+ init() {
147
+ console.log('Initializing PiFlash application...');
148
+ this.setupEventListeners();
149
+ this.loadDevices();
150
+ this.loadOSImages();
151
+ this.updateFlashButton();
152
+ }
153
+
154
+ /**
155
+ * Set up all event listeners
156
+ */
157
+ setupEventListeners() {
158
+ // Device refresh button
159
+ document.getElementById('refreshDevices').addEventListener('click', () => {
160
+ this.refreshDevices();
161
+ });
162
+
163
+ // OS image tabs
164
+ document.getElementById('tabRecommended').addEventListener('click', () => {
165
+ this.switchTab('recommended');
166
+ });
167
+ document.getElementById('tabAll').addEventListener('click', () => {
168
+ this.switchTab('all');
169
+ });
170
+ document.getElementById('tabOther').addEventListener('click', () => {
171
+ this.switchTab('other');
172
+ });
173
+
174
+ // Search functionality
175
+ document.getElementById('searchOS').addEventListener('input', (e) => {
176
+ this.filterOSImages(e.target.value);
177
+ });
178
+
179
+ // Custom image upload
180
+ document.getElementById('customImageUpload').addEventListener('click', () => {
181
+ document.getElementById('customImageFile').click();
182
+ });
183
+
184
+ document.getElementById('customImageFile').addEventListener('change', (e) => {
185
+ this.handleCustomImageUpload(e.target.files[0]);
186
+ });
187
+
188
+ // Flash button
189
+ document.getElementById('flashButton').addEventListener('click', () => {
190
+ this.startFlashing();
191
+ });
192
+
193
+ // Cancel flash button
194
+ document.getElementById('cancelFlash').addEventListener('click', () => {
195
+ this.cancelFlashing();
196
+ });
197
+
198
+ // Flash another button
199
+ document.getElementById('flashAnother').addEventListener('click', () => {
200
+ this.resetApplication();
201
+ });
202
+
203
+ // Form validation
204
+ this.setupFormValidation();
205
+ }
206
+
207
+ /**
208
+ * Set up form validation
209
+ */
210
+ setupFormValidation() {
211
+ const inputs = ['wifiSSID', 'wifiPassword', 'hostname'];
212
+ inputs.forEach(id => {
213
+ const input = document.getElementById(id);
214
+ input.addEventListener('input', () => {
215
+ this.validateInput(input);
216
+ });
217
+ });
218
+ }
219
+
220
+ /**
221
+ * Validate input fields
222
+ */
223
+ validateInput(input) {
224
+ const value = input.value.trim();
225
+
226
+ if (input.id === 'hostname') {
227
+ // Validate hostname format
228
+ const hostnameRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*$/;
229
+ if (value && !hostnameRegex.test(value)) {
230
+ input.classList.add('border-red-500');
231
+ this.showTooltip(input, 'Invalid hostname format');
232
+ } else {
233
+ input.classList.remove('border-red-500');
234
+ this.hideTooltip(input);
235
+ }
236
+ }
237
+
238
+ if (input.id === 'wifiSSID') {
239
+ // Basic SSID validation
240
+ if (value && value.length > 32) {
241
+ input.classList.add('border-red-500');
242
+ this.showTooltip(input, 'SSID too long (max 32 characters)');
243
+ } else {
244
+ input.classList.remove('border-red-500');
245
+ this.hideTooltip(input);
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Show tooltip for validation errors
252
+ */
253
+ showTooltip(element, message) {
254
+ // Remove existing tooltip
255
+ this.hideTooltip(element);
256
+
257
+ const tooltip = document.createElement('div');
258
+ tooltip.className = 'absolute z-10 px-2 py-1 text-xs text-white bg-red-600 rounded shadow-lg tooltip';
259
+ tooltip.textContent = message;
260
+ tooltip.style.top = '-30px';
261
+ tooltip.style.left = '0';
262
+
263
+ element.parentElement.style.position = 'relative';
264
+ element.parentElement.appendChild(tooltip);
265
+ }
266
+
267
+ /**
268
+ * Hide tooltip
269
+ */
270
+ hideTooltip(element) {
271
+ const tooltip = element.parentElement.querySelector('.tooltip');
272
+ if (tooltip) {
273
+ tooltip.remove();
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Load and display available devices
279
+ */
280
+ loadDevices() {
281
+ console.log('Loading devices...');
282
+ const deviceList = document.getElementById('deviceList');
283
+
284
+ // Show loading state
285
+ deviceList.innerHTML = '<div class="skeleton h-16 rounded-lg"></div>';
286
+
287
+ // Simulate loading delay
288
+ setTimeout(() => {
289
+ deviceList.innerHTML = '';
290
+
291
+ if (this.mockDevices.length === 0) {
292
+ deviceList.innerHTML = `
293
+ <div class="text-center py-8 text-gray-500">
294
+ <i class="fas fa-exclamation-circle text-2xl mb-2"></i>
295
+ <p class="text-sm">No storage devices found</p>
296
+ <p class="text-xs mt-1">Insert an SD card or USB drive</p>
297
+ </div>
298
+ `;
299
+ return;
300
+ }
301
+
302
+ this.mockDevices.forEach(device => {
303
+ const deviceElement = this.createDeviceElement(device);
304
+ deviceList.appendChild(deviceElement);
305
+ });
306
+ }, 1000);
307
+ }
308
+
309
+ /**
310
+ * Create device element
311
+ */
312
+ createDeviceElement(device) {
313
+ const deviceDiv = document.createElement('div');
314
+ deviceDiv.className = 'device-card p-3 border border-gray-200 rounded-lg cursor-pointer';
315
+ deviceDiv.setAttribute('data-device-id', device.id);
316
+
317
+ const icon = device.type === 'sd' ? 'fas fa-sd-card' : 'fas fa-usb';
318
+ const iconColor = device.type === 'sd' ? 'text-blue-500' : 'text-green-500';
319
+
320
+ deviceDiv.innerHTML = `
321
+ <div class="flex items-center justify-between">
322
+ <div class="flex items-center">
323
+ <i class="${icon} ${iconColor} mr-3"></i>
324
+ <div>
325
+ <h3 class="font-medium text-gray-800">${device.name}</h3>
326
+ <p class="text-sm text-gray-600">${device.path} • ${device.size}</p>
327
+ </div>
328
+ </div>
329
+ <div class="flex items-center">
330
+ <i class="fas fa-check text-green-500 hidden device-selected-icon"></i>
331
+ </div>
332
+ </div>
333
+ `;
334
+
335
+ deviceDiv.addEventListener('click', () => {
336
+ this.selectDevice(device);
337
+ });
338
+
339
+ return deviceDiv;
340
+ }
341
+
342
+ /**
343
+ * Select a device
344
+ */
345
+ selectDevice(device) {
346
+ console.log('Selecting device:', device.name);
347
+
348
+ // Remove previous selection
349
+ document.querySelectorAll('.device-card').forEach(card => {
350
+ card.classList.remove('selected');
351
+ card.querySelector('.device-selected-icon').classList.add('hidden');
352
+ });
353
+
354
+ // Add selection to current device
355
+ const deviceElement = document.querySelector(`[data-device-id="${device.id}"]`);
356
+ deviceElement.classList.add('selected');
357
+ deviceElement.querySelector('.device-selected-icon').classList.remove('hidden');
358
+
359
+ this.selectedDevice = device;
360
+ this.updateFlashSummary();
361
+ this.updateFlashButton();
362
+ }
363
+
364
+ /**
365
+ * Refresh devices list
366
+ */
367
+ refreshDevices() {
368
+ console.log('Refreshing devices...');
369
+ const refreshButton = document.getElementById('refreshDevices');
370
+ const icon = refreshButton.querySelector('i');
371
+
372
+ icon.classList.add('rotate-animation');
373
+
374
+ setTimeout(() => {
375
+ this.loadDevices();
376
+ icon.classList.remove('rotate-animation');
377
+ }, 1000);
378
+ }
379
+
380
+ /**
381
+ * Switch between OS image tabs
382
+ */
383
+ switchTab(tab) {
384
+ console.log('Switching to tab:', tab);
385
+
386
+ // Update tab buttons
387
+ document.querySelectorAll('.tab-button').forEach(button => {
388
+ button.classList.remove('active');
389
+ });
390
+ document.getElementById(`tab${tab.charAt(0).toUpperCase() + tab.slice(1)}`).classList.add('active');
391
+
392
+ this.currentTab = tab;
393
+ this.loadOSImages();
394
+ }
395
+
396
+ /**
397
+ * Load and display OS images
398
+ */
399
+ loadOSImages() {
400
+ console.log('Loading OS images for tab:', this.currentTab);
401
+ const osImageList = document.getElementById('osImageList');
402
+
403
+ // Show loading state
404
+ osImageList.innerHTML = '<div class="skeleton h-20 rounded-lg mb-3"></div>'.repeat(3);
405
+
406
+ setTimeout(() => {
407
+ osImageList.innerHTML = '';
408
+ const images = this.osImages[this.currentTab] || [];
409
+
410
+ if (images.length === 0) {
411
+ osImageList.innerHTML = `
412
+ <div class="text-center py-8 text-gray-500">
413
+ <i class="fas fa-image text-2xl mb-2"></i>
414
+ <p class="text-sm">No images available</p>
415
+ </div>
416
+ `;
417
+ return;
418
+ }
419
+
420
+ images.forEach(osImage => {
421
+ const imageElement = this.createOSImageElement(osImage);
422
+ osImageList.appendChild(imageElement);
423
+ });
424
+ }, 500);
425
+ }
426
+
427
+ /**
428
+ * Create OS image element
429
+ */
430
+ createOSImageElement(osImage) {
431
+ const imageDiv = document.createElement('div');
432
+ imageDiv.className = 'os-image-card p-3 border border-gray-200 rounded-lg cursor-pointer fade-in';
433
+ imageDiv.setAttribute('data-os-id', osImage.id);
434
+
435
+ imageDiv.innerHTML = `
436
+ <div class="flex items-start">
437
+ <img src="${osImage.image}" alt="${osImage.name}" class="w-10 h-10 rounded mr-3 flex-shrink-0" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiByeD0iOCIgZmlsbD0iIzZCNzI4MCIvPgo8cGF0aCBkPSJNMTIgMTVoMTZ2MkgxMnYtMnptMCA0aDE2djJIMTJ2LTJ6bTAgNGgxMnYySDE2di0yeiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg=='">
438
+ <div class="flex-1 min-w-0">
439
+ <h3 class="font-medium text-gray-800 truncate">${osImage.name}</h3>
440
+ <p class="text-sm text-gray-600 mb-1">${osImage.description}</p>
441
+ <div class="flex items-center justify-between text-xs text-gray-500">
442
+ <span>${osImage.version}</span>
443
+ <span>${osImage.size}</span>
444
+ </div>
445
+ </div>
446
+ <div class="ml-2 flex items-center">
447
+ <i class="fas fa-check text-green-500 hidden os-selected-icon"></i>
448
+ </div>
449
+ </div>
450
+ `;
451
+
452
+ imageDiv.addEventListener('click', () => {
453
+ this.selectOSImage(osImage);
454
+ });
455
+
456
+ return imageDiv;
457
+ }
458
+
459
+ /**
460
+ * Select an OS image
461
+ */
462
+ selectOSImage(osImage) {
463
+ console.log('Selecting OS image:', osImage.name);
464
+
465
+ // Remove previous selection
466
+ document.querySelectorAll('.os-image-card').forEach(card => {
467
+ card.classList.remove('selected');
468
+ const icon = card.querySelector('.os-selected-icon');
469
+ if (icon) icon.classList.add('hidden');
470
+ });
471
+
472
+ // Add selection to current image
473
+ const imageElement = document.querySelector(`[data-os-id="${osImage.id}"]`);
474
+ if (imageElement) {
475
+ imageElement.classList.add('selected');
476
+ const icon = imageElement.querySelector('.os-selected-icon');
477
+ if (icon) icon.classList.remove('hidden');
478
+ }
479
+
480
+ this.selectedOS = osImage;
481
+ this.updateFlashSummary();
482
+ this.updateFlashButton();
483
+ }
484
+
485
+ /**
486
+ * Filter OS images based on search
487
+ */
488
+ filterOSImages(searchTerm) {
489
+ const searchLower = searchTerm.toLowerCase();
490
+ const images = this.osImages[this.currentTab] || [];
491
+ const filteredImages = images.filter(image =>
492
+ image.name.toLowerCase().includes(searchLower) ||
493
+ image.description.toLowerCase().includes(searchLower)
494
+ );
495
+
496
+ const osImageList = document.getElementById('osImageList');
497
+ osImageList.innerHTML = '';
498
+
499
+ if (filteredImages.length === 0) {
500
+ osImageList.innerHTML = `
501
+ <div class="text-center py-8 text-gray-500">
502
+ <i class="fas fa-search text-2xl mb-2"></i>
503
+ <p class="text-sm">No images found for "${searchTerm}"</p>
504
+ </div>
505
+ `;
506
+ return;
507
+ }
508
+
509
+ filteredImages.forEach(osImage => {
510
+ const imageElement = this.createOSImageElement(osImage);
511
+ osImageList.appendChild(imageElement);
512
+ });
513
+ }
514
+
515
+ /**
516
+ * Handle custom image upload
517
+ */
518
+ handleCustomImageUpload(file) {
519
+ if (!file) return;
520
+
521
+ console.log('Handling custom image upload:', file.name);
522
+
523
+ const customOS = {
524
+ id: 'custom-' + Date.now(),
525
+ name: file.name,
526
+ description: 'Custom image file',
527
+ version: 'Custom',
528
+ size: this.formatFileSize(file.size),
529
+ sizeBytes: file.size,
530
+ category: 'custom',
531
+ file: file,
532
+ image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiByeD0iOCIgZmlsbD0iIzEwQjk4MSIvPgo8cGF0aCBkPSJNMTYgMTJsOCA4LTggOHYtNEgxMnYtOGg0di00eiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg=='
533
+ };
534
+
535
+ this.selectOSImage(customOS);
536
+
537
+ // Update the upload area to show selected file
538
+ const uploadArea = document.getElementById('customImageUpload');
539
+ uploadArea.innerHTML = `
540
+ <div class="flex items-center justify-center">
541
+ <i class="fas fa-file-check text-2xl text-green-600 mr-2"></i>
542
+ <div class="text-left">
543
+ <h3 class="font-medium text-gray-700">${file.name}</h3>
544
+ <p class="text-sm text-gray-500">${this.formatFileSize(file.size)}</p>
545
+ </div>
546
+ </div>
547
+ `;
548
+ uploadArea.classList.add('border-green-400', 'bg-green-50');
549
+ }
550
+
551
+ /**
552
+ * Format file size
553
+ */
554
+ formatFileSize(bytes) {
555
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
556
+ let size = bytes;
557
+ let unitIndex = 0;
558
+
559
+ while (size >= 1024 && unitIndex < units.length - 1) {
560
+ size /= 1024;
561
+ unitIndex++;
562
+ }
563
+
564
+ return `${size.toFixed(1)}${units[unitIndex]}`;
565
+ }
566
+
567
+ /**
568
+ * Update flash summary
569
+ */
570
+ updateFlashSummary() {
571
+ const summaryDiv = document.getElementById('flashSummary');
572
+
573
+ if (!this.selectedDevice && !this.selectedOS) {
574
+ summaryDiv.innerHTML = `
575
+ <div class="flex items-center mb-2">
576
+ <i class="fas fa-info-circle text-gray-500 mr-2"></i>
577
+ <h3 class="font-medium text-gray-700">Select Image and Device</h3>
578
+ </div>
579
+ <p class="text-sm text-gray-600">
580
+ Choose an OS image and storage device to get started.
581
+ </p>
582
+ `;
583
+ return;
584
+ }
585
+
586
+ if (this.selectedOS && !this.selectedDevice) {
587
+ summaryDiv.innerHTML = `
588
+ <div class="flex items-center mb-2">
589
+ <i class="fas fa-exclamation-triangle text-yellow-500 mr-2"></i>
590
+ <h3 class="font-medium text-gray-700">Select Storage Device</h3>
591
+ </div>
592
+ <p class="text-sm text-gray-600">
593
+ <strong>Image:</strong> ${this.selectedOS.name}<br>
594
+ Choose a storage device to continue.
595
+ </p>
596
+ `;
597
+ return;
598
+ }
599
+
600
+ if (!this.selectedOS && this.selectedDevice) {
601
+ summaryDiv.innerHTML = `
602
+ <div class="flex items-center mb-2">
603
+ <i class="fas fa-exclamation-triangle text-yellow-500 mr-2"></i>
604
+ <h3 class="font-medium text-gray-700">Select OS Image</h3>
605
+ </div>
606
+ <p class="text-sm text-gray-600">
607
+ <strong>Device:</strong> ${this.selectedDevice.name}<br>
608
+ Choose an OS image to continue.
609
+ </p>
610
+ `;
611
+ return;
612
+ }
613
+
614
+ // Both selected
615
+ const isDeviceCompatible = this.selectedDevice.sizeBytes >= this.selectedOS.sizeBytes;
616
+ const statusIcon = isDeviceCompatible ? 'fas fa-check-circle text-green-500' : 'fas fa-exclamation-triangle text-red-500';
617
+ const statusText = isDeviceCompatible ? 'Ready to Flash' : 'Size Mismatch';
618
+
619
+ summaryDiv.innerHTML = `
620
+ <div class="flex items-center mb-2">
621
+ <i class="${statusIcon} mr-2"></i>
622
+ <h3 class="font-medium text-gray-700">${statusText}</h3>
623
+ </div>
624
+ <div class="text-sm text-gray-600 space-y-1">
625
+ <p><strong>Image:</strong> ${this.selectedOS.name} (${this.selectedOS.size})</p>
626
+ <p><strong>Device:</strong> ${this.selectedDevice.name} (${this.selectedDevice.size})</p>
627
+ ${!isDeviceCompatible ? '<p class="text-red-600 mt-2"><strong>Warning:</strong> Device is too small for this image.</p>' : ''}
628
+ </div>
629
+ `;
630
+ }
631
+
632
+ /**
633
+ * Update flash button state
634
+ */
635
+ updateFlashButton() {
636
+ const flashButton = document.getElementById('flashButton');
637
+ const canFlash = this.selectedDevice && this.selectedOS &&
638
+ this.selectedDevice.sizeBytes >= this.selectedOS.sizeBytes;
639
+
640
+ if (canFlash) {
641
+ flashButton.disabled = false;
642
+ flashButton.className = 'w-full mt-6 py-3 px-4 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg shadow-md transition duration-300 flex items-center justify-center';
643
+ flashButton.innerHTML = '<i class="fas fa-bolt mr-2"></i> Flash!';
644
+ } else {
645
+ flashButton.disabled = true;
646
+ flashButton.className = 'w-full mt-6 py-3 px-4 bg-gray-400 text-white font-semibold rounded-lg shadow-md transition duration-300 flex items-center justify-center cursor-not-allowed';
647
+
648
+ if (!this.selectedDevice && !this.selectedOS) {
649
+ flashButton.innerHTML = '<i class="fas fa-bolt mr-2"></i> Select Image and Device';
650
+ } else if (!this.selectedDevice) {
651
+ flashButton.innerHTML = '<i class="fas fa-bolt mr-2"></i> Select Storage Device';
652
+ } else if (!this.selectedOS) {
653
+ flashButton.innerHTML = '<i class="fas fa-bolt mr-2"></i> Select OS Image';
654
+ } else {
655
+ flashButton.innerHTML = '<i class="fas fa-exclamation-triangle mr-2"></i> Device Too Small';
656
+ }
657
+ }
658
+ }
659
+
660
+ /**
661
+ * Start the flashing process
662
+ */
663
+ startFlashing() {
664
+ if (!this.selectedDevice || !this.selectedOS) return;
665
+
666
+ console.log('Starting flash process...');
667
+
668
+ // Show confirmation dialog
669
+ const confirmed = confirm(
670
+ `Are you sure you want to flash "${this.selectedOS.name}" to "${this.selectedDevice.name}"?\n\n` +
671
+ `This will PERMANENTLY erase all data on the device!\n\n` +
672
+ `Device: ${this.selectedDevice.path} (${this.selectedDevice.size})\n` +
673
+ `Image: ${this.selectedOS.name} (${this.selectedOS.size})`
674
+ );
675
+
676
+ if (!confirmed) return;
677
+
678
+ // Hide flash summary and show progress
679
+ document.getElementById('flashSummary').parentElement.classList.add('hidden');
680
+ document.getElementById('progressSection').classList.remove('hidden');
681
+ document.getElementById('progressSection').classList.add('slide-up');
682
+
683
+ // Initialize progress
684
+ this.flashingProgress = {
685
+ stage: 'preparing',
686
+ percent: 0,
687
+ speed: 0,
688
+ eta: 0,
689
+ startTime: Date.now()
690
+ };
691
+
692
+ this.updateProgress();
693
+ this.simulateFlashingProcess();
694
+ }
695
+
696
+ /**
697
+ * Simulate the flashing process
698
+ */
699
+ simulateFlashingProcess() {
700
+ const stages = [
701
+ { name: 'preparing', duration: 2000, message: 'Preparing device...' },
702
+ { name: 'unmounting', duration: 1000, message: 'Unmounting device...' },
703
+ { name: 'writing', duration: 15000, message: 'Writing image...' },
704
+ { name: 'verifying', duration: 8000, message: 'Verifying write...' },
705
+ { name: 'ejecting', duration: 1000, message: 'Ejecting device...' }
706
+ ];
707
+
708
+ let currentStageIndex = 0;
709
+ let stageStartTime = Date.now();
710
+ let totalDuration = stages.reduce((sum, stage) => sum + stage.duration, 0);
711
+ let elapsedTotal = 0;
712
+
713
+ this.flashingInterval = setInterval(() => {
714
+ const now = Date.now();
715
+ const currentStage = stages[currentStageIndex];
716
+ const stageElapsed = now - stageStartTime;
717
+ const stageProgress = Math.min(stageElapsed / currentStage.duration, 1);
718
+
719
+ // Update progress
720
+ const overallProgress = (elapsedTotal + (stageProgress * currentStage.duration)) / totalDuration;
721
+ this.flashingProgress.percent = Math.round(overallProgress * 100);
722
+ this.flashingProgress.stage = currentStage.name;
723
+ this.flashingProgress.message = currentStage.message;
724
+
725
+ // Calculate speed and ETA (simulation)
726
+ if (currentStage.name === 'writing') {
727
+ const bytesWritten = stageProgress * this.selectedOS.sizeBytes;
728
+ const timeElapsed = stageElapsed / 1000; // seconds
729
+ this.flashingProgress.speed = bytesWritten / timeElapsed; // bytes per second
730
+ this.flashingProgress.eta = (this.selectedOS.sizeBytes - bytesWritten) / this.flashingProgress.speed * 1000; // ms
731
+ }
732
+
733
+ this.updateProgress();
734
+
735
+ // Move to next stage
736
+ if (stageProgress >= 1) {
737
+ elapsedTotal += currentStage.duration;
738
+ currentStageIndex++;
739
+ stageStartTime = now;
740
+
741
+ if (currentStageIndex >= stages.length) {
742
+ clearInterval(this.flashingInterval);
743
+ this.completeFlashing();
744
+ }
745
+ }
746
+ }, 100);
747
+ }
748
+
749
+ /**
750
+ * Update progress display
751
+ */
752
+ updateProgress() {
753
+ const progress = this.flashingProgress;
754
+
755
+ // Update progress bar
756
+ document.getElementById('progressBar').style.width = `${progress.percent}%`;
757
+ document.getElementById('progressPercent').textContent = `${progress.percent}%`;
758
+ document.getElementById('progressStatus').textContent = progress.message || 'Processing...';
759
+
760
+ // Update time remaining
761
+ const timeRemaining = document.getElementById('timeRemaining');
762
+ if (progress.eta && progress.eta > 0) {
763
+ const minutes = Math.floor(progress.eta / 60000);
764
+ const seconds = Math.floor((progress.eta % 60000) / 1000);
765
+ timeRemaining.textContent = `${minutes}m ${seconds}s`;
766
+ } else {
767
+ timeRemaining.textContent = 'Calculating...';
768
+ }
769
+
770
+ // Update progress steps
771
+ const stepsDiv = document.getElementById('progressSteps');
772
+ const steps = [
773
+ { id: 'preparing', name: 'Preparing device', icon: 'fas fa-cog' },
774
+ { id: 'unmounting', name: 'Unmounting device', icon: 'fas fa-eject' },
775
+ { id: 'writing', name: 'Writing image', icon: 'fas fa-pen' },
776
+ { id: 'verifying', name: 'Verifying write', icon: 'fas fa-check-double' },
777
+ { id: 'ejecting', name: 'Ejecting device', icon: 'fas fa-sign-out-alt' }
778
+ ];
779
+
780
+ stepsDiv.innerHTML = steps.map(step => {
781
+ let statusClass = 'text-gray-400';
782
+ let statusIcon = 'far fa-circle';
783
+
784
+ if (step.id === progress.stage) {
785
+ statusClass = 'text-blue-600';
786
+ statusIcon = 'fas fa-spinner fa-spin';
787
+ } else if (steps.findIndex(s => s.id === step.id) < steps.findIndex(s => s.id === progress.stage)) {
788
+ statusClass = 'text-green-600';
789
+ statusIcon = 'fas fa-check-circle';
790
+ }
791
+
792
+ return `
793
+ <div class="flex items-center ${statusClass}">
794
+ <i class="${statusIcon} mr-2"></i>
795
+ <span>${step.name}</span>
796
+ </div>
797
+ `;
798
+ }).join('');
799
+ }
800
+
801
+ /**
802
+ * Cancel flashing process
803
+ */
804
+ cancelFlashing() {
805
+ const confirmed = confirm('Are you sure you want to cancel the flashing process?\n\nThis may leave your device in an unusable state.');
806
+
807
+ if (!confirmed) return;
808
+
809
+ console.log('Cancelling flash process...');
810
+
811
+ if (this.flashingInterval) {
812
+ clearInterval(this.flashingInterval);
813
+ this.flashingInterval = null;
814
+ }
815
+
816
+ // Show cancellation message
817
+ document.getElementById('progressStatus').textContent = 'Cancelled by user';
818
+ document.getElementById('progressBar').classList.add('bg-red-600');
819
+
820
+ setTimeout(() => {
821
+ this.resetApplication();
822
+ }, 2000);
823
+ }
824
+
825
+ /**
826
+ * Complete flashing process
827
+ */
828
+ completeFlashing() {
829
+ console.log('Flash process completed successfully!');
830
+
831
+ // Hide progress section and show completion
832
+ document.getElementById('progressSection').classList.add('hidden');
833
+ document.getElementById('completionSection').classList.remove('hidden');
834
+ document.getElementById('completionSection').classList.add('slide-up');
835
+
836
+ // Update completion message
837
+ const completionMessage = document.getElementById('completionMessage');
838
+ completionMessage.textContent = `Successfully flashed ${this.selectedOS.name} to ${this.selectedDevice.name}. Your SD card is ready to use!`;
839
+
840
+ // Play success sound (if available)
841
+ this.playSuccessSound();
842
+ }
843
+
844
+ /**
845
+ * Play success sound
846
+ */
847
+ playSuccessSound() {
848
+ try {
849
+ // Create a simple success tone
850
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
851
+ const oscillator = audioContext.createOscillator();
852
+ const gainNode = audioContext.createGain();
853
+
854
+ oscillator.connect(gainNode);
855
+ gainNode.connect(audioContext.destination);
856
+
857
+ oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
858
+ oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1);
859
+ gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
860
+ gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
861
+
862
+ oscillator.start(audioContext.currentTime);
863
+ oscillator.stop(audioContext.currentTime + 0.3);
864
+ } catch (error) {
865
+ console.log('Could not play success sound:', error);
866
+ }
867
+ }
868
+
869
+ /**
870
+ * Reset application to initial state
871
+ */
872
+ resetApplication() {
873
+ console.log('Resetting application...');
874
+
875
+ // Reset selections
876
+ this.selectedDevice = null;
877
+ this.selectedOS = null;
878
+ this.flashingProgress = null;
879
+
880
+ if (this.flashingInterval) {
881
+ clearInterval(this.flashingInterval);
882
+ this.flashingInterval = null;
883
+ }
884
+
885
+ // Reset UI
886
+ document.querySelectorAll('.device-card').forEach(card => {
887
+ card.classList.remove('selected');
888
+ card.querySelector('.device-selected-icon').classList.add('hidden');
889
+ });
890
+
891
+ document.querySelectorAll('.os-image-card').forEach(card => {
892
+ card.classList.remove('selected');
893
+ const icon = card.querySelector('.os-selected-icon');
894
+ if (icon) icon.classList.add('hidden');
895
+ });
896
+
897
+ // Reset custom upload
898
+ const uploadArea = document.getElementById('customImageUpload');
899
+ uploadArea.innerHTML = `
900
+ <i class="fas fa-file-upload text-3xl text-gray-400 mb-2"></i>
901
+ <h3 class="font-medium text-gray-700">Use Custom Image</h3>
902
+ <p class="text-sm text-gray-500">Upload your own .img or .zip file</p>
903
+ `;
904
+ uploadArea.classList.remove('border-green-400', 'bg-green-50');
905
+
906
+ // Reset form fields
907
+ document.getElementById('wifiSSID').value = '';
908
+ document.getElementById('wifiPassword').value = '';
909
+ document.getElementById('hostname').value = '';
910
+ document.getElementById('sshOption').value = 'disabled';
911
+ document.getElementById('customImageFile').value = '';
912
+
913
+ // Hide sections
914
+ document.getElementById('progressSection').classList.add('hidden');
915
+ document.getElementById('completionSection').classList.add('hidden');
916
+ document.getElementById('flashSummary').parentElement.classList.remove('hidden');
917
+
918
+ // Update UI
919
+ this.updateFlashSummary();
920
+ this.updateFlashButton();
921
+ }
922
+ }
923
+
924
+ // Initialize the application when DOM is loaded
925
+ document.addEventListener('DOMContentLoaded', () => {
926
+ console.log('DOM loaded, initializing PiFlash...');
927
+ new PiFlashApp();
928
+ });
929
+
930
+ // Unit tests for key functions
931
+ if (typeof module !== 'undefined' && module.exports) {
932
+ module.exports = PiFlashApp;
933
+ }