File size: 55,436 Bytes
1b4b6d2
d617de9
361e46e
5885061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
7516417
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5885061
1b4b6d2
7516417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361e46e
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d617de9
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
e735501
 
 
 
452be5a
e735501
 
 
5885061
 
e735501
 
 
 
 
 
 
 
 
 
7516417
e735501
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e093b12
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a625c4
 
 
 
 
 
 
 
 
 
 
571cb08
5a625c4
 
 
 
 
 
 
 
 
 
 
571cb08
 
5a625c4
 
 
 
 
 
 
 
 
 
 
571cb08
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
c91deb8
 
1b4b6d2
 
 
c91deb8
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eedc61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5885061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
e093b12
1b4b6d2
 
 
 
 
 
 
 
 
3f2a193
 
2991a72
 
 
 
 
 
 
 
 
 
 
3f2a193
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5903f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e093b12
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eedc61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React from 'react';
import { Trash2, Plus, Info } from 'lucide-react';
import { cacheUrl } from '../../cacheUrl';

const ScheduleTableEditorModal = ({ isArabic, schedules, onSave, onClose }) => {
  const [footings, setFootings] = React.useState(schedules?.foundation?.footings || []);
  const [columns, setColumns] = React.useState(schedules?.superstructure?.columns || []);

  const handleUpdate = (state, setter, index, field, val) => {
    const updated = [...state];
    updated[index] = { ...updated[index], [field]: val };
    setter(updated);
  };

  const handleRemove = (state, setter, index) => {
    setter(state.filter((_, i) => i !== index));
  };

  const handleAdd = (setter, state, defaultPrefix) => {
    setter([...state, { type: `${defaultPrefix}${state.length + 1}`, length: 1.0, width: 1.0, count: 1 }]);
  };

  const renderTable = (title, state, setter, prefix) => (
    <div style={{ marginBottom: '25px', backgroundColor: '#1e293b', padding: '15px', borderRadius: '8px' }}>
      <h4 style={{ color: 'white', marginTop: 0, marginBottom: '10px', display: 'flex', justifyContent: 'space-between' }}>
        {title}
        <button type="button" onClick={() => handleAdd(setter, state, prefix)} style={{ background: '#3b82f6', color: 'white', border: 'none', padding: '4px 10px', borderRadius: '4px', cursor: 'pointer', fontSize: '0.8rem', display: 'flex', alignItems: 'center', gap: '4px' }}>
          <Plus size={14} /> {isArabic ? 'إضافة صف' : 'Add Row'}
        </button>
      </h4>
      {state.length === 0 ? (
        <p style={{ color: '#94a3b8', fontSize: '0.85rem' }}>{isArabic ? 'لا توجد بيانات مستخرجة.' : 'No data extracted.'}</p>
      ) : (
        <table style={{ width: '100%', borderCollapse: 'collapse', color: 'white', fontSize: '0.85rem', textAlign: 'left' }}>
          <thead>
            <tr style={{ borderBottom: '1px solid #334155' }}>
              <th style={{ padding: '8px 4px' }}>{isArabic ? 'النوع' : 'Type'}</th>
              <th style={{ padding: '8px 4px' }}>{isArabic ? 'الطول (م)' : 'Length (m)'}</th>
              <th style={{ padding: '8px 4px' }}>{isArabic ? 'العرض (م)' : 'Width (m)'}</th>
              <th style={{ padding: '8px 4px' }}>{isArabic ? 'العدد' : 'Count'}</th>
              <th style={{ padding: '8px 4px' }}></th>
            </tr>
          </thead>
          <tbody>
            {state.map((row, i) => (
              <tr key={i} style={{ borderBottom: '1px solid #334155' }}>
                <td style={{ padding: '6px 4px' }}>
                  <input type="text" value={row.type || ''} onChange={(e) => handleUpdate(state, setter, i, 'type', e.target.value)} style={{ width: '100%', background: '#0f172a', border: '1px solid #334155', color: 'white', padding: '4px', borderRadius: '4px' }} />
                </td>
                <td style={{ padding: '6px 4px' }}>
                  <input type="number" step="0.01" value={row.length || ''} onChange={(e) => handleUpdate(state, setter, i, 'length', parseFloat(e.target.value) || 0)} style={{ width: '100%', background: '#0f172a', border: '1px solid #334155', color: 'white', padding: '4px', borderRadius: '4px' }} />
                </td>
                <td style={{ padding: '6px 4px' }}>
                  <input type="number" step="0.01" value={row.width || ''} onChange={(e) => handleUpdate(state, setter, i, 'width', parseFloat(e.target.value) || 0)} style={{ width: '100%', background: '#0f172a', border: '1px solid #334155', color: 'white', padding: '4px', borderRadius: '4px' }} />
                </td>
                <td style={{ padding: '6px 4px' }}>
                  <input type="number" value={row.count || ''} onChange={(e) => handleUpdate(state, setter, i, 'count', parseInt(e.target.value) || 0)} style={{ width: '100%', background: '#0f172a', border: '1px solid #334155', color: 'white', padding: '4px', borderRadius: '4px' }} />
                </td>
                <td style={{ padding: '6px 4px', textAlign: 'center' }}>
                  <button type="button" onClick={() => handleRemove(state, setter, i)} style={{ background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer' }} title={isArabic ? 'حذف' : 'Remove'}>
                    <Trash2 size={16} />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );

  return (
    <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.7)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
      <div style={{ background: 'var(--bg-primary)', padding: '25px', borderRadius: '12px', width: '100%', maxWidth: '800px', maxHeight: '90vh', display: 'flex', flexDirection: 'column', boxShadow: '0 10px 25px rgba(0,0,0,0.5)' }}>
        <h3 style={{ marginTop: 0, marginBottom: '15px', display: 'flex', justifyContent: 'space-between' }}>
          <span>{isArabic ? 'محرر الجداول الهندسية' : 'Engineering Schedules Editor'}</span>
          <button type="button" onClick={onClose} style={{ background: 'none', border: 'none', fontSize: '1.2rem', cursor: 'pointer', color: 'var(--text-secondary)' }}>&times;</button>
        </h3>
        <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '15px' }}>
          {isArabic 
            ? 'يمكنك هنا مراجعة وإضافة وتعديل بيانات القواعد والأعمدة يدوياً.' 
            : 'Review, add, or edit footings and columns data directly from the schedules.'}
        </p>
        
        <div style={{ flex: 1, overflowY: 'auto', paddingRight: '10px' }}>
          {renderTable(isArabic ? 'جدول القواعد (Footings)' : 'Footings Schedule', footings, setFootings, 'F')}
          {renderTable(isArabic ? 'جدول الأعمدة (Columns)' : 'Columns Schedule', columns, setColumns, 'C')}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px', marginTop: '20px' }}>
          <button type="button" onClick={onClose} className="btn" style={{ padding: '8px 16px', background: 'transparent', border: '1px solid var(--border-color)' }}>
            {isArabic ? 'إلغاء' : 'Cancel'}
          </button>
          <button type="button" onClick={() => onSave({
            ...schedules,
            foundation: { ...(schedules?.foundation || {}), footings },
            superstructure: { ...(schedules?.superstructure || {}), columns }
          })} className="btn btn-primary" style={{ padding: '8px 16px' }}>
            {isArabic ? 'حفظ الجداول' : 'Save Schedules'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default function VerifyStep({
  currentStep,
  projectId,
  token,
  confirmedData,
  extractionResults,
  sanityWarnings,
  updateConfirmedField,
  updateOpeningField,
  renderSourceBadge,
  hasEstimates,
  acknowledgedEstimates,
  setAcknowledgedEstimates,
  handleConfirmDataSubmit,
  calcParams,
  setCalcParams,
  handleRunCalculation,
  loading,
  isArabic
}) {
  const [markupImage, setMarkupImage] = React.useState(null);
  const [showTableEditor, setShowTableEditor] = React.useState(false);

  // Scale Calibration State
  const [calibPixel, setCalibPixel] = React.useState('');
  const [calibReal, setCalibReal] = React.useState('');
  const [calibStatus, setCalibStatus] = React.useState('');
  const [calibLoading, setCalibLoading] = React.useState(false);

  const handleCalibrate = async () => {
    if (!calibPixel || !calibReal || !projectId || !token) return;
    setCalibLoading(true);
    setCalibStatus('');
    try {
      const res = await fetch(`/api/projects/${projectId}/calibrate_scale`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          pixel_distance: parseFloat(calibPixel),
          real_distance: parseFloat(calibReal)
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Calibration failed');
      setCalibStatus(isArabic ? 'تم معايرة المقياس بنجاح. يمكنك الآن إعادة تشغيل استخراج الأبعاد.' : 'Scale calibrated successfully. You can now re-run extraction.');
      
      // Update local inputs with the new scale (just roughly)
      if (confirmedData.longest_length && data.scale_factor) {
         // This is a naive update, real calculation happens on the backend on re-extract
      }
    } catch (err) {
      setCalibStatus(isArabic ? `خطأ: ${err.message}` : `Error: ${err.message}`);
    } finally {
      setCalibLoading(false);
    }
  };

  if (currentStep === 4) {
    return (
      <div className="glass-panel" style={{ padding: '30px', maxWidth: '900px', margin: '0 auto', position: 'relative' }}>
        
        {/* Takeoff Viewer Modal */}
        {markupImage === 'show' && (
          <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.8)', zIndex: 9999, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
            <div style={{ background: '#1e293b', padding: '15px', borderRadius: '8px', width: '100%', maxWidth: '1200px', maxHeight: '95vh', display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                <h3 style={{ color: 'white', margin: 0 }}>👁️ Auto-Coloring Takeoff Viewer (OpenCV)</h3>
                <button onClick={() => setMarkupImage(null)} style={{ background: '#ef4444', color: 'white', border: 'none', padding: '8px 16px', borderRadius: '4px', cursor: 'pointer' }}>Close</button>
              </div>
              <div style={{ flex: 1, overflow: 'auto', background: '#000', borderRadius: '4px', display: 'flex', flexDirection: 'column', gap: '20px', padding: '20px' }}>
                {extractionResults && Object.keys(extractionResults).filter(k => extractionResults[k].markup_url).length > 0 ? (
                  Object.values(extractionResults).filter(res => res.markup_url).map((res, idx) => {
                    let imgUrl = res.markup_url;
                    if (imgUrl.includes('\\') || imgUrl.includes('C:')) {
                      const parts = imgUrl.split(/[\\/]/);
                      imgUrl = '/cache/' + parts[parts.length - 1];
                    }
                    return (
                      <div key={idx} style={{ border: '2px solid #333', borderRadius: '8px', padding: '10px', background: '#222' }}>
                        <h4 style={{ color: '#60a5fa', margin: '0 0 10px 0' }}>{res.detected_type || 'Markup'}</h4>
                        <img src={cacheUrl(imgUrl)} alt="Takeoff Markup" style={{ maxWidth: '100%', objectFit: 'contain' }} />
                      </div>
                    );
                  })
                ) : <div style={{ color: 'white', textAlign: 'center', marginTop: '20px' }}>No OpenCV Markups generated for this project.</div>}
              </div>
            </div>
          </div>
        )}
        <h3 style={{ fontSize: '1.3rem', fontWeight: 800, marginBottom: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span>{isArabic ? '4. مراجعة وتأكيد المقاسات المستخرجة' : '4. Confirm & Verify Extracted Parameters'}</span>
          <button 
            type="button"
            onClick={() => setMarkupImage('show')}
            style={{ fontSize: '0.9rem', background: '#3b82f6', color: 'white', padding: '6px 12px', borderRadius: '4px', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '5px' }}
          >
            👁️ {isArabic ? 'عرض التلوين التلقائي' : 'View CV Takeoffs'}
          </button>
        </h3>
      <div style={{ padding: '15px 20px', backgroundColor: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)', borderRadius: '8px', display: 'flex', alignItems: 'flex-start', gap: '12px', marginBottom: '25px', textAlign: isArabic ? 'right' : 'left' }}>
        <div style={{ color: '#3b82f6', marginTop: '2px' }}><Info size={20} /></div>
        <div>
          <h4 style={{ fontWeight: 700, color: 'var(--text-primary)', marginBottom: '4px', fontSize: '0.95rem' }}>
            {isArabic ? 'ما المطلوب في هذه الخطوة؟' : 'What to do in this step?'}
          </h4>
          <p style={{ color: 'var(--text-secondary)', fontSize: '0.85rem', margin: 0, lineHeight: '1.5' }}>
            {isArabic 
              ? 'يرجى تدقيق القيم التي استخرجها الذكاء الاصطناعي وتعديل أي قيم غير دقيقة قبل حساب جداول الحصر النهائي. إذا كانت هناك قيم مفقودة يمكنك إضافتها يدوياً عبر محرر الجداول.'
              : 'Inspect the parameters extracted by AI. Correct any dimensions before running engineering calculations. If there are missing values, you can use the Schedules Editor to add them manually.'}
          </p>
        </div>
      </div>

        {/* Failed Extractions Warnings */}
        {extractionResults && Object.values(extractionResults).filter(res => res._ok === false).length > 0 && (
          <div style={{ backgroundColor: '#fff1f2', borderLeft: '4px solid #e11d48', padding: '15px', marginBottom: '20px', borderRadius: '4px', boxShadow: 'var(--shadow-sm)' }}>
            <h4 style={{ color: '#be123c', fontSize: '1rem', fontWeight: 700, marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              🚨 {isArabic ? 'تنبيه: انخفاض جودة بعض المخططات' : 'Alert: Low Clarity on Some Pages'}
            </h4>
            <p style={{ margin: '0 0 10px 0', color: '#9f1239', fontSize: '0.9rem' }}>
              {isArabic 
                ? 'لم يتمكن الذكاء الاصطناعي من قراءة الجداول من بعض المستندات. يمكنك الآن استخدام "محرر الجداول الهندسية" بالأسفل لإدخالها يدوياً بسهولة كبديل للبرامج المعقدة.'
                : 'The AI could not clearly read the schedules from some documents. You can now use the "Schedules Editor" below to easily input them manually instead of relying on external software.'}
            </p>
            <ul style={{ margin: 0, paddingLeft: '20px', color: '#881337', fontSize: '0.9rem', fontWeight: 500 }}>
              {Object.values(extractionResults).filter(res => res._ok === false).map((res, i) => (
                <li key={i} style={{ marginBottom: '6px' }}>
                  <strong>{res.detected_type || 'Unknown'} (Page {res.page_num || '?'})</strong>: {res._error || 'Unreadable format or missing tables.'}
                </li>
              ))}
            </ul>
          </div>
        )}


        {sanityWarnings && sanityWarnings.length > 0 && (
          <div style={{ backgroundColor: '#fee2e2', borderLeft: '4px solid #ef4444', padding: '15px', marginBottom: '20px', borderRadius: '4px' }}>
            <h4 style={{ color: '#b91c1c', fontSize: '1rem', fontWeight: 700, marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              ⚠️ {isArabic ? 'تحذيرات هندسية' : 'Engineering Warnings'}
            </h4>
            <ul style={{ margin: 0, paddingLeft: '20px', color: '#991b1b', fontSize: '0.9rem' }}>
              {sanityWarnings.map((warn, i) => (
                <li key={i} style={{ marginBottom: '4px' }}>{warn}</li>
              ))}
            </ul>
          </div>
        )}

        <form onSubmit={handleConfirmDataSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
          {/* Form Grid */}
          <div className="grid-cols-3" style={{ gap: '15px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'أطول طول للمبنى (متر)' : 'Longest Footprint Length (m)'}
                {renderSourceBadge('longest_length')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.longest_length ?? ''}
                onChange={(e) => updateConfirmedField('longest_length', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'أطول عرض للمبنى (متر)' : 'Longest Footprint Width (m)'}
                {renderSourceBadge('longest_width')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.longest_width ?? ''}
                onChange={(e) => updateConfirmedField('longest_width', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'مساحة الأرض (متر مربع)' : 'Plot Area (m²)'}
                {renderSourceBadge('plot_area')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.plot_area ?? ''}
                onChange={(e) => updateConfirmedField('plot_area', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'مساحة الدور الأرضي (متر مربع)' : 'Ground Floor Built Area (m²)'}
                {renderSourceBadge('gf_area')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.gf_area ?? ''}
                onChange={(e) => updateConfirmedField('gf_area', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'ارتفاع الدور الأرضي (متر)' : 'GF Height (m)'}
                {renderSourceBadge('gf_height')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.gf_height ?? 4.2}
                onChange={(e) => updateConfirmedField('gf_height', parseFloat(e.target.value) || 0)}
              />
            </div>
            {calcParams.num_floors >= 2 && (
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'ارتفاع الدور الأول (متر)' : '1F Height (m)'}
                {renderSourceBadge('f1_height')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.f1_height ?? 3.7}
                onChange={(e) => updateConfirmedField('f1_height', parseFloat(e.target.value) || 0)}
              />
            </div>
            )}
            {calcParams.num_floors >= 3 && (
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'ارتفاع الدور الثاني (متر)' : '2F Height (m)'}
                {renderSourceBadge('f2_height')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.f2_height ?? 3.7}
                onChange={(e) => updateConfirmedField('f2_height', parseFloat(e.target.value) || 0)}
              />
            </div>
            )}
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'المحيط الخارجي للمبنى (متر)' : 'External Perimeter (m)'}
                {renderSourceBadge('ext_perimeter')}
              </label>
                <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.ext_perimeter ?? ''}
                onChange={(e) => updateConfirmedField('ext_perimeter', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'الجدران الداخلية 20 سم (متر)' : 'Internal Walls 20cm Length (m)'}
                {renderSourceBadge('int_walls_20cm_m')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.int_walls_20cm_m ?? ''}
                onChange={(e) => updateConfirmedField('int_walls_20cm_m', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'الجدران الداخلية 10 سم (متر)' : 'Internal Walls 10cm Length (m)'}
                {renderSourceBadge('int_walls_10cm_m')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.int_walls_10cm_m ?? ''}
                onChange={(e) => updateConfirmedField('int_walls_10cm_m', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'محيط السقف (متر)' : 'Roof Perimeter (m)'}
                {renderSourceBadge('roof_perimeter')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.roof_perimeter ?? ''}
                onChange={(e) => updateConfirmedField('roof_perimeter', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'مساحة السقف (متر مربع)' : 'Roof Slab Area (m²)'}
                {renderSourceBadge('roof_slab_area')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.roof_slab_area ?? ''}
                onChange={(e) => updateConfirmedField('roof_slab_area', parseFloat(e.target.value) || 0)}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'طول السور الخارجي (متر)' : 'Compound Wall Length (m)'}
                {confirmedData.compound_length_is_estimated && <span style={{ color: '#d97706', fontSize: '0.75rem', marginLeft: '5px' }}>{isArabic ? ' (تقديري)' : ' (Estimated)'}</span>}
                {renderSourceBadge('compound_length')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.compound_length ?? ''}
                onChange={(e) => updateConfirmedField('compound_length', parseFloat(e.target.value) || 0)}
                style={confirmedData.compound_length_is_estimated ? { borderColor: '#f59e0b', backgroundColor: '#fffbeb' } : {}}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'إجمالي عدد الأبواب' : 'Total Door Count (Nr)'}
                {confirmedData.openings?.totals?.door_count_is_estimated && <span style={{ color: '#d97706', fontSize: '0.75rem', marginLeft: '5px' }}>{isArabic ? ' (تقديري)' : ' (Estimated)'}</span>}
                {renderSourceBadge('door_count')}
              </label>
              <input
                type="number" step="1" className="form-input" required
                value={confirmedData.openings?.totals?.door_count ?? ''}
                onChange={(e) => updateOpeningField('door_count', parseInt(e.target.value) || 0)}
                style={confirmedData.openings?.totals?.door_count_is_estimated ? { borderColor: '#f59e0b', backgroundColor: '#fffbeb' } : {}}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                {isArabic ? 'إجمالي مساحة النوافذ (متر مربع)' : 'Total Window Area (m²)'}
                {confirmedData.openings?.totals?.window_area_is_estimated && <span style={{ color: '#d97706', fontSize: '0.75rem', marginLeft: '5px' }}>{isArabic ? ' (تقديري)' : ' (Estimated)'}</span>}
                {renderSourceBadge('window_area')}
              </label>
              <input
                type="number" step="0.01" className="form-input" required
                value={confirmedData.openings?.totals?.window_area ?? ''}
                onChange={(e) => updateOpeningField('window_area', parseFloat(e.target.value) || 0)}
                style={confirmedData.openings?.totals?.window_area_is_estimated ? { borderColor: '#f59e0b', backgroundColor: '#fffbeb' } : {}}
              />
            </div>
          </div>

          {/* Per-type Doors & Windows breakdown (count + area each) */}
          {(confirmedData.openings?.windows?.length > 0 || confirmedData.openings?.doors?.length > 0) && (
            <div style={{ marginTop: '10px', background: 'rgba(15,23,42,0.03)', border: '1px solid var(--border-color)', borderRadius: '8px', padding: '16px', textAlign: isArabic ? 'right' : 'left' }}>
              <h4 style={{ fontSize: '1rem', fontWeight: 700, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                🪟 {isArabic ? 'تفصيل النوافذ والأبواب (لكل نوع)' : 'Windows & Doors Breakdown (per type)'}
                {confirmedData.openings?._source === 'vector_text' && (
                  <span style={{ fontSize: '0.7rem', background: '#dcfce7', color: '#166534', padding: '2px 8px', borderRadius: '10px', fontWeight: 600 }}>
                    {isArabic ? '✓ قراءة دقيقة من المخطط' : '✓ Read from drawing'}
                  </span>
                )}
                {confirmedData.openings?._needs_size_review && (
                  <span style={{ fontSize: '0.7rem', background: '#fef3c7', color: '#b45309', padding: '2px 8px', borderRadius: '10px', fontWeight: 600 }}>
                    {isArabic ? '⚠ بعض المقاسات تحتاج مراجعة' : '⚠ Some sizes need review'}
                  </span>
                )}
              </h4>

              {confirmedData.openings?.windows?.length > 0 && (
                <div style={{ marginBottom: '18px', overflowX: 'auto' }}>
                  <div style={{ fontWeight: 600, fontSize: '0.85rem', marginBottom: '6px', color: 'var(--text-secondary)' }}>{isArabic ? 'النوافذ' : 'Windows'}</div>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
                    <thead>
                      <tr style={{ borderBottom: '1px solid var(--border-color)' }}>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'الرمز' : 'Mark'}</th>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'المقاس (عرض×ارتفاع)' : 'Size (W×H)'}</th>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'العدد' : 'Count'}</th>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'المساحة (م²)' : 'Area (m²)'}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {confirmedData.openings.windows.map((w, i) => {
                        const wm = Number(w.width_m ?? w.width ?? 0);
                        const hm = Number(w.height_m ?? w.height ?? 0);
                        const c = Number(w.count ?? w.count_in_plans ?? 0);
                        return (
                          <tr key={i} style={{ borderBottom: '1px solid rgba(148,163,184,0.25)' }}>
                            <td style={{ padding: '5px 4px', fontWeight: 600 }}>{w.mark || `W${i + 1}`}</td>
                            <td style={{ padding: '5px 4px' }}>
                              {(wm > 0 && hm > 0) ? `${wm.toFixed(2)} × ${hm.toFixed(2)}` : (isArabic ? '— أدخل المقاس' : '— enter size')}
                              {(wm <= 0 || hm <= 0) && (
                                <span title={isArabic ? 'تعذّر قراءة المقاس — يُرجى إدخاله' : 'size could not be read — please enter it'} style={{ color: '#d97706', marginInlineStart: '5px' }}>⚠</span>
                              )}
                              {w.size_source === 'vision' && wm > 0 && hm > 0 && (
                                <span title={isArabic ? 'مقاس مقروء بصرياً من الجدول — يُفضّل التأكد' : 'size read visually from the schedule — best to verify'} style={{ color: '#3b82f6', marginInlineStart: '5px', fontSize: '0.7rem' }}>📷</span>
                              )}
                            </td>
                            <td style={{ padding: '5px 4px' }}>{c}</td>
                            <td style={{ padding: '5px 4px' }}>{(wm * hm * c).toFixed(2)}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                    <tfoot>
                      <tr style={{ borderTop: '2px solid var(--border-color)', fontWeight: 700 }}>
                        <td colSpan={3} style={{ padding: '6px 4px' }}>{isArabic ? 'إجمالي مساحة النوافذ' : 'Total Window Area'}</td>
                        <td style={{ padding: '6px 4px' }}>
                          {confirmedData.openings.windows.reduce((s, w) => s + Number(w.width_m ?? w.width ?? 0) * Number(w.height_m ?? w.height ?? 0) * Number(w.count ?? w.count_in_plans ?? 0), 0).toFixed(2)} m²
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              )}

              {confirmedData.openings?.doors?.length > 0 && (
                <div style={{ overflowX: 'auto' }}>
                  <div style={{ fontWeight: 600, fontSize: '0.85rem', marginBottom: '6px', color: 'var(--text-secondary)' }}>{isArabic ? 'الأبواب' : 'Doors'}</div>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
                    <thead>
                      <tr style={{ borderBottom: '1px solid var(--border-color)' }}>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'الرمز' : 'Mark'}</th>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'المقاس (عرض×ارتفاع)' : 'Size (W×H)'}</th>
                        <th style={{ padding: '6px 4px' }}>{isArabic ? 'العدد' : 'Count'}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {confirmedData.openings.doors.map((d, i) => {
                        const wm = Number(d.width_m ?? d.width ?? 0);
                        const hm = Number(d.height_m ?? d.height ?? 0);
                        const c = Number(d.count ?? d.count_in_plans ?? 0);
                        return (
                          <tr key={i} style={{ borderBottom: '1px solid rgba(148,163,184,0.25)' }}>
                            <td style={{ padding: '5px 4px', fontWeight: 600 }}>{d.mark || `D${i + 1}`}</td>
                            <td style={{ padding: '5px 4px' }}>{wm > 0 ? `${wm.toFixed(2)} × ${hm.toFixed(2)}` : '—'}</td>
                            <td style={{ padding: '5px 4px' }}>{c}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                    <tfoot>
                      <tr style={{ borderTop: '2px solid var(--border-color)', fontWeight: 700 }}>
                        <td colSpan={2} style={{ padding: '6px 4px' }}>{isArabic ? 'إجمالي عدد الأبواب' : 'Total Door Count'}</td>
                        <td style={{ padding: '6px 4px' }}>
                          {confirmedData.openings.doors.reduce((s, d) => s + Number(d.count ?? d.count_in_plans ?? 0), 0)} {isArabic ? 'باب' : 'Nr'}
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              )}
            </div>
          )}

          {/* Table Editor Button & Modal */}
          <div style={{ marginTop: '15px' }}>
            <button
              type="button"
              onClick={() => setShowTableEditor(true)}
              style={{ background: '#3b82f6', color: 'white', border: 'none', padding: '10px 20px', borderRadius: '6px', fontSize: '0.95rem', cursor: 'pointer', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '8px', boxShadow: '0 4px 6px rgba(59, 130, 246, 0.3)' }}
            >
              📝 {isArabic ? 'محرر الجداول الهندسية (بديل الإدخال اليدوي)' : 'Engineering Schedules Editor (Manual Input)'}
            </button>
            <p style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '8px' }}>
              {isArabic ? 'استخدم هذا المحرر لإدخال جداول القواعد والأعمدة إذا فشل الذكاء الاصطناعي في التعرف عليها بدلاً من الاعتماد على الفرضيات.' : 'Use this editor to manually input footings and columns if AI extraction failed, instead of relying on assumptions.'}
            </p>
          </div>

          {showTableEditor && (
            <ScheduleTableEditorModal
              isArabic={isArabic}
              schedules={confirmedData.schedules}
              onClose={() => setShowTableEditor(false)}
              onSave={(newSchedules) => {
                updateConfirmedField('schedules', newSchedules);
                setShowTableEditor(false);
              }}
            />
          )}

          {/* Engineering Assumptions Section */}
          <div style={{ marginTop: '20px', borderTop: '1px solid #e5e7eb', paddingTop: '20px' }}>
            <h4 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              ⚙️ {isArabic ? 'الافتراضات الهندسية (أبعاد ونسب تقديرية قابلة للتعديل)' : 'Engineering Assumptions & Estimators (Editable)'}
            </h4>
            <div className="grid-cols-2" style={{ gap: '15px' }}>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'عمق الحفر الافتراضي (متر)' : 'Default Excavation Depth (m)'}
                  {renderSourceBadge('excavation_depth')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.excavation_depth ?? 1.25}
                  onChange={(e) => updateConfirmedField('excavation_depth', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'سماكة خرسانة الأرضية (متر)' : 'Slab on Grade Thickness (m)'}
                  {renderSourceBadge('sog_thickness')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.sog_thickness ?? 0.10}
                  onChange={(e) => updateConfirmedField('sog_thickness', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'ارتفاع الفيلا الكلي (متر)' : 'Total Villa Height (m)'}
                  {renderSourceBadge('total_villa_height')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.total_villa_height ?? ''}
                  onChange={(e) => updateConfirmedField('total_villa_height', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'ارتفاع رقاب الأعمدة (متر)' : 'Neck Column Height (m)'}
                  {renderSourceBadge('neck_column_height')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.neck_column_height ?? 1.0}
                  onChange={(e) => updateConfirmedField('neck_column_height', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'ارتفاع الطابوق المصمت تحت الميدة (متر)' : 'Solid Block Work Height (m)'}
                  {renderSourceBadge('solid_block_height')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.solid_block_height ?? 1.0}
                  onChange={(e) => updateConfirmedField('solid_block_height', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'حجم خرسانة الدرج لكل دور (م³)' : 'Staircase Concrete Volume per Floor (m³)'}
                  {renderSourceBadge('staircase_volume_per_level')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.staircase_volume_per_level ?? 5.2}
                  onChange={(e) => updateConfirmedField('staircase_volume_per_level', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'متوسط طول العمود الافتراضي (متر)' : 'Default Column Length (m)'}
                  {renderSourceBadge('default_col_length')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.default_col_length ?? 0.60}
                  onChange={(e) => updateConfirmedField('default_col_length', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '6px', fontSize: '0.85rem', fontWeight: 600 }}>
                  {isArabic ? 'متوسط عرض العمود الافتراضي (متر)' : 'Default Column Width (m)'}
                  {renderSourceBadge('default_col_width')}
                </label>
                <input
                  type="number" step="0.01" className="form-input" required
                  value={confirmedData.default_col_width ?? 0.20}
                  onChange={(e) => updateConfirmedField('default_col_width', parseFloat(e.target.value) || 0)}
                />
              </div>
            </div>
          </div>

          {hasEstimates ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginTop: '10px' }}>
              <div style={{
                padding: '12px',
                backgroundColor: '#fffbeb',
                border: '1px solid #fde68a',
                borderRadius: '6px',
                color: '#b45309',
                fontSize: '0.85rem',
                display: 'flex',
                alignItems: 'center',
                gap: '8px'
              }}>
                <span>⚠️</span>
                <span>
                  {isArabic 
                    ? 'تم تقدير بعض القيم المميزة باللون الأصفر تلقائياً بناءً على قواعد هندسية تقريبية لعدم توفرها بالملفات. يرجى مراجعتها وتأكيدها.' 
                    : 'Some values highlighted in yellow have been estimated using standard QS heuristic rules because they were not found in the uploaded documents. Please review and confirm.'}
                </span>
              </div>
              
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '10px',
                padding: '12px',
                backgroundColor: '#eff6ff',
                border: '1px solid #bfdbfe',
                borderRadius: '6px'
              }}>
                <input
                  type="checkbox"
                  id="ack-estimates"
                  checked={acknowledgedEstimates}
                  onChange={(e) => setAcknowledgedEstimates(e.target.checked)}
                  style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                />
                <label htmlFor="ack-estimates" style={{ fontSize: '0.9rem', color: '#1e40af', cursor: 'pointer', fontWeight: 600 }}>
                  {isArabic 
                    ? 'أقر بصحة هذه التقديرات أو قمت بتعديلها يدوياً للمطابقة.' 
                    : 'I verify these estimated values are correct or I have manually adjusted them.'}
                </label>
              </div>
            </div>
          ) : null}

          <button 
            type="submit" 
            className="btn btn-primary" 
            style={{ width: '100%', marginTop: '15px', padding: '12px' }} 
            disabled={loading || (hasEstimates && !acknowledgedEstimates)}
          >
            {loading ? (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                <div className="spin-anim" style={{ width: '16px', height: '16px', border: '2px solid white', borderTopColor: 'transparent', borderRadius: '50%' }}></div>
                <span>{isArabic ? 'جاري الحفظ والانتقال...' : 'Saving & Proceeding...'}</span>
              </div>
            ) : (
              isArabic ? 'تأكيد البيانات والانتقال لحساب الكميات' : 'Confirm Data & Open Calculations Panel'
            )}
          </button>
        </form>
      </div>
    );
  }

  if (currentStep === 5) {
    return (
      <div className="glass-panel" style={{ padding: '30px', maxWidth: '700px', margin: '0 auto' }}>
        <h3 style={{ fontSize: '1.3rem', fontWeight: 800, marginBottom: '8px' }}>
          {isArabic ? '5. إعدادات حساب كميات الهيكل الإنشائي والتشطيبات' : '5. Structural & Finishes Calculation Settings'}
        </h3>
        <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', marginBottom: '25px' }}>
          {isArabic 
            ? 'اضبط إعدادات الارتفاع وعدد الأدوار لتشغيل محرك الحسابات الهندسية.'
            : 'Adjust the height values, floor layers, and excavation depths to compute the takeoff sheet.'}
        </p>

        <form onSubmit={handleRunCalculation} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
          <div className="grid-cols-2" style={{ gap: '20px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'عدد الأدوار الإجمالي' : 'Number of Villa Floors'}
              </label>
              <select 
                className="form-input"
                value={calcParams.num_floors}
                onChange={(e) => setCalcParams({ ...calcParams, num_floors: parseInt(e.target.value) || 2 })}
              >
                <option value={1}>{isArabic ? 'دور واحد (أرضي فقط)' : '1 Floor (Ground Only)'}</option>
                <option value={2}>{isArabic ? 'دورين (أرضي + أول)' : '2 Floors (Ground + 1st)'}</option>
                <option value={3}>{isArabic ? '3 أدوار (أرضي + أول + ثاني)' : '3 Floors (Ground + 1st + 2nd)'}</option>
              </select>
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'عمق الحفر الافتراضي (متر)' : 'Default Soil Excavation Depth (m)'}
              </label>
              <input
                type="number" step="0.05" className="form-input" required
                value={calcParams.excavation_depth}
                onChange={(e) => setCalcParams({ ...calcParams, excavation_depth: parseFloat(e.target.value) || 1.25 })}
              />
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'ارتفاع الدور الأرضي (متر)' : 'Ground Floor Height (m)'}
              </label>
              <input
                type="number" step="0.1" className="form-input" required
                value={calcParams.gf_height}
                onChange={(e) => setCalcParams({ ...calcParams, gf_height: parseFloat(e.target.value) || 4.0 })}
              />
            </div>

            {calcParams.num_floors >= 2 && (
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                  {isArabic ? 'ارتفاع الدور الأول (متر)' : '1st Floor Height (m)'}
                </label>
                <input
                  type="number" step="0.1" className="form-input" required
                  value={calcParams.f1_height}
                  onChange={(e) => setCalcParams({ ...calcParams, f1_height: parseFloat(e.target.value) || 4.0 })}
                />
              </div>
            )}

            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'درجة الخرسانة الهيكلية' : 'Structural Concrete Grade'}
              </label>
              <select 
                className="form-input"
                value={calcParams.concrete_grade || 'C30/37'}
                onChange={(e) => setCalcParams({ ...calcParams, concrete_grade: e.target.value })}
              >
                <option value="C20/25">C20/25</option>
                <option value="C30/37">C30/37</option>
                <option value="C35/45">C35/45</option>
                <option value="C40/50">C40/50</option>
              </select>
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'سماكة البلوك المصمت (تحت الأرض)' : 'Substructure Solid Block'}
              </label>
              <select 
                className="form-input"
                value={calcParams.solid_block_thickness || '200mm'}
                onChange={(e) => setCalcParams({ ...calcParams, solid_block_thickness: e.target.value })}
              >
                <option value="150mm">150 mm (6")</option>
                <option value="200mm">200 mm (8")</option>
                <option value="250mm">250 mm (10")</option>
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'سماكة البلوك المعزول (خارجي)' : 'External Thermal Block'}
              </label>
              <select 
                className="form-input"
                value={calcParams.thermal_block_thickness || '200mm'}
                onChange={(e) => setCalcParams({ ...calcParams, thermal_block_thickness: e.target.value })}
              >
                <option value="150mm">150 mm (6")</option>
                <option value="200mm">200 mm (8")</option>
                <option value="250mm">250 mm (10")</option>
              </select>
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', fontWeight: 600 }}>
                {isArabic ? 'سماكة البلوك المفرغ (داخلي)' : 'Internal Hollow Block'}
              </label>
              <select 
                className="form-input"
                value={calcParams.hollow_block_thickness || '100mm'}
                onChange={(e) => setCalcParams({ ...calcParams, hollow_block_thickness: e.target.value })}
              >
                <option value="100mm">100 mm (4")</option>
                <option value="150mm">150 mm (6")</option>
                <option value="200mm">200 mm (8")</option>
              </select>
            </div>
          </div>

          {/* Roof stair-room control for the top floor (auto-detected, editable) */}
          {calcParams.num_floors >= 2 && (
            <div style={{ marginTop: '10px', background: 'rgba(15,23,42,0.03)', border: '1px solid var(--border-color)', borderRadius: '8px', padding: '14px', textAlign: isArabic ? 'right' : 'left' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', fontWeight: 600 }}>
                <input
                  type="checkbox"
                  checked={!!calcParams.top_floor_is_stair_room}
                  onChange={(e) => setCalcParams({ ...calcParams, top_floor_is_stair_room: e.target.checked })}
                  style={{ width: '18px', height: '18px' }}
                />
                {isArabic ? 'الدور العلوي غرفة درج سطح فقط (ليس دوراً كاملاً)' : 'Top floor is a roof stair-room only (not a full floor)'}
                {calcParams.top_floor_is_stair_room && (
                  <span style={{ fontSize: '0.7rem', background: '#dcfce7', color: '#166534', padding: '2px 8px', borderRadius: '10px' }}>
                    {isArabic ? 'مكتشف تلقائياً' : 'auto-detected'}
                  </span>
                )}
              </label>
              <p style={{ fontSize: '0.78rem', color: 'var(--text-secondary)', margin: '6px 26px 0' }}>
                {isArabic
                  ? 'فعّله إذا كان الدور العلوي سطحاً مفتوحاً بغرفة درج فقط — فتُحسب التشطيبات من الغرفة لا من المبنى كله (يصحّح تضخّم البلوك واللياسة).'
                  : 'Enable if the top level is an open roof with only a staircase room — finishes are then computed from that small room, not the whole building.'}
              </p>
              {calcParams.top_floor_is_stair_room && (
                <div className="grid-cols-2" style={{ gap: '12px', marginTop: '10px' }}>
                  <div>
                    <label style={{ display: 'block', marginBottom: '4px', fontSize: '0.82rem', fontWeight: 600 }}>{isArabic ? 'مساحة غرفة الدرج (م²)' : 'Stair-room area (m²)'}</label>
                    <input type="number" step="0.1" className="form-input" placeholder={isArabic ? 'تلقائي' : 'auto'}
                      value={calcParams.stair_room_area} onChange={(e) => setCalcParams({ ...calcParams, stair_room_area: e.target.value })} />
                  </div>
                  <div>
                    <label style={{ display: 'block', marginBottom: '4px', fontSize: '0.82rem', fontWeight: 600 }}>{isArabic ? 'محيط غرفة الدرج (م)' : 'Stair-room perimeter (m)'}</label>
                    <input type="number" step="0.1" className="form-input" placeholder={isArabic ? 'تلقائي' : 'auto'}
                      value={calcParams.stair_room_perimeter} onChange={(e) => setCalcParams({ ...calcParams, stair_room_perimeter: e.target.value })} />
                  </div>
                </div>
              )}
            </div>
          )}

          <div style={{ marginTop: '10px' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', fontWeight: 600 }}>
              <input
                type="checkbox"
                checked={calcParams.include_road_base}
                onChange={(e) => setCalcParams({ ...calcParams, include_road_base: e.target.checked })}
                style={{ width: '18px', height: '18px' }}
              />
              {isArabic ? 'تضمين طبقة تحت الأساسات (Road Base)' : 'Include Sub-Structure Road Base Layer'}
            </label>
          </div>

          <button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '10px', padding: '12px' }} disabled={loading}>
            {loading ? (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                <div className="spin-anim" style={{ width: '16px', height: '16px', border: '2px solid white', borderTopColor: 'transparent', borderRadius: '50%' }}></div>
                <span>{isArabic ? 'جاري حساب الكميات بالمعادلات الهندسية...' : 'Calculating concrete volumes...'}</span>
              </div>
            ) : (
              isArabic ? 'تشغيل حساب كميات الهيكل والتشطيبات' : 'Calculate & Generate Takeoff Bill'
            )}
          </button>
        </form>
      </div>
    );
  }

  return null;
}