File size: 25,736 Bytes
70b7901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// --- Utilities ---
const $ = (sel, el = document) => el.querySelector(sel);
const $$ = (sel, el = document) => Array.from(el.querySelectorAll(sel));

function getTodayStr() {
  return new Date().toISOString().split('T')[0];
}

function formatDate(dateStr) {
  const d = new Date(dateStr + 'T00:00:00');
  return d.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

function formatDateTime() {
  return new Date().toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'short' });
}

// --- Storage ---
const STORAGE_KEY = 'poolChecklist_v1';
function loadData() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; } catch { return {}; }
}
function saveData() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state.data));
}

// --- Schedule Data ---
const SCHEDULE = [
  {
    key: 'morning',
    label: 'Morning Schedule',
    icon: 'sun',
    periods: [
      { time: '5:00AM - 5:30AM', tasks: ['Open Umbrella','Check Filters','Check Pumps','Check Water Level','Check Water Temperature','Check Water Clarity (Clear or Cloudy)','Open sprinkler for landscape'] },
      { time: '5:30AM - 6:00AM', tasks: ['Test Water pH Level (ideal 7.4 - 7.6)','Test Chlorine level (ideal 1-3 ppm)','Add Chlorine (if needed)','Add Acid (if needed)','Add algaecide (if needed)'] },
      { time: '6:00AM - 8:00AM', tasks: ['Leaf Skimming (surface)','Check, clean & empty skimmer baskets','Vacuum Pool','Clean/scrub pool walls & floors','Unclog and clean foot baths'] },
      { time: '8:00AM - 9:00AM', tasks: ['Backwash filter (if needed)','Polish pool ladders','Scrub pool walls & decks'] },
      { time: '9:00AM - 10:30AM', tasks: ['Doors & door locks','Lavatory Sinks','Faucets & fittings','Shower & fittings','Bidets','Mirrors','Toilet bowls & fittings','Walls','Floors','Light, Switches & Outlets','Drains','Exhaust Fans','Garbage Cans'] },
      { time: '10:30AM - 12:00NN', tasks: ['Gardening Works Outside Pool'] },
      { time: '1:00PM - 2:00PM', tasks: ['Final leaf skimming','Endorse left work or issue upon duty'] }
    ]
  },
  {
    key: 'afternoon',
    label: 'Afternoon Schedule',
    icon: 'moon',
    periods: [
      { time: '1:00PM - 2:00PM', tasks: ['Inspect pumps','Inspect filters','Check overall cleanliness of pool and surroundings'] },
      { time: '2:00PM - 6:00PM', tasks: ['Leaf Skimming (as needed)','Inspect and clean skimmer baskets if debris is heavy','Spot Cleaning of pool decks and walls','Check furniture alignments','Ensure umbrellas remain folded when not in use','Observe water clarity and circulation'] },
      { time: '6:00PM - 7:30PM', tasks: ['Clean toilet bowls & fittings','Clean lavatory sinks','Wipe mirrors','Spot clean floor and drains','Check exhaust fans','Clean garbage bins'] },
      { time: '7:30PM - 8:00PM', tasks: ['Final light leaf skimming','Visual Clarity and water level check'] },
      { time: '8:00PM - 9:00PM', tasks: ['Final pump and filter inspection','Water level and clarity check','Overall cleanliness inspection (pool, CR, Common areas)','Secure equipment and area'] },
      { time: '9:00PM - 10:00PM', tasks: ['Watering of landscape','Fold all umbrella'] }
    ]
  }
];

const TOTAL_TASKS = SCHEDULE.reduce((sum, shift) => sum + shift.periods.reduce((s, p) => s + p.tasks.length, 0), 0);

// --- State ---
const state = {
  view: 'dashboard',
  selectedDate: getTodayStr(),
  data: loadData(),
  attendantName: localStorage.getItem('poolAttendantName') || ''
};

// --- Init ---
function init() {
  navigate('dashboard');
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeReport(); });
}

// --- Navigation ---
function updateNav() {
  $$('.nav-btn').forEach(btn => {
    const isActive = btn.id === `nav-${state.view}`;
    btn.className = `nav-btn px-4 py-1.5 rounded-md text-sm font-medium transition ${isActive ? 'bg-white text-cyan-700 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`;
  });
}

function navigate(view, date = null) {
  if (date) state.selectedDate = date;
  state.view = view;
  updateNav();
  if (view === 'dashboard') renderDashboard();
  else if (view === 'checklist') renderChecklist();
  lucide.createIcons();
}

function setMainContent(html) {
  $('#app').innerHTML = `<div class="animate-fade-in">${html}</div>`;
}

// --- Stats ---
function getDayData(date) {
  return state.data[date] || {};
}

function calculateStats(date) {
  const day = getDayData(date);
  let completed = 0;
  let withPhotos = 0;
  SCHEDULE.forEach(shift => {
    shift.periods.forEach((period, pi) => {
      period.tasks.forEach((_, ti) => {
        const tid = `${shift.key}-${pi}-${ti}`;
        const t = day[tid];
        if (t?.completed) completed++;
        if (t?.photo) withPhotos++;
      });
    });
  });
  return { total: TOTAL_TASKS, completed, pending: TOTAL_TASKS - completed, withPhotos, percent: Math.round((completed / TOTAL_TASKS) * 100) };
}

// --- Dashboard ---
function renderDashboard() {
  const today = getTodayStr();
  const todayStats = calculateStats(today);
  const dates = Object.keys(state.data).sort((a, b) => new Date(b + 'T00:00:00') - new Date(a + 'T00:00:00'));

  let historyHtml = dates.slice(0, 14).map(date => {
    const s = calculateStats(date);
    return `
      <div onclick="goToDate('${date}')" class="group flex items-center justify-between p-4 hover:bg-slate-50 cursor-pointer transition rounded-xl border border-transparent hover:border-slate-200">
        <div class="flex items-center gap-4">
          <div class="w-10 h-10 rounded-full flex items-center justify-center ${s.percent === 100 ? 'bg-emerald-100 text-emerald-600' : 'bg-cyan-50 text-cyan-600'} font-bold text-sm">
            ${s.percent}%
          </div>
          <div>
            <div class="font-semibold text-slate-800">${formatDate(date)}</div>
            <div class="text-xs text-slate-500">${s.completed}/${s.total} tasks • ${s.withPhotos} photos</div>
          </div>
        </div>
        <i data-lucide="chevron-right" class="text-slate-300 group-hover:text-slate-500 w-5 h-5"></i>
      </div>
    `;
  }).join('');

  if (dates.length === 0) {
    historyHtml = `<div class="p-8 text-center text-slate-400 text-sm">No records yet. Open the checklist to start tracking.</div>`;
  }

  const html = `
    <div class="p-4 md:p-8 max-w-5xl mx-auto space-y-8">
      <div class="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 class="text-3xl font-bold text-slate-900">Dashboard</h1>
          <p class="text-slate-500 mt-1">Monitor daily pool operations at a glance.</p>
        </div>
        <button onclick="navigate('checklist')" class="inline-flex items-center justify-center gap-2 bg-cyan-600 hover:bg-cyan-700 text-white px-6 py-3 rounded-xl font-semibold shadow-lg shadow-cyan-200 transition transform hover:scale-105">
          <i data-lucide="clipboard-check"></i> Today's Checklist
        </button>
      </div>

      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
          <div class="flex items-center justify-between mb-4">
            <span class="text-xs font-bold tracking-wider text-cyan-600 uppercase bg-cyan-50 px-2 py-1 rounded-md">Today</span>
            <div class="p-2 bg-cyan-50 text-cyan-600 rounded-lg"><i data-lucide="activity"></i></div>
          </div>
          <div class="text-4xl font-extrabold text-slate-800">${todayStats.percent}<span class="text-lg text-slate-400 font-medium">%</span></div>
          <div class="text-sm text-slate-500 mt-1">Completion Rate</div>
          <div class="mt-4 h-2 w-full bg-slate-100 rounded-full overflow-hidden">
            <div class="h-full bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full transition-all" style="width:${todayStats.percent}%"></div>
          </div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
          <div class="flex items-center justify-between mb-4">
            <div class="p-2 bg-emerald-50 text-emerald-600 rounded-lg"><i data-lucide="check-circle-2"></i></div>
          </div>
          <div class="text-4xl font-extrabold text-slate-800">${todayStats.completed}</div>
          <div class="text-sm text-slate-500 mt-1">Tasks Done</div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
          <div class="flex items-center justify-between mb-4">
            <div class="p-2 bg-amber-50 text-amber-600 rounded-lg"><i data-lucide="circle-dot"></i></div>
          </div>
          <div class="text-4xl font-extrabold text-slate-800">${todayStats.pending}</div>
          <div class="text-sm text-slate-500 mt-1">Tasks Pending</div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
          <div class="flex items-center justify-between mb-4">
            <div class="p-2 bg-indigo-50 text-indigo-600 rounded-lg"><i data-lucide="camera"></i></div>
          </div>
          <div class="text-4xl font-extrabold text-slate-800">${todayStats.withPhotos}</div>
          <div class="text-sm text-slate-500 mt-1">Photos Uploaded</div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-slate-100">
          <div class="p-6 border-b border-slate-100 flex items-center justify-between">
            <h2 class="text-lg font-bold text-slate-800 flex items-center gap-2"><i data-lucide="history" class="w-5 h-5 text-cyan-600"></i> Recent History</h2>
          </div>
          <div class="p-4 space-y-2 max-h-[600px] overflow-y-auto">
            ${historyHtml}
          </div>
        </div>

        <div class="bg-gradient-to-br from-cyan-600 to-blue-700 rounded-2xl shadow-lg text-white p-6 flex flex-col justify-between">
          <div>
            <h2 class="text-xl font-bold mb-2">Daily Reminder</h2>
            <p class="text-cyan-100 text-sm leading-relaxed">Maintain water pH at 7.4 - 7.6 and chlorine at 1-3 ppm. Fold umbrellas by 10:00PM and secure all equipment.</p>
          </div>
          <div class="mt-6">
            <div class="text-xs font-semibold uppercase tracking-wider text-cyan-200 mb-2">Scheduled Tasks</div>
            <div class="text-5xl font-extrabold">${TOTAL_TASKS}</div>
            <div class="text-sm text-cyan-100 mt-1">across morning & afternoon shifts</div>
          </div>
        </div>
      </div>
    </div>
  `;
  setMainContent(html);
  lucide.createIcons();
}

// --- Checklist ---
function renderChecklist() {
  const dayData = getDayData(state.selectedDate);
  const stats = calculateStats(state.selectedDate);

  const shiftHtml = SCHEDULE.map(shift => {
    const periodHtml = shift.periods.map((period, pi) => {
      const tasksHtml = period.tasks.map((task, ti) => {
        const tid = `${shift.key}-${pi}-${ti}`;
        const tdata = dayData[tid] || {};
        const isDone = !!tdata.completed;
        const photo = tdata.photo || null;
        const notes = tdata.notes || '';

        return `
          <div class="task-row bg-white border border-slate-200 rounded-xl p-4 transition hover:shadow-md hover:border-cyan-200 ${isDone ? 'bg-slate-50/50' : ''}">
            <div class="flex items-start gap-4">
              <div class="pt-0.5">
                <input type="checkbox" 
                  class="task-checkbox w-6 h-6 rounded-lg border-2 border-slate-300 text-cyan-600 focus:ring-cyan-500 cursor-pointer transition" 
                  data-tid="${tid}" 
                  ${isDone ? 'checked' : ''}>
              </div>
              <div class="flex-1 min-w-0">
                <div class="task-text font-medium text-slate-800 text-sm md:text-base leading-snug ${isDone ? 'line-through text-slate-400' : ''}">${task}</div>
                
                <div class="mt-3 flex flex-wrap items-center gap-3">
                  <button type="button" class="photo-trigger inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition ${photo ? 'bg-indigo-50 border-indigo-200 text-indigo-700' : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-50'}">
                    <i data-lucide="${photo ? 'image' : 'camera'}"></i>
                    ${photo ? 'Change Photo' : 'Add Photo'}
                  </button>
                  <input type="file" class="photo-input hidden" data-tid="${tid}" accept="image/*">
                  
                  ${photo ? `
                    <div class="relative group/prev">
                      <img src="${photo}" class="h-10 w-10 rounded-lg object-cover border border-slate-200 cursor-pointer photo-preview" data-tid="${tid}">
                      <button class="remove-photo absolute -top-1.5 -right-1.5 bg-red-500 text-white rounded-full p-0.5 shadow-sm opacity-0 group-hover/prev:opacity-100 transition" data-tid="${tid}">
                        <i data-lucide="x" class="w-3 h-3"></i>
                      </button>
                    </div>
                  ` : ''}
                </div>
                
                <div class="mt-3">
                  <input type="text" placeholder="Add notes / issues..." 
                    class="task-notes w-full bg-transparent text-sm text-slate-600 placeholder-slate-400 border-b border-slate-200 focus:border-cyan-500 focus:outline-none pb-1 transition"
                    data-tid="${tid}" value="${notes}">
                </div>
              </div>
            </div>
          </div>
        `;
      }).join('');

      return `
        <div class="period-block mb-6">
          <button type="button" class="period-toggle w-full flex items-center justify-between p-3 bg-slate-100 hover:bg-slate-200 rounded-xl transition text-left mb-3" onclick="this.nextElementSibling.classList.toggle('hidden'); this.querySelector('.chevron-icon').classList.toggle('rotate-180')">
            <span class="font-bold text-slate-700 text-sm md:text-base flex items-center gap-2">
              <i data-lucide="clock" class="w-4 h-4 text-cyan-600"></i> ${period.time}
            </span>
            <i data-lucide="chevron-down" class="chevron-icon w-4 h-4 text-slate-500 transition-transform duration-200"></i>
          </button>
          <div class="space-y-3 pl-1">
            ${tasksHtml}
          </div>
        </div>
      `;
    }).join('');

    return `
      <div class="mb-10">
        <div class="flex items-center gap-3 mb-6">
          <div class="p-2 ${shift.key === 'morning' ? 'bg-amber-100 text-amber-600' : 'bg-indigo-100 text-indigo-600'} rounded-lg">
            <i data-lucide="${shift.icon}"></i>
          </div>
          <h2 class="text-xl font-bold text-slate-800">${shift.label}</h2>
        </div>
        ${periodHtml}
      </div>
    `;
  }).join('');

  const html = `
    <div class="p-4 md:p-8 max-w-4xl mx-auto space-y-6">
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 no-print">
        <div>
          <h1 class="text-2xl md:text-3xl font-bold text-slate-900">Daily Checklist</h1>
          <p class="text-slate-500 text-sm mt-1">Complete tasks, attach photos, and add notes for verification.</p>
        </div>
        <div class="flex items-center gap-3">
          <input type="date" id="date-picker" value="${state.selectedDate}" 
            class="bg-white border border-slate-200 text-slate-700 text-sm rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-cyan-500 shadow-sm">
        </div>
      </div>

      <div class="sticky top-16 z-30 bg-white/90 backdrop-blur border-y border-slate-200 -mx-4 md:-mx-8 px-4 md:px-8 py-3 no-print">
        <div class="max-w-4xl mx-auto flex items-center gap-4">
          <div class="flex-1 h-2.5 bg-slate-100 rounded-full overflow-hidden">
            <div class="h-full bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full transition-all" style="width:${stats.percent}%"></div>
          </div>
          <span class="text-sm font-bold text-slate-700 w-12 text-right">${stats.percent}%</span>
        </div>
      </div>

      <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-4 md:p-6 no-print">
        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Attendant Name</label>
        <input type="text" id="attendant-name" value="${state.attendantName}" placeholder="Enter attendant name..."
          class="w-full md:w-1/2 bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-500 transition">
      </div>

      <div class="no-print flex flex-wrap gap-3">
        <button onclick="generateReport('${state.selectedDate}')" class="inline-flex items-center gap-2 bg-slate-800 hover:bg-slate-900 text-white px-5 py-2.5 rounded-xl text-sm font-semibold transition shadow-md">
          <i data-lucide="file-text"></i> Generate Report
        </button>
        <button onclick="navigate('dashboard')" class="inline-flex items-center gap-2 bg-white hover:bg-slate-50 text-slate-700 border border-slate-200 px-5 py-2.5 rounded-xl text-sm font-semibold transition">
          <i data-lucide="arrow-left"></i> Back to Dashboard
        </button>
      </div>

      <div class="pb-20">
        ${shiftHtml}
      </div>
    </div>
  `;
  setMainContent(html);
  setupChecklistListeners();
  lucide.createIcons();
}

function setupChecklistListeners() {
  const app = $('#app');

  const dp = $('#date-picker', app);
  if (dp) {
    dp.addEventListener('change', (e) => {
      state.selectedDate = e.target.value;
      renderChecklist();
      showToast(`Switched to ${formatDate(state.selectedDate)}`);
    });
  }

  const an = $('#attendant-name', app);
  if (an) {
    an.addEventListener('input', (e) => {
      state.attendantName = e.target.value;
      localStorage.setItem('poolAttendantName', state.attendantName);
    });
  }

  $$('.task-checkbox', app).forEach(cb => {
    cb.addEventListener('change', (e) => {
      const tid = e.target.dataset.tid;
      if (!state.data[state.selectedDate]) state.data[state.selectedDate] = {};
      if (!state.data[state.selectedDate][tid]) state.data[state.selectedDate][tid] = {};
      state.data[state.selectedDate][tid].completed = e.target.checked;
      state.data[state.selectedDate][tid].updatedAt = new Date().toISOString();
      saveData();

      const row = e.target.closest('.task-row');
      const text = row.querySelector('.task-text');
      if (e.target.checked) {
        text.classList.add('line-through', 'text-slate-400');
        row.classList.add('bg-slate-50/50');
      } else {
        text.classList.remove('line-through', 'text-slate-400');
        row.classList.remove('bg-slate-50/50');
      }
      showToast(e.target.checked ? 'Task completed' : 'Task unchecked');
    });
  });

  $$('.photo-trigger', app).forEach(btn => {
    btn.addEventListener('click', () => {
      const row = btn.closest('.task-row');
      const input = row.querySelector('.photo-input');
      input.click();
    });
  });

  $$('.photo-input', app).forEach(input => {
    input.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const tid = input.dataset.tid;
      resizeImage(file, 800, (base64) => {
        if (!state.data[state.selectedDate]) state.data[state.selectedDate] = {};
        if (!state.data[state.selectedDate][tid]) state.data[state.selectedDate][tid] = {};
        state.data[state.selectedDate][tid].photo = base64;
        state.data[state.selectedDate][tid].updatedAt = new Date().toISOString();
        saveData();
        renderChecklist();
        showToast('Photo uploaded');
      });
    });
  });

  $$('.remove-photo', app).forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const tid = btn.dataset.tid;
      if (state.data[state.selectedDate]?.[tid]) {
        delete state.data[state.selectedDate][tid].photo;
        if (!state.data[state.selectedDate][tid].completed && !state.data[state.selectedDate][tid].notes) {
          delete state.data[state.selectedDate][tid];
        }
        saveData();
        renderChecklist();
        showToast('Photo removed');
      }
    });
  });

  $$('.task-notes', app).forEach(input => {
    let timeout;
    input.addEventListener('input', (e) => {
      const tid = e.target.dataset.tid;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        if (!state.data[state.selectedDate]) state.data[state.selectedDate] = {};
        if (!state.data[state.selectedDate][tid]) state.data[state.selectedDate][tid] = {};
        state.data[state.selectedDate][tid].notes = e.target.value;
        saveData();
      }, 600);
    });
  });
}

// --- Image Resizing ---
function resizeImage(file, maxWidth, callback) {
  const reader = new FileReader();
  reader.onload = (evt) => {
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const scale = Math.min(1, maxWidth / img.width);
      canvas.width = img.width * scale;
      canvas.height = img.height * scale;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      callback(canvas.toDataURL('image/jpeg', 0.8));
    };
    img.src = evt.target.result;
  };
  reader.readAsDataURL(file);
}

// --- Report ---
function generateReport(date) {
  const dayData = getDayData(date);
  const stats = calculateStats(date);
  const generatedOn = formatDateTime();

  const shiftsHtml = SCHEDULE.map(shift => {
    const periodsHtml = shift.periods.map((period, pi) => {
      const tasksHtml = period.tasks.map((task, ti) => {
        const tid = `${shift.key}-${pi}-${ti}`;
        const t = dayData[tid] || {};
        const done = !!t.completed;
        return `
          <div class="flex items-start gap-3 py-3 border-b border-slate-100 last:border-0">
            <div class="mt-0.5 shrink-0">
              ${done 
                ? '<div class="w-5 h-5 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center"><i data-lucide="check" class="w-3 h-3"></i></div>' 
                : '<div class="w-5 h-5 rounded-full border-2 border-slate-300"></div>'}
            </div>
            <div class="flex-1 min-w-0">
              <div class="text-sm ${done ? 'text-slate-800 font-medium' : 'text-slate-500'}">${task}</div>
              ${t.notes ? `<div class="text-xs text-amber-700 mt-1.5 bg-amber-50 inline-block px-2 py-0.5 rounded border border-amber-100">Note: ${t.notes}</div>` : ''}
              ${t.photo ? `<img src="${t.photo}" class="mt-2 h-28 w-auto rounded-lg border border-slate-200 object-cover">` : ''}
            </div>
          </div>
        `;
      }).join('');

      return `
        <div class="mb-5">
          <div class="bg-slate-100 text-slate-700 font-bold text-xs uppercase tracking-wider px-3 py-2 rounded-lg mb-2">${period.time}</div>
          <div class="pl-1">
            ${tasksHtml}
          </div>
        </div>
      `;
    }).join('');

    return `
      <div class="mb-8">
        <h3 class="text-lg font-bold text-cyan-800 mb-4 flex items-center gap-2 border-b border-cyan-100 pb-2">
          <i data-lucide="${shift.icon}"></i> ${shift.label}
        </h3>
        ${periodsHtml}
      </div>
    `;
  }).join('');

  const html = `
    <div class="max-w-[700px] mx-auto">
      <div class="text-center mb-8 border-b-2 border-cyan-600 pb-6">
        <h1 class="text-2xl md:text-3xl font-extrabold text-slate-900 uppercase tracking-tight">Pool Attendant Checklist Report</h1>
        <div class="mt-2 text-cyan-700 font-semibold text-lg">${formatDate(date)}</div>
        <div class="mt-4 flex flex-wrap justify-center gap-6 text-sm text-slate-600">
          <div class="flex items-center gap-1.5"><i data-lucide="user" class="w-4 h-4"></i> ${state.attendantName || 'Unassigned'}</div>
          <div class="flex items-center gap-1.5"><i data-lucide="check-circle" class="w-4 h-4 text-emerald-600"></i> ${stats.completed} / ${stats.total} Completed</div>
        </div>
      </div>
      
      ${shiftsHtml}
      
      <div class="mt-10 pt-6 border-t border-slate-200 text-xs text-slate-500 flex flex-col md:flex-row justify-between gap-2">
        <span>Report generated on ${generatedOn}</span>
        <span>PoolCheck Pro System</span>
      </div>
      
      <div class="mt-16 grid grid-cols-2 gap-12 no-print">
        <div>
          <div class="border-b border-slate-400 mb-2 h-6"></div>
          <div class="text-xs font-bold text-slate-700 uppercase tracking-wide">Prepared By</div>
        </div>
        <div>
          <div class="border-b border-slate-400 mb-2 h-6"></div>
          <div class="text-xs font-bold text-slate-700 uppercase tracking-wide">Supervisor Sign-off</div>
        </div>
      </div>
    </div>
  `;

  $('#report-content').innerHTML = html;
  $('#report-modal').classList.remove('hidden');
  lucide.createIcons();
}

function closeReport() {
  $('#report-modal').classList.add('hidden');
}

// --- Toast ---
let toastTimer;
function showToast(msg) {
  const toast = $('#toast');
  $('#toast-msg').textContent = msg;
  toast.classList.remove('translate-y-20', 'opacity-0');
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => {
    toast.classList.add('translate-y-20', 'opacity-0');
  }, 2200);
}

// --- Expose Globals ---
window.navigate = navigate;
window.generateReport = generateReport;
window.closeReport = closeReport;
window.goToDate = (date) => navigate('checklist', date);

// Start
init();