Spaces:
Running

File size: 32,081 Bytes
5518291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c13ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
// AgriCensus Pro - Main JavaScript

// Global State
const state = {
    currentUser: null,
    currentSurvey: null,
    currentStep: 1,
    totalSteps: 5,
    surveys: [],
    enumerators: [],
    households: [],
    loginType: 'enumerator'
};

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    initializeTheme();
    loadSampleData();
    updateUI();
    feather.replace();
});

// Theme Management
function initializeTheme() {
    const savedTheme = localStorage.getItem('theme') || 'light';
    if (savedTheme === 'dark') {
        document.documentElement.classList.add('dark');
    }
    
    document.getElementById('themeToggle').addEventListener('click', toggleTheme);
}

function toggleTheme() {
    const isDark = document.documentElement.classList.toggle('dark');
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
    feather.replace();
}

// Sample Data for Demo
function loadSampleData() {
    // Sample enumerators
    state.enumerators = [
        { id: 'ENUM001', name: 'Ram Bahadur', email: 'ram@example.com', college: 'Agriculture University', status: 'active', collegeIdVerified: true },
        { id: 'ENUM002', name: 'Sita Devi', email: 'sita@example.com', college: 'Tribhuvan University', status: 'pending', collegeIdVerified: false },
        { id: 'ENUM003', name: 'Hari Prasad', email: 'hari@example.com', college: 'Himalayan College', status: 'active', collegeIdVerified: true }
    ];
    
    // Sample surveys
    state.surveys = [
        {
            id: 'SURV001',
            title: 'Kathmandu Valley Baseline Survey',
            location: 'Kathmandu District, Ward 5',
            status: 'draft',
            progress: 60,
            lastModified: '2024-01-15',
            enumeratorId: 'ENUM001',
            data: {}
        },
        {
            id: 'SURV002',
            title: 'Pokhara Agricultural Census',
            location: 'Kaski District, Ward 3',
            status: 'submitted',
            progress: 100,
            lastModified: '2024-01-10',
            enumeratorId: 'ENUM001',
            data: {}
        },
        {
            id: 'SURV003',
            title: 'Terai Region Survey',
            location: 'Dhanusha District, Ward 7',
            status: 'draft',
            progress: 25,
            lastModified: '2024-01-14',
            enumeratorId: 'ENUM002',
            data: {}
        }
    ];
}

// UI Updates
function updateUI() {
    const authButtons = document.getElementById('authButtons');
    const userMenu = document.getElementById('userMenu');
    const heroSection = document.getElementById('heroSection');
    const dashboardSection = document.getElementById('dashboardSection');
    const adminSection = document.getElementById('adminSection');
    
    if (state.currentUser) {
        authButtons.classList.add('hidden');
        userMenu.classList.remove('hidden');
        document.getElementById('userName').textContent = state.currentUser.name;
        heroSection.classList.add('hidden');
        
        if (state.currentUser.role === 'admin') {
            adminSection.classList.remove('hidden');
            dashboardSection.classList.add('hidden');
            renderAdminPanel();
        } else {
            dashboardSection.classList.remove('hidden');
            adminSection.classList.add('hidden');
            renderDashboard();
        }
    } else {
        authButtons.classList.remove('hidden');
        userMenu.classList.add('hidden');
        heroSection.classList.remove('hidden');
        dashboardSection.classList.add('hidden');
        adminSection.classList.add('hidden');
    }
}

// Login System
function showLoginModal() {
    document.getElementById('loginModal').classList.remove('hidden');
    document.getElementById('loginModal').classList.add('modal-enter');
}

function closeLoginModal() {
    document.getElementById('loginModal').classList.add('hidden');
}

function switchLoginType(type) {
    state.loginType = type;
    const enumBtn = document.getElementById('enumLoginBtn');
    const adminBtn = document.getElementById('adminLoginBtn');
    
    if (type === 'enumerator') {
        enumBtn.classList.add('bg-primary-500', 'text-white');
        enumBtn.classList.remove('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
        adminBtn.classList.remove('bg-primary-500', 'text-white');
        adminBtn.classList.add('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
    } else {
        adminBtn.classList.add('bg-primary-500', 'text-white');
        adminBtn.classList.remove('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
        enumBtn.classList.remove('bg-primary-500', 'text-white');
        enumBtn.classList.add('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
    }
}

function handleLogin(e) {
    e.preventDefault();
    const email = document.getElementById('loginEmail').value;
    const password = document.getElementById('loginPassword').value;
    
    // Demo authentication
    if (state.loginType === 'admin' && email === 'admin' && password === 'admin') {
        state.currentUser = { id: 'ADMIN001', name: 'System Administrator', role: 'admin', email: 'admin@agricensus.pro' };
        showToast('Welcome, Administrator!');
        closeLoginModal();
        updateUI();
    } else if (state.loginType === 'enumerator') {
        const enumerator = state.enumerators.find(e => e.email === email && password === 'password');
        if (enumerator && enumerator.status === 'active') {
            state.currentUser = { ...enumerator, role: 'enumerator' };
            showToast(`Welcome, ${enumerator.name}!`);
            closeLoginModal();
            updateUI();
        } else if (enumerator && enumerator.status === 'pending') {
            showToast('Your account is pending verification. Please wait for admin approval.');
        } else {
            showToast('Invalid credentials. Try email: ram@example.com, password: password');
        }
    }
}

function logout() {
    state.currentUser = null;
    state.currentSurvey = null;
    updateUI();
    showToast('Logged out successfully');
}

// Enumerator Registration
function showEnumeratorRegister() {
    document.getElementById('registerModal').classList.remove('hidden');
}

function closeRegisterModal() {
    document.getElementById('registerModal').classList.add('hidden');
}
function previewIdCard(input) {
    const preview = document.getElementById('idCardPreview');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.classList.remove('hidden');
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function handleRegister(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    // Validate college ID photo
    const idPhoto = document.getElementById('idCardPhoto').files[0];
    if (!idPhoto) {
        showToast('Please upload your College ID Card photo');
        return;
    }
    
    // Create new enumerator
    const newEnumerator = {
        id: 'ENUM' + String(state.enumerators.length + 1).padStart(3, '0'),
        name: formData.get('fullName'),
        email: formData.get('email'),
        phone: formData.get('phone'),
        college: formData.get('college'),
        collegeId: formData.get('collegeId'),
        status: 'pending',
        collegeIdVerified: false
    };
    
    state.enumerators.push(newEnumerator);
    showToast('Registration submitted successfully! Your account is pending verification.');
    closeRegisterModal();
    e.target.reset();
    document.getElementById('idCardPreview').classList.add('hidden');
}

// Survey Management
function renderDashboard() {
    const grid = document.getElementById('surveyGrid');
    const mySurveys = state.surveys.filter(s => s.enumeratorId === state.currentUser.id);
    
    grid.innerHTML = mySurveys.map(survey => `
        <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow">
            <div class="p-6">
                <div class="flex justify-between items-start mb-4">
                    <span class="px-3 py-1 rounded-full text-xs font-semibold ${getStatusClass(survey.status)}">
                        ${survey.status.toUpperCase()}
                    </span>
                    <span class="text-sm text-gray-500 dark:text-gray-400">${survey.lastModified}</span>
                </div>
                <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-2">${survey.title}</h3>
                <p class="text-gray-600 dark:text-gray-400 text-sm mb-4">${survey.location}</p>
                
                <div class="mb-4">
                    <div class="flex justify-between text-sm mb-1">
                        <span class="text-gray-600 dark:text-gray-400">Progress</span>
                        <span class="text-gray-900 dark:text-white font-semibold">${survey.progress}%</span>
                    </div>
                    <div class="h-2 bg-gray-200 dark:bg-gray-700 rounded-full">
                        <div class="h-full bg-primary-500 rounded-full transition-all duration-500" style="width: ${survey.progress}%"></div>
                    </div>
                </div>
                
                <div class="flex gap-2">
                    <button onclick="openSurvey('${survey.id}')" class="flex-1 bg-primary-500 hover:bg-primary-600 text-white py-2 rounded-lg font-medium transition-colors text-sm">
                        ${survey.status === 'draft' ? 'Continue' : 'View'}
                    </button>
                    ${survey.status === 'draft' ? `
                        <button onclick="deleteSurvey('${survey.id}')" class="px-3 py-2 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors">
                            <i data-feather="trash-2" class="w-4 h-4"></i>
                        </button>
                    ` : ''}
                </div>
            </div>
        </div>
    `).join('');
    
    feather.replace();
}

function getStatusClass(status) {
    const classes = {
        draft: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
        submitted: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
        verified: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
        rejected: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
    };
    return classes[status] || classes.draft;
}

function createNewSurvey() {
    state.currentSurvey = {
        id: 'SURV' + Date.now(),
        title: 'New Survey ' + new Date().toLocaleDateString(),
        status: 'draft',
        progress: 0,
        data: {},
        createdAt: new Date().toISOString()
    };
    state.currentStep = 1;
    state.households = [];
    openSurveyModal();
    updateStepIndicators();
}

function openSurvey(id) {
    const survey = state.surveys.find(s => s.id === id);
    if (survey) {
        state.currentSurvey = {...survey};
        state.currentStep = 1;
        state.households = survey.data.households || [];
        openSurveyModal();
        populateSurveyData();
        updateStepIndicators();
    }
}

function openSurveyModal() {
    document.getElementById('surveyModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    feather.replace();
}

function closeSurveyModal() {
    document.getElementById('surveyModal').classList.add('hidden');
    document.body.style.overflow = '';
    state.currentSurvey = null;
    state.currentStep = 1;
}

function populateSurveyData() {
    if (!state.currentSurvey || !state.currentSurvey.data) return;
    
    const data = state.currentSurvey.data;
    const form = document.getElementById('surveyForm');
    
    // Populate form fields
    Object.keys(data).forEach(key => {
        const field = form.querySelector(`[name="${key}"]`);
        if (field) {
            field.value = data[key];
        }
    });
    
    // Restore households
    if (data.households && data.households.length > 0) {
        state.households = data.households;
        renderHouseholds();
    }
}

// Step Navigation
function nextStep() {
    if (validateCurrentStep()) {
        saveCurrentStepData();
        if (state.currentStep < state.totalSteps) {
            state.currentStep++;
            showStep(state.currentStep);
            updateStepIndicators();
        }
    }
}

function prevStep() {
    if (state.currentStep > 1) {
        saveCurrentStepData();
        state.currentStep--;
        showStep(state.currentStep);
        updateStepIndicators();
    }
}

function showStep(step) {
    // Hide all steps
    document.querySelectorAll('.survey-step').forEach(el => el.classList.add('hidden'));
    // Show current step
    document.getElementById(`step${step}`).classList.remove('hidden');
    
    // Update buttons
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const submitBtn = document.getElementById('submitBtn');
    
    if (step === 1) {
        prevBtn.classList.add('hidden');
    } else {
        prevBtn.classList.remove('hidden');
    }
    
    if (step === state.totalSteps) {
        nextBtn.classList.add('hidden');
        submitBtn.classList.remove('hidden');
    } else {
        nextBtn.classList.remove('hidden');
        submitBtn.classList.add('hidden');
    }
    
    // Render households if on step 5
    if (step === 5) {
        renderHouseholds();
    }
    
    feather.replace();
}

function updateStepIndicators() {
    for (let i = 1; i <= state.totalSteps; i++) {
        const indicator = document.getElementById(`step${i}Indicator`);
        const progress = document.getElementById(`progress${i}`);
        
        if (i < state.currentStep) {
            // Completed
            indicator.className = 'w-8 h-8 rounded-full bg-green-500 text-white flex items-center justify-center';
            indicator.innerHTML = '<i data-feather="check" class="w-4 h-4"></i>';
            if (progress) progress.style.width = '100%';
        } else if (i === state.currentStep) {
            // Current
            indicator.className = 'w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center';
            indicator.innerHTML = i;
            if (progress) progress.style.width = '50%';
        } else {
            // Not started
            indicator.className = 'w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 flex items-center justify-center';
            indicator.innerHTML = i;
            if (progress) progress.style.width = '0%';
        }
    }
    feather.replace();
}

function validateCurrentStep() {
    const currentStepEl = document.getElementById(`step${state.currentStep}`);
    const requiredFields = currentStepEl.querySelectorAll('[required]');
    let valid = true;
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            field.classList.add('ring-2', 'ring-red-500');
            valid = false;
            setTimeout(() => field.classList.remove('ring-2', 'ring-red-500'), 3000);
        }
    });
    
    if (!valid) {
        showToast('Please fill all required fields');
    }
    
    return valid;
}

function saveCurrentStepData() {
    if (!state.currentSurvey) return;
    
    const form = document.getElementById('surveyForm');
    const formData = new FormData(form);
    const data = {};
    
    // Get all form fields
    form.querySelectorAll('input, select, textarea').forEach(field => {
        if (field.name) {
            if (field.type === 'checkbox') {
                data[field.name] = field.checked;
            } else if (field.type === 'radio') {
                if (field.checked) {
                    data[field.name] = field.value;
                }
            } else {
                data[field.name] = field.value;
            }
        }
    });
    
    // Add households data
    data.households = state.households;
    
    state.currentSurvey.data = data;
    
    // Update progress
    state.currentSurvey.progress = Math.round((state.currentStep / state.totalSteps) * 100);
}

function saveDraft() {
    saveCurrentStepData();
    
    if (state.currentSurvey) {
        const existingIndex = state.surveys.findIndex(s => s.id === state.currentSurvey.id);
        if (existingIndex >= 0) {
            state.surveys[existingIndex] = {...state.currentSurvey, lastModified: new Date().toISOString().split('T')[0]};
        } else {
            state.surveys.push({...state.currentSurvey, lastModified: new Date().toISOString().split('T')[0]});
        }
        
        showToast('Draft saved successfully');
        renderDashboard();
    }
}

// Household Management
function addHousehold() {
    const household = {
        id: 'HH' + Date.now(),
        number: state.households.length + 1,
        name: '',
        data: {}
    };
    state.households.push(household);
    renderHouseholds();
}

function removeHousehold(id) {
    state.households = state.households.filter(h => h.id !== id);
    // Renumber
    state.households.forEach((h, i) => h.number = i + 1);
    renderHouseholds();
}

function renderHouseholds() {
    const container = document.getElementById('householdsContainer');
    if (!container) return;
    
    if (state.households.length === 0) {
        container.innerHTML = `
            <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                <i data-feather="home" class="w-12 h-12 mx-auto mb-4 opacity-50"></i>
                <p>No households added yet. Click "Add New Household" to start.</p>
            </div>
        `;
    } else {
        container.innerHTML = state.households.map((hh, index) => `
            <div class="bg-white dark:bg-gray-700 rounded-xl p-6 border border-gray-200 dark:border-gray-600">
                <div class="flex justify-between items-center mb-4">
                    <h6 class="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                        <span class="bg-primary-500 text-white w-6 h-6 rounded-full flex items-center justify-center text-xs">${hh.number}</span>
                        Household #${hh.number}
                    </h6>
                    <button onclick="removeHousehold('${hh.id}')" class="text-red-500 hover:text-red-600 p-1">
                        <i data-feather="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Head of Household Name</label>
                        <input type="text" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm" placeholder="Enter name">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Family Members</label>
                        <input type="number" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm" placeholder="Count">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Land Area (ha)</label>
                        <input type="number" step="0.01" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm" placeholder="Hectares">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Primary Crop</label>
                        <select class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm">
                            <option value="">Select</option>
                            <option value="rice">Rice</option>
                            <option value="wheat">Wheat</option>
                            <option value="maize">Maize</option>
                            <option value="vegetables">Vegetables</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    feather.replace();
}

// Final Submission
function showFinalSubmitModal() {
    saveCurrentStepData();
    
    const summary = document.getElementById('submissionSummary');
    const data = state.currentSurvey?.data || {};
    
    summary.innerHTML = `
        <div class="flex justify-between"><span>Survey ID:</span><span class="font-medium">${state.currentSurvey?.id || 'N/A'}</span></div>
        <div class="flex justify-between"><span>Community:</span><span class="font-medium">${data.villageName || 'N/A'}</span></div>
        <div class="flex justify-between"><span>Ward:</span><span class="font-medium">${data.wardCode || 'N/A'}</span></div>
        <div class="flex justify-between"><span>Total Households:</span><span class="font-medium">${data.totalHouseholds || 'N/A'}</span></div>
        <div class="flex justify-between"><span>Households Entered:</span><span class="font-medium">${state.households.length}</span></div>
        <div class="flex justify-between"><span>Completion:</span><span class="font-medium text-green-600">${state.currentSurvey?.progress || 0}%</span></div>
    `;
    
    document.getElementById('finalSubmitModal').classList.remove('hidden');
}

function closeFinalSubmitModal() {
    document.getElementById('finalSubmitModal').classList.add('hidden');
}

function finalSubmit() {
    // Check all terms are accepted
    const terms1 = document.getElementById('finalTerms1').checked;
    const terms2 = document.getElementById('finalTerms2').checked;
    const terms3 = document.getElementById('finalTerms3').checked;
    
    if (!terms1 || !terms2 || !terms3) {
        showToast('Please accept all terms to proceed');
        return;
    }
    
    // Submit the survey
    if (state.currentSurvey) {
        state.currentSurvey.status = 'submitted';
        state.currentSurvey.progress = 100;
        state.currentSurvey.lastModified = new Date().toISOString().split('T')[0];
        
        const existingIndex = state.surveys.findIndex(s => s.id === state.currentSurvey.id);
        if (existingIndex >= 0) {
            state.surveys[existingIndex] = state.currentSurvey;
        } else {
            state.surveys.push(state.currentSurvey);
        }
        
        closeFinalSubmitModal();
        closeSurveyModal();
        showToast('Survey submitted successfully! Awaiting admin verification.');
        renderDashboard();
    }
}

// Admin Functions
function renderAdminPanel() {
    renderEnumeratorsList();
    renderPendingSurveys();
    renderAdminStats();
}

function renderEnumeratorsList() {
    const container = document.getElementById('enumeratorsList');
    if (!container) return;
    
    container.innerHTML = state.enumerators.map(enumerator => `
        <div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
                    <i data-feather="user" class="w-5 h-5 text-primary-500"></i>
                </div>
                <div>
                    <p class="font-medium text-gray-900 dark:text-white text-sm">${enumerator.name}</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">${enumerator.college}</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <span class="px-2 py-1 rounded text-xs font-medium ${enumerator.status === 'active' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'}">
                    ${enumerator.status}
                </span>
                ${enumerator.status === 'pending' ? `
                    <button onclick="approveEnumerator('${enumerator.id}')" class="p-1 text-green-500 hover:bg-green-50 dark:hover:bg-green-900/20 rounded">
                        <i data-feather="check" class="w-4 h-4"></i>
                    </button>
                ` : ''}
            </div>
        </div>
    `).join('');
    
    feather.replace();
}

function renderPendingSurveys() {
    const container = document.getElementById('pendingSurveysList');
    if (!container) return;
    
    const pendingSurveys = state.surveys.filter(s => s.status === 'submitted');
    
    if (pendingSurveys.length === 0) {
        container.innerHTML = `
            <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                <i data-feather="inbox" class="w-12 h-12 mx-auto mb-4 opacity-50"></i>
                <p>No pending surveys</p>
            </div>
        `;
    } else {
        container.innerHTML = pendingSurveys.map(survey => `
            <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="flex justify-between items-start mb-2">
                    <h4 class="font-medium text-gray-900 dark:text-white text-sm">${survey.title}</h4>
                    <span class="px-2 py-1 bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 rounded text-xs">Submitted</span>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">${survey.location}</p>
                <div class="flex gap-2">
                    <button onclick="verifySurvey('${survey.id}', 'verified')" class="flex-1 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg text-xs font-medium transition-colors">
                        Verify
                    </button>
                    <button onclick="verifySurvey('${survey.id}', 'rejected')" class="flex-1 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-xs font-medium transition-colors">
                        Reject
                    </button>
                </div>
            </div>
        `).join('');
    }
    
    feather.replace();
}

function renderAdminStats() {
    const container = document.getElementById('adminStats');
    if (!container) return;
    
    const stats = {
        totalEnumerators: state.enumerators.length,
        activeEnumerators: state.enumerators.filter(e => e.status === 'active').length,
        pendingEnumerators: state.enumerators.filter(e => e.status === 'pending').length,
        totalSurveys: state.surveys.length,
        draftSurveys: state.surveys.filter(s => s.status === 'draft').length,
        submittedSurveys: state.surveys.filter(s => s.status === 'submitted').length,
        verifiedSurveys: state.surveys.filter(s => s.status === 'verified').length
    };
    
    container.innerHTML = `
        <div class="grid grid-cols-2 gap-4">
            <div class="bg-primary-50 dark:bg-primary-900/20 rounded-lg p-4 text-center">
                <div class="text-2xl font-bold text-primary-600 dark:text-primary-400">${stats.totalEnumerators}</div>
                <div class="text-xs text-gray-600 dark:text-gray-400">Total Enumerators</div>
            </div>
            <div class="bg-green-50 dark:bg-green-900/20 rounded-lg p-4 text-center">
                <div class="text-2xl font-bold text-green-600 dark:text-green-400">${stats.activeEnumerators}</div>
                <div class="text-xs text-gray-600 dark:text-gray-400">Active</div>
            </div>
            <div class="bg-secondary-50 dark:bg-secondary-900/20 rounded-lg p-4 text-center">
                <div class="text-2xl font-bold text-secondary-600 dark:text-secondary-400">${stats.totalSurveys}</div>
                <div class="text-xs text-gray-600 dark:text-gray-400">Total Surveys</div>
            </div>
            <div class="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 text-center">
                <div class="text-2xl font-bold text-blue-600 dark:text-blue-400">${stats.submittedSurveys}</div>
                <div class="text-xs text-gray-600 dark:text-gray-400">Pending Review</div>
            </div>
        </div>
        
        <div class="mt-6">
            <h4 class="font-medium text-gray-900 dark:text-white mb-3">Survey Status Distribution</h4>
            <div class="space-y-2">
                <div class="flex items-center gap-3">
                    <span class="text-xs w-16">Draft</span>
                    <div class="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div class="h-full bg-yellow-400 rounded-full" style="width: ${stats.totalSurveys ? (stats.draftSurveys / stats.totalSurveys * 100) : 0}%"></div>
                    </div>
                    <span class="text-xs w-8 text-right">${stats.draftSurveys}</span>
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-xs w-16">Submitted</span>
                    <div class="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div class="h-full bg-blue-400 rounded-full" style="width: ${stats.totalSurveys ? (stats.submittedSurveys / stats.totalSurveys * 100) : 0}%"></div>
                    </div>
                    <span class="text-xs w-8 text-right">${stats.submittedSurveys}</span>
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-xs w-16">Verified</span>
                    <div class="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div class="h-full bg-green-400 rounded-full" style="width: ${stats.totalSurveys ? (stats.verifiedSurveys / stats.totalSurveys * 100) : 0}%"></div>
                    </div>
                    <span class="text-xs w-8 text-right">${stats.verifiedSurveys}</span>
                </div>
            </div>
        </div>
    `;
}

function approveEnumerator(id) {
    const enumerator = state.enumerators.find(e => e.id === id);
    if (enumerator) {
        enumerator.status = 'active';
        enumerator.collegeIdVerified = true;
        showToast(`Enumerator ${enumerator.name} approved`);
        renderEnumeratorsList();
        renderAdminStats();
    }
}

function verifySurvey(id, status) {
    const survey = state.surveys.find(s => s.id === id);
    if (survey) {
        survey.status = status;
        showToast(`Survey ${status === 'verified' ? 'verified' : 'rejected'}`);
        renderPendingSurveys();
        renderAdminStats();
    }
}

function deleteSurvey(id) {
    if (confirm('Are you sure you want to delete this survey?')) {
        state.surveys = state.surveys.filter(s => s.id !== id);
        showToast('Survey deleted');
        renderDashboard();
    }
}

// Toast Notification
function showToast(message) {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toastMessage');
    
    toastMessage.textContent = message;
    toast.classList.remove('translate-y-20', 'opacity-0');
    
    setTimeout(() => {
        toast.classList.add('translate-y-20', 'opacity-0');
    }, 3000);
}

// Close modals on backdrop click
document.addEventListener('click', (e) => {
    if (e.target.id === 'loginModal') {
        closeLoginModal();
    }
    if (e.target.id === 'registerModal') {
        closeRegisterModal();
    }
    if (e.target.id === 'surveyModal') {
        closeSurveyModal();
    }
    if (e.target.id === 'finalSubmitModal') {
        closeFinalSubmitModal();
    }
});