File size: 10,351 Bytes
ed9f15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * Stepper Navigation - Handles multi-step workflow

 */

import { showConfirmModal } from './modal.js';
import { saveGradingResults, prepareEmbryoData, isFirebaseReady } from '../utils/firebaseService.js';
import { appState } from '../state.js';
import { showToast } from './toast.js';

let currentStep = 1;
const totalSteps = 3;

/**

 * Initialize stepper navigation

 */
export function initializeStepper() {
    updateStepperUI();
    attachStepperEventListeners();
}

/**

 * Navigate to a specific step

 */
export function goToStep(stepNumber) {
    if (stepNumber < 1 || stepNumber > totalSteps) return;
    
    currentStep = stepNumber;
    updateStepperUI();
    scrollToTop();
}

/**

 * Go to next step

 */
export function nextStep() {
    if (currentStep < totalSteps) {
        currentStep++;
        updateStepperUI();
        scrollToTop();
    }
}

/**

 * Go to previous step

 */
export function prevStep() {
    if (currentStep > 1) {
        currentStep--;
        updateStepperUI();
        scrollToTop();
    }
}

/**

 * Mark a step as completed

 */
export function markStepCompleted(stepNumber) {
    const step = document.querySelector(`.step[data-step="${stepNumber}"]`);
    if (step) {
        step.classList.add('completed');
    }
    
    // Update step line
    const stepLines = document.querySelectorAll('.step-line');
    if (stepLines[stepNumber - 1]) {
        stepLines[stepNumber - 1].classList.add('completed');
    }
}

/**

 * Update stepper UI

 */
function updateStepperUI() {
    // Update step indicators
    document.querySelectorAll('.step').forEach((step, index) => {
        const stepNum = index + 1;
        step.classList.remove('active');
        
        if (stepNum === currentStep) {
            step.classList.add('active');
        }
    });
    
    // Update step content visibility
    document.querySelectorAll('.step-content').forEach((content, index) => {
        const stepNum = index + 1;
        content.classList.remove('active');
        
        if (stepNum === currentStep) {
            content.classList.add('active');
        }
    });
}

/**

 * Reset stepper to first step

 */
export function resetStepper() {
    currentStep = 1;
    
    // Remove completed status from all steps
    document.querySelectorAll('.step').forEach(step => {
        step.classList.remove('completed', 'active');
    });
    
    document.querySelectorAll('.step-line').forEach(line => {
        line.classList.remove('completed');
    });
    
    updateStepperUI();
}

/**

 * Get current step number

 */
export function getCurrentStep() {
    return currentStep;
}

/**

 * Scroll to top of page

 */
function scrollToTop() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

/**

 * Attach event listeners for step navigation

 */
function attachStepperEventListeners() {
    // Step 1 navigation
    const nextStep1 = document.getElementById('nextStep1');
    if (nextStep1) {
        nextStep1.addEventListener('click', () => {
            markStepCompleted(1);
            goToStep(2);
            initializeStep2();
        });
    }

    const startOverBtn = document.getElementById('startOverBtn');
    if (startOverBtn) {
        startOverBtn.addEventListener('click', async () => {
            const confirmed = await showConfirmModal(
                'Are you sure you want to start over? All progress will be lost.',
                'Start Over'
            );
            
            if (confirmed) {
                resetStepper();
                resetWorkflow();
            }
        });
    }

    // Step 2 navigation
    const prevStep2 = document.getElementById('prevStep2');
    if (prevStep2) {
        prevStep2.addEventListener('click', () => goToStep(1));
    }

    const nextStep2 = document.getElementById('nextStep2');
    if (nextStep2) {
        nextStep2.addEventListener('click', () => {
            markStepCompleted(2);
            goToStep(3);
            initializeStep3();
        });
    }

    // Step 3 navigation
    const prevStep3 = document.getElementById('prevStep3');
    if (prevStep3) {
        prevStep3.addEventListener('click', () => goToStep(2));
    }

    const analyzeAnother = document.getElementById('analyzeAnother');
    if (analyzeAnother) {
        analyzeAnother.addEventListener('click', async () => {
            // Save results first, then reset
            await handleSaveAndReset();
        });
    }
}

/**

 * Initialize Step 2 - Show embryo image and prepare for detection

 */
function initializeStep2() {
    // Show the embryo image first, then trigger detection after UI is ready
    setTimeout(() => {
        import('./workflow.js').then(module => {
            module.showEmbryoImageAndDetect();
        });
    }, 150);
}

/**

 * Initialize Step 3 - Evaluate all embryos in background

 */
function initializeStep3() {
    // Trigger evaluation of all embryos in background
    import('./workflow.js').then(module => {
        module.evaluateAllEmbryos();
    });
}

/**

 * Reset workflow (to be called from workflow.js)

 */
export function resetWorkflow() {
    // Reset file input to allow re-uploading the same file
    const imageInput = document.getElementById('imageInput');
    if (imageInput) {
        imageInput.value = '';
    }
    
    // Clear images
    const mainImage = document.getElementById('mainImage');
    const mainImagePreview = document.getElementById('mainImagePreview');
    const croppedImage = document.getElementById('croppedImage');
    const cropCanvas = document.getElementById('cropCanvas');
    
    if (mainImage) {
        mainImage.style.display = 'none';
        mainImage.src = '';
    }
    
    if (croppedImage) {
        croppedImage.style.display = 'none';
        croppedImage.src = '';
    }
    
    if (cropCanvas) {
        cropCanvas.style.display = 'none';
    }
    
    if (mainImagePreview) {
        const placeholder = mainImagePreview.querySelector('.placeholder');
        if (placeholder) placeholder.style.display = 'flex';
    }
    
    // Reset buttons
    const nextStep1 = document.getElementById('nextStep1');
    if (nextStep1) nextStep1.disabled = true;
    
    const nextStep2 = document.getElementById('nextStep2');
    if (nextStep2) nextStep2.disabled = true;
    
    // Clear classification status
    const classificationStatus = document.getElementById('classificationStatus');
    if (classificationStatus) {
        classificationStatus.innerHTML = `

            <p>Upload an image to check if it contains an embryo.</p>

            <p>The system will automatically classify the image upon upload.</p>

        `;
    }
    
    // Clear results
    const finalResults = document.getElementById('finalResults');
    if (finalResults) finalResults.innerHTML = '<p>Processing all embryos...</p>';
    
    const finalPredictions = document.getElementById('finalPredictions');
    if (finalPredictions) finalPredictions.innerHTML = '';
    
    const selectionInfo = document.getElementById('selectionInfo');
    if (selectionInfo) {
        selectionInfo.innerHTML = '<p>Select an embryo to continue.</p>';
    }
    
    // Clear embryo thumbnails
    const embryoThumbnails = document.getElementById('embryoThumbnails');
    if (embryoThumbnails) {
        embryoThumbnails.innerHTML = '';
    }
    
    // Disable zoom controls
    const zoomIn = document.getElementById('zoomIn');
    const zoomOut = document.getElementById('zoomOut');
    const zoomReset = document.getElementById('zoomReset');
    if (zoomIn) zoomIn.disabled = true;
    if (zoomOut) zoomOut.disabled = true;
    if (zoomReset) zoomReset.disabled = true;
    
    // Hide crop editor
    const cropControls = document.getElementById('cropControls');
    const editCropBtn = document.getElementById('editCropBtn');
    if (cropControls) cropControls.style.display = 'none';
    if (editCropBtn) editCropBtn.style.display = 'none';
    
    // Reset appState
    import('../state.js').then(module => {
        module.appState.croppedEmbryos = [];
        module.appState.embryoResults = [];
        module.appState.embryoRemarks = {};  // Clear all remarks
        module.appState.currentEmbryoIndex = 0;
        module.appState.currentImage = null;
        module.appState.zoomLevel = 1;
        module.appState.finalResult = null;
    });
}

/**

 * Enable next button for a step

 */
export function enableNextButton(stepNumber) {
    const button = document.getElementById(`nextStep${stepNumber}`);
    if (button) {
        button.disabled = false;
    }
}

/**

 * Disable next button for a step

 */
export function disableNextButton(stepNumber) {
    const button = document.getElementById(`nextStep${stepNumber}`);
    if (button) {
        button.disabled = true;
    }
}

/**

 * Handle saving results to Firebase

 */
async function handleSaveResults() {
    if (!isFirebaseReady()) {
        console.warn('Firebase is not configured.');
        return false;
    }
    
    if (!appState.croppedEmbryos || appState.croppedEmbryos.length === 0) {
        console.warn('No embryos to save');
        return false;
    }
    
    try {
        // Prepare the data with results and remarks
        const embryoData = prepareEmbryoData(
            appState.croppedEmbryos, 
            appState.currentImage,
            appState.embryoResults,
            appState.embryoRemarks
        );
        
        // Save to Firebase silently
        const docId = await saveGradingResults(embryoData);
        
        // Log to console for debugging
        console.log('Results saved successfully! Document ID:', docId);
        return true;
    } catch (error) {
        console.error('Error saving results:', error);
        return false;
    }
}

/**

 * Handle saving results and then resetting for a new analysis

 */
async function handleSaveAndReset() {
    // Save silently in background
    await handleSaveResults();
    
    // Reset immediately
    resetStepper();
    resetWorkflow();
}