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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e994ddf
1b4b6d2
 
 
e994ddf
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7516417
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369b6c9
 
 
 
 
 
 
 
1b4b6d2
 
 
 
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
import React, { useState, useEffect } from 'react';
import { 
  Upload, CheckCircle, AlertTriangle, Play, HelpCircle, 
  Layers, Check, ChevronRight, FileSpreadsheet, FileText, ZoomIn, ZoomOut
} from 'lucide-react';
import UploadStep from './workflow/UploadStep';
import ClassifyStep from './workflow/ClassifyStep';
import ExtractStep from './workflow/ExtractStep';
import LoadingOverlay from './common/LoadingOverlay';
import VerifyStep from './workflow/VerifyStep';
import BoqStep from './workflow/BoqStep';
import FeedbackModal from './common/FeedbackModal';

export default function Workflow({ token, project, isArabic, onNavigate }) {
  const [currentStep, setCurrentStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [loadingText, setLoadingText] = useState('');
  const [loadingSubtext, setLoadingSubtext] = useState('');
  const [message, setMessage] = useState('');
  
  // File Upload State
  const [strFiles, setStrFiles] = useState([]);
  const [archFiles, setArchFiles] = useState([]);
  const [uploadResult, setUploadResult] = useState(null);
  
  // Classification State
  const [classifiedPages, setClassifiedPages] = useState([]);
  const [selectedPageIndex, setSelectedPageIndex] = useState(0);
  
  // Extraction State
  const [extractionResults, setExtractionResults] = useState(null);
  
  // Confirm/Verify State
  const [confirmedData, setConfirmedData] = useState({
    longest_length: 0,
    longest_width: 0,
    plot_area: 0,
    gf_area: 0,
    ext_perimeter: 0,
    roof_perimeter: 0,
    roof_slab_area: 0,
    compound_length: 0,
    total_villa_height: 0,
    parapet_height: 1.0,
    excavation_depth: 1.25,
    neck_column_height: 1.0,
    solid_block_height: 1.0,
    staircase_volume_per_level: 5.2,
    schedules: {},
    floors: {},
    walls: {},
    openings: {}
  });
  
  // Calculation Parameters
  const [calcParams, setCalcParams] = useState({
    num_floors: 2,
    gf_height: 4.0,
    f1_height: 4.0,
    f2_height: 4.0,
    excavation_depth: 1.25,
    include_road_base: true,
    concrete_grade: "C30/37",
    solid_block_thickness: "200mm",
    thermal_block_thickness: "200mm",
    hollow_block_thickness: "100mm",
    // Roof stair-room handling for the top floor (auto-detected, user-editable)
    top_floor_is_stair_room: false,
    stair_room_area: "",
    stair_room_perimeter: ""
  });
  
  // Review / BOQ Items
  const [boqItems, setBoqItems] = useState([]);
  const [boqMeta, setBoqMeta] = useState({ needs_input: [], estimates: [] });
  const [sanityWarnings, setSanityWarnings] = useState([]);
  
  const [showFeedback, setShowFeedback] = useState(false);
  
  // UI States
  const [zoom, setZoom] = useState(1);
  const [acknowledgedEstimates, setAcknowledgedEstimates] = useState(false);

  const renderSourceBadge = (fieldName) => {
    const source = confirmedData.sources?.[fieldName] || '';
    if (!source) return null;
    
    let badgeColor = '#3b82f6'; // blue for AI
    let bgColor = '#eff6ff';
    let confidence = '85%';
    
    if (source.includes('Verified')) {
      badgeColor = '#10b981'; // green for user verified
      bgColor = '#ecfdf5';
      confidence = '100%';
    } else if (source.includes('CV')) {
      badgeColor = '#8b5cf6'; // purple for CV
      bgColor = '#f5f3ff';
      confidence = '70%';
    } else if (source.includes('Fallback') || source.includes('Heuristic')) {
      badgeColor = '#f59e0b'; // orange for math fallback/estimates
      bgColor = '#fffbeb';
      confidence = '50%';
    } else if (source.includes('Default')) {
      badgeColor = '#6b7280'; // gray for default
      bgColor = '#f3f4f6';
      confidence = '90%';
    }
    
    return (
      <span style={{ 
        marginLeft: '8px', 
        padding: '2px 6px', 
        borderRadius: '4px', 
        fontSize: '0.7rem', 
        fontWeight: 600,
        color: badgeColor,
        backgroundColor: bgColor,
        border: `1.5px solid ${badgeColor}`
      }}>
        {source} ({confidence})
      </span>
    );
  };

  const updateConfirmedField = (fieldName, value) => {
    setConfirmedData(prev => {
      const updated = { ...prev };
      updated[fieldName] = value;
      if (!updated.sources) updated.sources = {};
      updated.sources[fieldName] = "User Verified";
      if (fieldName === 'compound_length') {
        updated.compound_length_is_estimated = false;
      }
      return updated;
    });
  };

  const updateOpeningField = (subField, value) => {
    setConfirmedData(prev => {
      const updated = { ...prev };
      if (!updated.openings) updated.openings = {};
      if (!updated.openings.totals) updated.openings.totals = {};
      updated.openings.totals[subField] = value;
      
      if (!updated.sources) updated.sources = {};
      updated.sources[subField] = "User Verified";
      
      if (subField === 'door_count') {
        updated.openings.totals.door_count_is_estimated = false;
      } else if (subField === 'window_area') {
        updated.openings.totals.window_area_is_estimated = false;
      }
      return updated;
    });
  };

  const hasEstimates = !!(confirmedData.compound_length_is_estimated ||
                       confirmedData.openings?.totals?.door_count_is_estimated || 
                       confirmedData.openings?.totals?.window_area_is_estimated);

  const API_URL = "/api/workflow";

  useEffect(() => {
    // If project already has some state, load it
    if (project) {
      setCurrentStep(project.current_step || 1);
      fetchActiveState();
    }
  }, [project]);

  const fetchActiveState = async () => {
    try {
      const res = await fetch(`${API_URL}/projects/active?project_id=${project.id}`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (!res.ok) return;
      const text = await res.text();
      if (!text) return;
      let data = null;
      try { data = JSON.parse(text); } catch (e) { return; }
      if (data.has_active && data.state_data) {
        const state = typeof data.state_data === 'string' ? JSON.parse(data.state_data) : data.state_data;
        if (state.classified_pages) setClassifiedPages(state.classified_pages);
        if (state.extraction_results) setExtractionResults(state.extraction_results);
        if (state.confirmed_auto_data) {
          setConfirmedData(prev => ({ 
            ...prev, 
            excavation_depth: 1.25,
            neck_column_height: 1.0,
            solid_block_height: 1.0,
            staircase_volume_per_level: 5.2,
            ...state.confirmed_auto_data 
          }));
        }
        if (state.boq_items) setBoqItems(state.boq_items);
        if (state.boq_meta) setBoqMeta(state.boq_meta);
        // Pre-fill the auto-detected roof stair-room flag for the top floor.
        {
          const ftypes = (state.confirmed_auto_data && state.confirmed_auto_data.floor_types) || state.floor_types || {};
          const nf = state.num_floors || (state.confirmed_auto_data && state.confirmed_auto_data.structural_levels) || 2;
          const topFk = nf >= 3 ? '2f' : '1f';
          const topIsStair = ftypes[topFk] === 'stair_room';
          const topFloor = ((state.confirmed_auto_data && state.confirmed_auto_data.floors) || {})[topFk] || {};
          setCalcParams(prev => ({
            ...prev,
            top_floor_is_stair_room: topIsStair,
            stair_room_area: (topIsStair && topFloor.is_stair_room) ? (topFloor.area ?? '') : prev.stair_room_area,
            stair_room_perimeter: (topIsStair && topFloor.is_stair_room) ? (topFloor.ext_perimeter ?? '') : prev.stair_room_perimeter,
          }));
        }
        if (state.num_floors) setCalcParams(prev => ({
          ...prev,
          num_floors: state.num_floors,
          gf_height: state.gf_height || 4.0,
          f1_height: state.f1_height || 4.0,
          f2_height: state.f2_height || 4.0,
          excavation_depth: state.excavation_depth || 1.25,
          include_road_base: state.include_road_base !== false,
          concrete_grade: state.concrete_grade || "C30/37",
          solid_block_thickness: state.solid_block_thickness || "200mm",
          thermal_block_thickness: state.thermal_block_thickness || "200mm",
          hollow_block_thickness: state.hollow_block_thickness || "100mm"
        }));
      }
    } catch (err) {
      console.error(err);
    }
  };

  const saveActiveState = async (step, overrideState = {}) => {
    try {
      const stateToSave = {
        project_id: project.id,
        project_name: project.name,
        current_step: step,
        classified_pages: classifiedPages,
        extraction_results: extractionResults,
        confirmed_auto_data: confirmedData,
        boq_items: boqItems,
        boq_meta: boqMeta,
        ...calcParams,
        ...overrideState
      };
      
      await fetch("/api/projects", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          project_id: project.id,
          project_name: project.name,
          current_step: step,
          state_data: stateToSave,
          boq_data: { items: boqItems.filter(item => !item._is_header) }
        })
      });
    } catch (err) {
      console.error(err);
    }
  };

  // Step 1: Upload Files
  const handleUpload = async (e) => {
    e.preventDefault();
    if ((strFiles.length === 0 && archFiles.length === 0) || loading) return;

    setLoading(true);
    setLoadingText(isArabic ? 'جاري قراءة المخططات...' : 'Uploading & Processing Blueprints...');
    setMessage('');

    const safeJsonFetch = async (url, options = {}) => {
      const res = await fetch(url, options);
      const text = await res.text();
      let data = null;
      if (text) {
        try {
          data = JSON.parse(text);
        } catch (e) {}
      }
      if (!res.ok) {
        const msg = data?.detail || (res.status === 504 ? (isArabic ? 'انتهت مهلة استجابة الخادم (504). يرجى المحاولة مجدداً.' : 'Server gateway timeout (504). Please try again.') : (isArabic ? `فشل طلب الخادم (رمز ${res.status}).` : `Server request failed (HTTP ${res.status}).`));
        throw new Error(msg);
      }
      if (!data) {
        throw new Error(isArabic ? `تنسيق رد غير صالح من الخادم (رمز ${res.status}).` : `Invalid response format from server (HTTP ${res.status}).`);
      }
      return data;
    };

    try {
      let lastData = null;

      const formData = new FormData();
      formData.append('project_id', project.id);
      
      let hasStr = false;
      if (strFiles.length > 0) {
        hasStr = true;
        strFiles.forEach(f => formData.append('str_files', f));
      }
      
      let hasArch = false;
      if (archFiles.length > 0) {
        hasArch = true;
        archFiles.forEach(f => formData.append('arch_files', f));
      }
      
      if (hasStr || hasArch) {
        setLoadingSubtext(isArabic ? 'جاري رفع المخططات (الإنشائية والمعمارية)...' : 'Uploading Drawings (Structural & Architectural)...');
        lastData = await safeJsonFetch(`${API_URL}/upload`, {
          method: 'POST',
          headers: { 'Authorization': `Bearer ${token}` },
          body: formData
        });
      }
      
      setUploadResult(lastData);
      setMessage(isArabic ? 'تم رفع المخططات وتقسيمها بنجاح!' : 'Drawings uploaded successfully!');
      
      // Auto run classification
      handleAutoClassify();
    } catch (err) {
      setMessage(`Error: ${err.message}`);
      setLoading(false);
    }
  };

  // Step 2: Auto Classify
  const handleAutoClassify = async () => {
    setLoading(true);
    setLoadingText(isArabic ? 'جاري تصنيف الصفحات...' : 'Classifying Pages...');
    setLoadingSubtext(isArabic ? 'يقوم الذكاء الاصطناعي بالتعرف على نوع كل صفحة...' : 'AI is analyzing and identifying each drawing type...');
    try {
      const safeJsonFetch = async (url, options = {}) => {
        const res = await fetch(url, options);
        const text = await res.text();
        let data = null;
        if (text) {
          try { data = JSON.parse(text); } catch (e) {}
        }
        if (!res.ok) {
          const msg = data?.detail || (res.status === 504 ? (isArabic ? 'انتهت مهلة استجابة الخادم أثناء التصنيف (504).' : 'Server gateway timeout during classification (504).') : `Server error (HTTP ${res.status})`);
          throw new Error(msg);
        }
        if (!data) throw new Error(`Invalid response format from server (HTTP ${res.status}).`);
        return data;
      };

      const data = await safeJsonFetch(`${API_URL}/classify/auto`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ project_id: project.id })
      });
      
      setClassifiedPages(data.classified_pages || []);
      setCurrentStep(2);
      await saveActiveState(2, { classified_pages: data.classified_pages });
    } catch (err) {
      setMessage(`Error: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleSaveClassifications = async () => {
    setLoading(true);
    setLoadingText(isArabic ? 'جاري الحفظ...' : 'Saving Classifications...');
    setLoadingSubtext('');
    try {
      const cleanPages = (classifiedPages || []).map(p => ({
        pdf: p.pdf || 'structural',
        page_index: Number(p.page_index) || 0,
        page_num: Number(p.page_num) || 1,
        text_preview: (p.text_preview || '').slice(0, 200),
        detected_type: p.detected_type || 'unknown',
        confidence: p.confidence || 'low',
        items: Array.isArray(p.items) ? p.items : []
      }));

      const res = await fetch(`${API_URL}/classify/save`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          project_id: Number(project.id),
          classified_pages: cleanPages
        })
      });
      const text = await res.text();
      let data = null;
      if (text) {
        try { data = JSON.parse(text); } catch (e) {}
      }
      if (!res.ok) {
        throw new Error(data?.detail || (isArabic ? 'فشل حفظ التصنيفات.' : 'Failed to save classifications.'));
      }
      
      setCurrentStep(3);
      await saveActiveState(3, { classified_pages: cleanPages });
    } catch (err) {
      alert(err.message);
    } finally {
      setLoading(false);
    }
  };

  const [extractionProgress, setExtractionProgress] = useState(null);

  // Step 3: Run AI Extraction
  const handleRunExtraction = async () => {
    setLoading(true);
    setExtractionProgress(0);
    setLoadingText(isArabic ? 'جاري الاستخراج بالذكاء الاصطناعي...' : 'AI Extraction in Progress...');
    setLoadingSubtext(isArabic ? 'هذه العملية قد تستغرق دقيقة. جاري استخراج الجداول والأبعاد...' : 'This might take a minute. Extracting schedules and dimensions...');
    setMessage('');
    try {
      const res = await fetch(`${API_URL}/extract`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ project_id: project.id })
      });
      
      if (!res.ok) {
        let errorMsg = 'AI extraction failed.';
        try {
          const text = await res.text();
          if (text) {
            const errJson = JSON.parse(text);
            errorMsg = errJson.detail || errorMsg;
          }
        } catch (e) {
          errorMsg = res.status === 504 ? (isArabic ? 'انتهت مهلة خادم الاستخراج (504). يرجى المحاولة مجدداً.' : 'Extraction request timed out (504). Please try again.') : `Server Error (HTTP ${res.status})`;
        }
        throw new Error(errorMsg);
      }
      
      const reader = res.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let isStreamDone = false;
      let buffer = '';

      while (!isStreamDone) {
        const { value, done } = await reader.read();
        isStreamDone = done;
        if (value) {
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop(); // keep the last incomplete chunk in buffer
          
          for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.substring(6));
                
                if (data.progress !== undefined) {
                  setExtractionProgress(data.progress);
                }
                if (data.status) {
                  setLoadingSubtext(data.status);
                }
                if (data.done) {
                  setExtractionResults(data.extraction_results);

                  // Prefer the backend-healed confirmed_auto_data (includes geometric fallbacks,
                  // CV heuristics, and all reconstruct_project_inputs healing). Fall back to
                  // parsing raw extraction_results only if the backend didn't return healed data.
                  let confirmedObj;
                  if (data.confirmed_auto_data && Object.keys(data.confirmed_auto_data).length > 0) {
                    confirmedObj = {
                      ...confirmedData,
                      ...data.confirmed_auto_data,
                      floors: { ...(confirmedData.floors || {}), ...(data.confirmed_auto_data.floors || {}) },
                      walls: { ...(confirmedData.walls || {}), ...(data.confirmed_auto_data.walls || {}) },
                      schedules: { ...(confirmedData.schedules || {}), ...(data.confirmed_auto_data.schedules || {}) },
                      openings: data.confirmed_auto_data.openings || confirmedData.openings || {},
                    };
                    // Map openings totals to flat fields expected by VerifyStep
                    const totals = confirmedObj.openings?.totals || {};
                    if (totals.door_count !== undefined) confirmedObj.total_doors_count = totals.door_count;
                    if (totals.window_area !== undefined) confirmedObj.total_windows_area = totals.window_area;
                  } else {
                    // Fallback: parse raw extraction results manually
                    confirmedObj = {
                      ...confirmedData,
                      floors: { ...(confirmedData.floors || {}) },
                      walls: { ...(confirmedData.walls || {}) },
                      schedules: { ...(confirmedData.schedules || {}) },
                      openings: { ...(confirmedData.openings || {}) }
                    };

                    const floorMap = {
                      "ground_floor_plan": "gf",
                      "first_floor_plan": "1f",
                      "second_floor_plan": "2f",
                      "roof_floor_plan": "roof"
                    };

                    confirmedObj.total_doors_count = 0;
                    confirmedObj.total_windows_area = 0;

                    Object.values(data.extraction_results).forEach(page => {
                      if (!page._ok) return;

                      const dtype = page.drawing_type || page.detected_type;

                      if (page.longest_length) confirmedObj.longest_length = page.longest_length;
                      if (page.longest_width) confirmedObj.longest_width = page.longest_width;
                      if (page.plot_area) confirmedObj.plot_area = page.plot_area;
                      if (page.compound_length) confirmedObj.compound_length = page.compound_length;
                      if (page.total_villa_height) confirmedObj.total_villa_height = page.total_villa_height;

                      if (dtype === "ground_floor_plan") {
                        if (page.total_floor_area) confirmedObj.gf_area = page.total_floor_area;
                        if (page.ext_perimeter) confirmedObj.ext_perimeter = page.ext_perimeter;
                        if (page.int_walls_length) confirmedObj.int_walls_length = page.int_walls_length;
                        if (page.int_walls_10cm_m !== undefined) confirmedObj.int_walls_10cm_m = page.int_walls_10cm_m;
                        if (page.int_walls_20cm_m !== undefined) confirmedObj.int_walls_20cm_m = page.int_walls_20cm_m;
                      }

                      if (["ground_floor_plan", "first_floor_plan", "second_floor_plan", "roof_floor_plan"].includes(dtype)) {
                        if (page.total_doors_count !== undefined) {
                          confirmedObj.total_doors_count = (confirmedObj.total_doors_count || 0) + page.total_doors_count;
                        }
                        if (page.total_windows_area !== undefined) {
                          confirmedObj.total_windows_area = (confirmedObj.total_windows_area || 0) + page.total_windows_area;
                        }
                      }

                      if (dtype === "roof_floor_plan" || dtype === "roof_slab") {
                        if (page.roof_perimeter) confirmedObj.roof_perimeter = page.roof_perimeter;
                        if (page.slab_area) confirmedObj.roof_slab_area = page.slab_area;
                      }

                      if (floorMap[dtype]) {
                        const fk = floorMap[dtype];
                        confirmedObj.floors[fk] = {
                          area: page.total_floor_area || page.floor_area || 0.0,
                          ext_perimeter: page.ext_perimeter || 0.0,
                          wet_area: page.wet_area || 0.0,
                          wet_perimeter: page.wet_perimeter || 0.0,
                          dry_perimeter: page.dry_perimeter || 0.0,
                          balcony_area: page.balcony_area || page.balcony_terrace_area_m2 || 0.0,
                          height: page.floor_height || 4.0
                        };

                        confirmedObj.walls[fk] = {
                          internal_total_m: page.int_walls_length || 0.0,
                          internal_10cm_m: page.int_walls_10cm_m || 0.0,
                          internal_20cm_m: page.int_walls_20cm_m || 0.0
                        };
                      }

                      if (page.footings) {
                        confirmedObj.schedules.foundation = { footings: page.footings };
                      }
                      if (page.beams) {
                        confirmedObj.schedules[dtype] = { beams: page.beams };
                      }
                      if (page.columns) {
                        confirmedObj.schedules.column_schedule = { columns: page.columns };
                      }
                      if (page.doors || page.windows) {
                        if (page.doors) confirmedObj.openings.doors = page.doors;
                        if (page.windows) confirmedObj.openings.windows = page.windows;
                      }
                    });
                  }

                  setConfirmedData(confirmedObj);
                  // Pre-fill the auto-detected roof stair-room flag for the top floor
                  {
                    const ftypes = confirmedObj.floor_types || {};
                    const nf = calcParams.num_floors || confirmedObj.structural_levels || 2;
                    const topFk = nf >= 3 ? '2f' : '1f';
                    const topIsStair = ftypes[topFk] === 'stair_room';
                    const topFloor = (confirmedObj.floors || {})[topFk] || {};
                    setCalcParams(prev => ({
                      ...prev,
                      top_floor_is_stair_room: topIsStair,
                      stair_room_area: (topIsStair && topFloor.is_stair_room) ? (topFloor.area ?? '') : prev.stair_room_area,
                      stair_room_perimeter: (topIsStair && topFloor.is_stair_room) ? (topFloor.ext_perimeter ?? '') : prev.stair_room_perimeter,
                    }));
                  }
                  setCurrentStep(4);
                  await saveActiveState(4, { extraction_results: data.extraction_results, confirmed_auto_data: confirmedObj });
                  
                  setLoading(false);
                  setExtractionProgress(null);
                  isStreamDone = true; // explicitly break
                }
              } catch (e) {
                console.error("Error parsing SSE chunk:", e, line);
              }
            }
          }
        }
      }
    } catch (err) {
      setMessage(`Error: ${err.message}`);
      setLoading(false);
      setExtractionProgress(null);
    }
  };

  // Step 4: Confirm parsed variables
  const handleConfirmDataSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setLoadingText(isArabic ? 'جاري حفظ التأكيد...' : 'Saving Verified Data...');
    setLoadingSubtext('');
    try {
      const res = await fetch(`${API_URL}/confirm`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          project_id: project.id,
          confirmed_data: confirmedData
        })
      });
      if (!res.ok) throw new Error('Failed to save confirmation data.');
      
      setCurrentStep(5);
      await saveActiveState(5);
    } catch (err) {
      alert(err.message);
    } finally {
      setLoading(false);
    }
  };

  // Step 5: Execute BOQ Calculation
  const handleRunCalculation = async (e) => {
    e.preventDefault();
    setLoading(true);
    setLoadingText(isArabic ? 'جاري الحساب الهندسي...' : 'Running Engineering Calculations...');
    setLoadingSubtext(isArabic ? 'نقوم الآن بتطبيق معادلات حصر الكميات وبناء جدول الكميات...' : 'Applying QS formulas and building the BOQ...');
    try {
      const res = await fetch(`${API_URL}/calculate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          project_id: project.id,
          ...calcParams,
          // Send null (not "") for blank stair-room dims so the backend uses its
          // auto value; pydantic floats reject empty strings.
          stair_room_area: calcParams.stair_room_area === "" || calcParams.stair_room_area == null ? null : parseFloat(calcParams.stair_room_area),
          stair_room_perimeter: calcParams.stair_room_perimeter === "" || calcParams.stair_room_perimeter == null ? null : parseFloat(calcParams.stair_room_perimeter),
          top_floor_is_stair_room: !!calcParams.top_floor_is_stair_room
        })
      });
      const text = await res.text();
      let data = null;
      if (text) {
        try { data = JSON.parse(text); } catch (e) {}
      }
      if (!res.ok) throw new Error(data?.detail || 'Calculation engine failed.');
      if (!data) throw new Error('Calculation engine returned an invalid response.');
      
      // Inject pricing columns if not present
      const pricedItems = data.boq_items.map(item => {
        if (item._is_header) return item;
        return {
          ...item,
          "Unit Price": item["Unit Price"] !== undefined ? parseFloat(item["Unit Price"]) : 0.0,
          "Total": item["Total"] !== undefined ? parseFloat(item["Total"]) : 0.0
        };
      });

      setBoqItems(pricedItems);
      setBoqMeta(data.boq_meta);
      setCurrentStep(6);
      await saveActiveState(6, { boq_items: pricedItems, boq_meta: data.boq_meta });
    } catch (err) {
      alert(err.message);
    } finally {
      setLoading(false);
    }
  };

  // Step 6: Review Pricing and quantities
  const handlePriceChange = (index, priceVal) => {
    const price = parseFloat(priceVal) || 0.0;
    setBoqItems(prev => {
      const updated = [...prev];
      const qty = parseFloat(updated[index]["Quantity"]) || 0.0;
      updated[index]["Unit Price"] = price;
      updated[index]["Total"] = qty * price;
      return updated;
    });
  };

  const handleQtyChange = (index, qtyVal) => {
    const qty = parseFloat(qtyVal);
    setBoqItems(prev => {
      const updated = [...prev];
      updated[index]["Quantity"] = isNaN(qty) ? 0 : qty;
      updated[index].has_error = false;   // a manual edit clears the calc-error flag
      const price = parseFloat(updated[index]["Unit Price"]) || 0.0;
      updated[index]["Total"] = (isNaN(qty) ? 0 : qty) * price;
      return updated;
    });
  };

  const calculateGrandTotal = () => {
    return boqItems.reduce((acc, item) => {
      if (item._is_header) return acc;
      return acc + (parseFloat(item["Total"]) || 0.0);
    }, 0.0);
  };

  const handleSaveReview = async () => {
    setLoading(true);
    setLoadingText(isArabic ? 'جاري الحفظ...' : 'Saving Review...');
    try {
      const res = await fetch(`${API_URL}/review/save`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          project_id: project.id,
          boq_items: boqItems
        })
      });
      if (!res.ok) throw new Error('Failed to save quantities review.');
      
      setCurrentStep(8); // Proceed directly to download
      await saveActiveState(8);
    } catch (err) {
      alert(err.message);
    } finally {
      setLoading(false);
    }
  };

  // Exporters
  const downloadExcel = () => {
    window.open(`/api/workflow/export/excel?project_id=${project.id}&Authorization=Bearer ${token}`);
    setShowFeedback(true);
  };

  const downloadPDF = () => {
    window.open(`/api/workflow/export/pdf?project_id=${project.id}&Authorization=Bearer ${token}`);
    setShowFeedback(true);
  };

  // UI Helpers
  const stepIcons = {
    1: <Upload size={16} />,
    2: <Layers size={16} />,
    3: <Play size={16} />,
    4: <Check size={16} />,
    5: <Layers size={16} />,
    6: <FileText size={16} />,
    7: <Layers size={16} />,
    8: <FileSpreadsheet size={16} />
  };

  const stepLabels = {
    1: { en: 'Upload', ar: 'رفع المخططات' },
    2: { en: 'Classify', ar: 'تصنيف الصفحات' },
    3: { en: 'Extract', ar: 'استخراج بالذكاء' },
    4: { en: 'Confirm', ar: 'تأكيد الحقول' },
    5: { en: 'Equations', ar: 'تطبيق المعادلات' },
    6: { en: 'Review BOQ', ar: 'مراجعة الأسعار' },
    7: { en: 'Arrange', ar: 'ترتيب البنود' },
    8: { en: 'Download', ar: 'تحميل التقارير' }
  };

  return (
    <div style={{ position: 'relative', width: '100%', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <LoadingOverlay 
        isLoading={loading} 
        text={loadingText} 
        subtext={loadingSubtext}
        progress={extractionProgress}
        isArabic={isArabic} 
      />
      
      <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh', direction: isArabic ? 'rtl' : 'ltr', textAlign: isArabic ? 'right' : 'left' }}>
      
      {/* 8-Step Header Indicator */}
      <div className="glass-panel" style={{ margin: '20px 30px', padding: '15px 20px', display: 'flex', justifyContent: 'space-between', gap: '8px', overflowX: 'auto' }}>
        {[1, 2, 3, 4, 5, 6, 7, 8].map((num) => {
          const isActive = num === currentStep;
          const isDone = num < currentStep;
          return (
            <div 
              key={num} 
              onClick={() => isDone && setCurrentStep(num)}
              style={{
                flex: 1,
                minWidth: '95px',
                padding: '8px 4px',
                borderRadius: '12px',
                textAlign: 'center',
                background: isActive ? 'linear-gradient(135deg, var(--primary), var(--primary-hover))' : isDone ? 'rgba(16, 185, 129, 0.08)' : 'var(--bg-primary)',
                border: isActive ? 'none' : isDone ? '1px solid rgba(16, 185, 129, 0.3)' : '1px solid var(--border-color)',
                color: isActive ? 'white' : isDone ? 'var(--success)' : 'var(--text-secondary)',
                cursor: isDone ? 'pointer' : 'default',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: '4px',
                boxShadow: isActive ? '0 4px 12px var(--primary-glow)' : 'none',
                transition: 'all 0.3s ease'
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                {isDone ? <CheckCircle size={14} /> : stepIcons[num]}
                <span style={{ fontSize: '0.85rem', fontWeight: 700 }}>{num}</span>
              </div>
              <span style={{ fontSize: '0.72rem', fontWeight: 600, display: 'block', whiteSpace: 'nowrap' }}>
                {isArabic ? stepLabels[num].ar : stepLabels[num].en}
              </span>
            </div>
          );
        })}
      </div>

      {message && (
        <div style={{ margin: '0 30px 20px', padding: '12px 16px', backgroundColor: 'rgba(59,130,246,0.1)', color: 'var(--primary)', borderRadius: '8px', fontSize: '0.9rem' }}>
          {message}
        </div>
      )}

        {/* Steps Content Area */}
      <div style={{ flex: 1, padding: '0 30px 30px' }}>
        {currentStep === 1 && (
          <UploadStep
            strFiles={strFiles}
            setStrFiles={setStrFiles}
            archFiles={archFiles}
            setArchFiles={setArchFiles}
            loading={loading}
            handleUpload={handleUpload}
            isArabic={isArabic}
          />
        )}
        {currentStep === 2 && (
          <ClassifyStep
            classifiedPages={classifiedPages}
            setClassifiedPages={setClassifiedPages}
            selectedPageIndex={selectedPageIndex}
            setSelectedPageIndex={setSelectedPageIndex}
            zoom={zoom}
            setZoom={setZoom}
            isArabic={isArabic}
            handleSaveClassifications={handleSaveClassifications}
            loading={loading}
          />
        )}
        {currentStep === 3 && (
          <ExtractStep
            loading={loading}
            isArabic={isArabic}
            handleRunExtraction={handleRunExtraction}
          />
        )}
        {(currentStep === 4 || currentStep === 5) && (
          <VerifyStep
            currentStep={currentStep}
            projectId={project.id}
            token={token}
            confirmedData={confirmedData}
            sanityWarnings={sanityWarnings}
            updateConfirmedField={updateConfirmedField}
            updateOpeningField={updateOpeningField}
            renderSourceBadge={renderSourceBadge}
            extractionResults={extractionResults}
            hasEstimates={hasEstimates}
            acknowledgedEstimates={acknowledgedEstimates}
            setAcknowledgedEstimates={setAcknowledgedEstimates}
            handleConfirmDataSubmit={handleConfirmDataSubmit}
            calcParams={calcParams}
            setCalcParams={setCalcParams}
            handleRunCalculation={handleRunCalculation}
            loading={loading}
            isArabic={isArabic}
          />
        )}
        {(currentStep === 6 || currentStep === 8) && (
          <BoqStep
            currentStep={currentStep}
            boqMeta={boqMeta}
            calculateGrandTotal={calculateGrandTotal}
            boqItems={boqItems}
            handlePriceChange={handlePriceChange}
            handleQtyChange={handleQtyChange}
            handleSaveReview={handleSaveReview}
            setCurrentStep={setCurrentStep}
            downloadExcel={downloadExcel}
            downloadPDF={downloadPDF}
            onNavigate={onNavigate}
            isArabic={isArabic}
          />
        )}
      </div>
      
      <FeedbackModal 
        isOpen={showFeedback} 
        onClose={() => setShowFeedback(false)} 
        toolName="QTO Workflow" 
        projectName={project ? project.name : ''} 
        isArabic={isArabic} 
      />
    </div>
    </div>
  );
}