// Completion.jsx
// Time options for the End-time dropdown — hourly only (no half-hours), 6am–10pm.
const COMPLETION_TIME_OPTS = (() => {
  const out = [];
  for (let h = 6; h <= 22; h++) out.push(`${String(h).padStart(2, '0')}:00`);
  return out;
})();

// Mock GPS fix written into the completion photo stamp.
const COMPLETION_GPS = { lat: '1.470892', long: '103.891765', alt: 14 };

function CompletionPage({ onSubmit, onBack, role = 'Operator', bookingId = 'BK-2026-00420' }) {
  // Operators & riggers complete jobs on a phone — render inside the device frame.
  // Office roles (Admin/Operation/Finance/Management) only view it, so they keep
  // the wide desktop card.
  const isMobile = role === 'Operator' || role === 'Rigger';
  // Pull the live booking so company, location and scheduled times all flow
  // from how the booking was created — no hand-typed values.
  const booking = (typeof BOOKINGS !== 'undefined' && BOOKINGS.find(b => b.id === bookingId)) || {
    id: bookingId, customer: 'Ace Engineering', location: 'Pasir Gudang Industrial Park, Lot 14B',
    start: '08:00', end: '17:00', contact: 'Lim Wei Ming', machine: 'PLC-005 Tadano GR-500EX', tonnage: '50t',
  };

  const canvasRef = React.useRef(null);
  const [drawing, setDrawing] = React.useState(false);
  const [hasSig, setHasSig] = React.useState(false);
  const [photo, setPhoto] = React.useState(null);
  // WhatsApp "PDF to sign" share flow. stage: 'gen' (building PDF) → 'ready' (attached) → 'sent'.
  const [waOpen, setWaOpen] = React.useState(false);
  const [waStage, setWaStage] = React.useState('gen');

  // Start time follows the booking and is NOT editable. End time is hourly.
  const [endTime, setEndTime] = React.useState(booking.end || '17:00');
  // Overtime is itemised by source. lunch = worked through 12–1pm; after5 = hours past 5pm.
  const [lunchOT, setLunchOT] = React.useState('no');   // 'no' | 'yes' (1 hr)
  // Overtime after 5pm is DERIVED from the selected End Time — never hand-entered.
  // Any hour past 17:00 counts; e.g. 7pm end → 2 hrs OT.
  const after5OT = Math.max(0, Number((endTime || '17:00').split(':')[0]) - 17);
  const after5Label = after5OT === 0 ? 'None' : `${after5OT} hr${after5OT > 1 ? 's' : ''}`;

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * dpr;
    canvas.height = canvas.offsetHeight * dpr;
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.lineWidth = 2.5;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#0B1F3A';
  }, []);

  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    const t = e.touches?.[0];
    return { x: (t?.clientX ?? e.clientX) - r.left, y: (t?.clientY ?? e.clientY) - r.top };
  };
  const start = (e) => { e.preventDefault(); const ctx = canvasRef.current.getContext('2d'); const p = pos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); setDrawing(true); };
  const move = (e) => { if (!drawing) return; e.preventDefault(); const ctx = canvasRef.current.getContext('2d'); const p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); setHasSig(true); };
  const end = () => setDrawing(false);
  const clear = () => { const c = canvasRef.current; const ctx = c.getContext('2d'); ctx.clearRect(0, 0, c.width, c.height); setHasSig(false); };

  const fmtHM = (t) => { const [h, m] = (t || '00:00').split(':').map(Number); const ap = h < 12 ? 'am' : 'pm'; const h12 = ((h + 11) % 12) + 1; return `${h12}${m ? ':' + String(m).padStart(2, '0') : ''}${ap}`; };
  const fmtDate = (iso) => new Date((iso || '2026-04-29') + 'T00:00:00').toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });

  // Total overtime = lunch (1 hr if worked) + hours after 5pm.
  const totalOT = (lunchOT === 'yes' ? 1 : 0) + Number(after5OT);
  const otLabel = totalOT === 0 ? 'None' : `${totalOT} hr${totalOT > 1 ? 's' : ''}`;
  const machineLabelStr = (typeof bookingMachineLabel !== 'undefined') ? bookingMachineLabel(booking) : booking.machine;

  const selectStyle = { width: '100%' };

  // ===== WhatsApp share helpers =====
  // Once the modal opens, briefly "render the signed sheet to PDF" before it appears attached.
  React.useEffect(() => {
    if (waOpen && waStage === 'gen') {
      const t = setTimeout(() => setWaStage('ready'), 1100);
      return () => clearTimeout(t);
    }
  }, [waOpen, waStage]);
  const waContact = booking.contact || booking.customer;
  const waPhone = booking.phone || '+60 12-345 6789';
  const waInitials = (booking.customer || '?').trim().split(/\s+/).map(w => w[0]).slice(0, 2).join('').toUpperCase();
  // Show the unit / body number (e.g. "9744"), not the internal fleet id (PLC-005).
  const waMachineNo = (typeof bookingMachineLabel === 'function' && bookingMachineLabel(booking))
    || (booking.machine || '').replace(/^[A-Z]+-\d+\s+/, '')
    || booking.machine || '';
  const waDate = booking.date || (typeof TODAY !== 'undefined' ? TODAY : '');
  const waPreset = `Hi ${waContact}, attached is the Job Completion sheet for ${booking.id}${waDate ? ` — ${waDate}` : ''}${waMachineNo ? `, ${waMachineNo}` : ''}, ${booking.customer} — ${booking.location}. Kindly review and sign at the signed field, then send it back to confirm. Thank you — Pow Lee Crane.\n\nSalam boss ${waContact}, disertakan helaian Penyelesaian Kerja untuk ${booking.id}${waDate ? ` — ${waDate}` : ''}${waMachineNo ? `, ${waMachineNo}` : ''}, ${booking.customer} — ${booking.location}. Mohon semak dan tandatangan pada ruang tandatangan, kemudian hantar semula untuk pengesahan. Terima kasih — Pow Lee Crane.`;
  const waLink = `https://wa.me/${waPhone.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(waPreset)}`;
  const openWhatsApp = () => { setWaStage('gen'); setWaOpen(true); };
  const DoubleTick = ({ color }) => (
    <svg width="16" height="11" viewBox="0 0 16 11" fill="none" style={{flexShrink: 0}}>
      <path d="M1 5.6 3.9 8.6 9.4 2.6" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M6.4 8.2 6.9 8.6 12.5 2.6" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );

  // The WhatsApp compose sheet — represents WhatsApp opened with the PDF attached + message pre-filled.
  const WhatsAppShareModal = waOpen ? (
    <div onClick={() => setWaOpen(false)} style={{position: 'fixed', inset: 0, background: 'rgba(11,31,58,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20}}>
      <style>{`@keyframes plcspin{to{transform:rotate(360deg)}}`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{width: '100%', maxWidth: 400, height: 600, maxHeight: '92vh', background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 24px 70px rgba(0,0,0,0.45)', display: 'flex', flexDirection: 'column'}}>
        {/* WhatsApp conversation header */}
        <div style={{background: '#075E54', color: '#fff', padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0}}>
          <div style={{width: 40, height: 40, borderRadius: '50%', background: '#25D366', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 15, flexShrink: 0}}>{waInitials}</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{waContact}</div>
            <div style={{fontSize: 12, opacity: 0.85}}>{waPhone}</div>
          </div>
          <button type="button" onClick={() => setWaOpen(false)} style={{width: 34, height: 34, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 8, background: 'rgba(255,255,255,0.14)', color: '#fff', border: 'none', cursor: 'pointer'}}><X size={18}/></button>
        </div>

        {/* Chat area */}
        <div style={{flex: 1, overflowY: 'auto', padding: '18px 14px', background: '#ECE5DD', backgroundImage: 'radial-gradient(rgba(0,0,0,0.045) 1px, transparent 1px)', backgroundSize: '18px 18px', display: 'flex', flexDirection: 'column', gap: 8}}>
          <div style={{alignSelf: 'center', background: 'rgba(255,255,255,0.85)', color: '#54656f', fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 8}}>Today</div>

          {waStage === 'gen' ? (
            <div style={{alignSelf: 'flex-end', display: 'flex', alignItems: 'center', gap: 10, background: '#DCF8C6', borderRadius: '10px 10px 2px 10px', padding: '12px 14px', boxShadow: '0 1px 1px rgba(0,0,0,0.12)'}}>
              <span style={{width: 16, height: 16, border: '2px solid #9bbf88', borderTopColor: '#1c7a44', borderRadius: '50%', display: 'inline-block', animation: 'plcspin 0.7s linear infinite'}}/>
              <span style={{fontSize: 13, color: '#3d5247', fontWeight: 600}}>Generating signed PDF…</span>
            </div>
          ) : (
            <div style={{alignSelf: 'flex-end', maxWidth: '86%', background: '#DCF8C6', borderRadius: '10px 10px 2px 10px', padding: 7, boxShadow: '0 1px 1px rgba(0,0,0,0.12)'}}>
              <div style={{display: 'flex', alignItems: 'center', gap: 10, background: '#c9ecae', borderRadius: 8, padding: '10px 12px'}}>
                <div style={{width: 34, height: 42, borderRadius: 4, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#d3463a', flexShrink: 0}}><FileText size={20}/></div>
                <div style={{minWidth: 0}}>
                  <div style={{fontSize: 13, fontWeight: 700, color: '#0b1f3a', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>Job Completion {booking.id} — {waDate} — {booking.customer} — {booking.location}.pdf</div>
                  <div style={{fontSize: 11, color: '#4a5b52', marginTop: 1}}>1 page · PDF · 248 KB</div>
                </div>
              </div>
              <div style={{fontSize: 13.5, color: '#0b1f3a', lineHeight: 1.45, padding: '8px 5px 2px', whiteSpace: 'pre-line'}}>{waPreset}</div>
              <div style={{display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 4, fontSize: 10.5, color: '#667781', paddingRight: 2}}>
                <span>9:41 am</span>
                <DoubleTick color={waStage === 'sent' ? '#53bdeb' : '#8aa0ad'}/>
              </div>
            </div>
          )}

          {waStage === 'sent' && (
            <div style={{alignSelf: 'center', marginTop: 6, background: '#d8f3c4', border: '1px solid #b6dfa0', color: '#1c7a44', fontSize: 12, fontWeight: 700, padding: '6px 12px', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 6}}>
              <Check size={14}/> Sent to {booking.customer}
            </div>
          )}
        </div>

        {/* Compose / action bar */}
        {waStage !== 'sent' ? (
          <div style={{padding: '12px 14px', background: '#f0f2f5', display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0}}>
            <div style={{flex: 1, background: '#fff', borderRadius: 22, padding: '11px 16px', fontSize: 13, color: '#54656f', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>
              {waStage === 'gen' ? 'Attaching PDF…' : 'Message ready — tap to send'}
            </div>
            <button type="button" disabled={waStage !== 'ready'} onClick={() => setWaStage('sent')}
              style={{width: 48, height: 48, borderRadius: '50%', background: waStage === 'ready' ? '#25D366' : '#a9c8b5', border: 'none', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: waStage === 'ready' ? 'pointer' : 'default', flexShrink: 0, boxShadow: waStage === 'ready' ? '0 2px 8px rgba(37,211,102,0.5)' : 'none'}}>
              <Send size={20}/>
            </button>
          </div>
        ) : (
          <div style={{padding: '12px 14px', background: '#f0f2f5', display: 'flex', gap: 10, flexShrink: 0}}>
            <button type="button" className="btn btn--ghost" style={{flex: 1, gap: 8}} onClick={() => window.open(waLink, '_blank')}><WhatsApp size={15}/> Open in WhatsApp</button>
            <button type="button" className="btn btn--primary" style={{flex: 1, gap: 8}} onClick={() => setWaOpen(false)}><Check size={15}/> Done</button>
          </div>
        )}
      </div>
    </div>
  ) : null;

  // Shared form sections so mobile + desktop stay in sync.
  const SignaturePad = (
    <div className="field full">
      <label>Customer Signature</label>
      <canvas ref={canvasRef} className="sig-pad"
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end}/>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8}}>
        <div className="field__hint">{hasSig ? 'Signature captured.' : 'Customer signs above with finger or stylus.'}</div>
        <button type="button" className="btn btn--ghost" style={{height: 32, padding: '0 12px', fontSize: 12}} onClick={clear}>Clear</button>
      </div>
    </div>
  );

  const PhotoField = (
    <div className="field full">
      <label>Completion Photo</label>
      {photo ? (
        <div style={{position: 'relative', borderRadius: 12, overflow: 'hidden', border: '1px solid var(--border-default)'}}>
          <div style={{height: 200, background: 'repeating-linear-gradient(135deg, #d8dde4 0 12px, #cfd5dd 12px 24px)', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
            <span style={{fontFamily: 'monospace', fontSize: 12, color: 'var(--color-grey-600)', background: 'rgba(255,255,255,0.7)', padding: '4px 10px', borderRadius: 6}}>completion photo</span>
          </div>
          <div style={{position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 14px', background: 'linear-gradient(transparent, rgba(0,0,0,0.82))', color: '#fff', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12}}>
            <div style={{fontFamily: 'monospace', fontSize: 11, lineHeight: 1.55}}>
              <div style={{display: 'flex', alignItems: 'center', gap: 4, color: 'var(--color-yellow)', fontWeight: 700, marginBottom: 2}}>
                <MapPin size={12}/> <span>{booking.location}</span>
              </div>
              <div>Lat {COMPLETION_GPS.lat}°&nbsp;&nbsp;·&nbsp;&nbsp;Long {COMPLETION_GPS.long}°</div>
              <div>Alt {COMPLETION_GPS.alt} m</div>
            </div>
            <div style={{fontFamily: 'monospace', fontSize: 11, lineHeight: 1.55, textAlign: 'right', flexShrink: 0}}>
              <div>{fmtDate(booking.date)}</div>
              <div style={{fontWeight: 700}}>{fmtHM(endTime)}</div>
              <div style={{opacity: 0.8}}>GMT+8</div>
            </div>
          </div>
          <button type="button" className="btn btn--ghost" onClick={() => setPhoto(null)}
            style={{position: 'absolute', top: 8, right: 8, height: 30, padding: '0 10px', fontSize: 12, background: 'rgba(255,255,255,0.92)'}}>
            <Camera size={13}/> Retake
          </button>
        </div>
      ) : (
        <div className="upload-zone" onClick={() => setPhoto('job-completed.jpg')}>
          <Camera size={24} style={{marginBottom: 8}}/>
          <div style={{fontWeight: 600, color: 'var(--color-navy)'}}>Take or upload completion photo</div>
          <div style={{fontSize: 12, marginTop: 4}}>Auto-stamped with GPS coordinates + time on capture.</div>
        </div>
      )}
    </div>
  );

  // ============ MOBILE (operator / rigger) ============
  if (isMobile) {
    return (
      <React.Fragment>
      <div className="content">
        <div className="phone-frame">
          <div className="phone-frame__inner">
            <div className="phone-status">
              <span>9:41</span>
              <span style={{display: 'flex', gap: 4, alignItems: 'center'}}>
                <Signal size={12}/> <Wifi size={12}/> <Battery size={14}/>
              </span>
            </div>

            {/* App header with back-to-job-list */}
            <div style={{background: 'var(--color-navy)', color: 'white', padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10}}>
              <button type="button" onClick={() => onBack && onBack()}
                style={{width: 34, height: 34, flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 9, background: 'rgba(255,255,255,0.12)', color: 'white', border: 'none', cursor: 'pointer'}}>
                <ChevLeft size={18}/>
              </button>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 10, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600}}>Job Completion</div>
                <div style={{fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{booking.customer}</div>
              </div>
              <span className="badge badge--green" style={{flexShrink: 0}}>Done</span>
            </div>

            {/* Caution band — matches the desktop completion sheet */}
            <div className="caution-stripe" style={{height: 8, flexShrink: 0}}/>

            <div className="phone-content" style={{padding: 16}}>
              {/* Booking identity */}
              <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12}}>
                <span style={{fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 700}}>{booking.id}</span>
                <span style={{fontSize: 11, color: 'var(--color-grey-600)', fontWeight: 600}}>{machineLabelStr}</span>
              </div>

              {/* Company & location — read-only */}
              <div style={{border: '1px solid var(--border-default)', borderRadius: 12, overflow: 'hidden', marginBottom: 20}}>
                {[{ label: 'Company', value: booking.customer }, { label: 'Location', value: booking.location }].map((row, i) => (
                  <div key={row.label} style={{background: 'var(--color-grey-50)', padding: '10px 12px', borderTop: i ? '1px solid var(--border-default)' : 'none'}}>
                    <div style={{fontSize: 10, color: 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700}}>{row.label}</div>
                    <div style={{fontSize: 14, fontWeight: 600, color: 'var(--color-navy)', marginTop: 2}}>{row.value}</div>
                  </div>
                ))}
              </div>

              <div style={{display: 'flex', flexDirection: 'column', gap: 18}}>
                {/* Start / End — two compact columns */}
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
                  <div className="field" style={{margin: 0}}>
                    <label>Start Time</label>
                    <input value={fmtHM(booking.start)} readOnly disabled
                      style={{background: 'var(--color-grey-50)', color: 'var(--color-grey-600)', cursor: 'not-allowed'}}/>
                    <div className="field__hint">From booking.</div>
                  </div>
                  <div className="field" style={{margin: 0}}>
                    <label>End Time</label>
                    <select value={endTime} onChange={(e) => setEndTime(e.target.value)} style={selectStyle}>
                      {COMPLETION_TIME_OPTS.map(t => <option key={t} value={t}>{fmtHM(t)}</option>)}
                    </select>
                  </div>
                </div>

                {/* Overtime — stacked for narrow width */}
                <div className="field" style={{margin: 0}}>
                  <label>Overtime</label>
                  <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                    <div>
                      <div style={{fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 600, marginBottom: 4}}>12–1pm (lunch worked)</div>
                      <select value={lunchOT} onChange={(e) => setLunchOT(e.target.value)} style={selectStyle}>
                        <option value="no">No</option>
                        <option value="yes">Yes — 1 hr</option>
                      </select>
                    </div>
                    <div>
                      <div style={{fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 600, marginBottom: 4}}>Overtime after 5pm</div>
                      <input value={after5Label} readOnly disabled
                        style={{width: '100%', background: 'var(--color-grey-50)', color: 'var(--color-grey-600)', cursor: 'not-allowed'}}/>
                      <div className="field__hint">Auto-calculated from End Time.</div>
                    </div>
                    <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', background: totalOT > 0 ? 'rgba(255,213,0,0.18)' : 'var(--color-grey-50)', border: '1px solid var(--border-default)', borderRadius: 8}}>
                      <div style={{fontSize: 10, color: totalOT > 0 ? 'var(--color-yellow-700)' : 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700}}>Total OT</div>
                      <div style={{fontSize: 18, fontWeight: 800, color: 'var(--color-navy)'}}>{otLabel}</div>
                    </div>
                  </div>
                </div>

                <div className="field" style={{margin: 0}}>
                  <label>Customer Name</label>
                  <input defaultValue={booking.contact || ''}/>
                </div>

                {SignaturePad}
                {PhotoField}

                <div className="field" style={{margin: 0}}>
                  <label>Site Remarks</label>
                  <textarea defaultValue="All 4 columns placed and verified by site engineer. No incidents."/>
                </div>
              </div>
            </div>

            {/* Sticky submit bar */}
            <div style={{flexShrink: 0, borderTop: '1px solid var(--border-default)', background: 'white', padding: 12, display: 'flex', flexDirection: 'column', gap: 10}}>
              <button type="button" className="btn btn--ghost" style={{width: '100%', height: 48, gap: 8, borderColor: '#25D366', color: '#1c7a44'}} onClick={openWhatsApp}>
                <WhatsApp size={16}/> WhatsApp PDF to Sign
              </button>
              <div style={{display: 'flex', gap: 10}}>
                <button className="btn btn--ghost" style={{height: 48}} onClick={() => onBack && onBack()}>Cancel</button>
                <button className="btn btn--primary" style={{flex: 1, height: 48, fontSize: 15, fontWeight: 700}} onClick={() => onSubmit && onSubmit()}>
                  <Check size={16}/> Submit Completion
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      {WhatsAppShareModal}
      </React.Fragment>
    );
  }

  // ============ DESKTOP (office roles — view) ============
  return (
    <React.Fragment>
    <div className="content">
      <div className="card" style={{maxWidth: 760, margin: '0 auto'}}>
        <div className="caution-stripe" style={{margin: '-24px -24px 24px', borderRadius: '12px 12px 0 0'}}/>
        <div className="card__header">
          <div>
            <div className="card__title">Job Completion · {booking.id}</div>
            <div style={{fontSize: 13, color: 'var(--color-grey-500)', marginTop: 4}}>{booking.customer} · {machineLabelStr}</div>
          </div>
          <span className="badge badge--green">Job Completed</span>
        </div>

        {/* Company & location — read-only, straight from the booking. */}
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1, background: 'var(--border-default)', border: '1px solid var(--border-default)', borderRadius: 12, overflow: 'hidden', marginBottom: 24}}>
          {[{ label: 'Company', value: booking.customer }, { label: 'Location', value: booking.location }].map((row) => (
            <div key={row.label} style={{background: 'var(--color-grey-50)', padding: '12px 14px'}}>
              <div style={{fontSize: 10, color: 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700}}>{row.label}</div>
              <div style={{fontSize: 14, fontWeight: 600, color: 'var(--color-navy)', marginTop: 3}}>{row.value}</div>
            </div>
          ))}
        </div>

        <div className="form-grid">
          {/* Start time follows the booking order — read-only. End time editable, hourly. */}
          <div className="field">
            <label>Start Time</label>
            <input value={fmtHM(booking.start)} readOnly disabled
              style={{background: 'var(--color-grey-50)', color: 'var(--color-grey-600)', cursor: 'not-allowed'}}/>
            <div className="field__hint">Follows the booking — not editable.</div>
          </div>
          <div className="field">
            <label>End Time</label>
            <select value={endTime} onChange={(e) => setEndTime(e.target.value)} style={selectStyle}>
              {COMPLETION_TIME_OPTS.map(t => <option key={t} value={t}>{fmtHM(t)}</option>)}
            </select>
          </div>

          {/* Overtime — itemised dropdowns with computed total. */}
          <div className="field full">
            <label>Overtime</label>
            <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr auto', gap: 12, alignItems: 'end'}}>
              <div>
                <div style={{fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 600, marginBottom: 4}}>12–1pm (lunch worked)</div>
                <select value={lunchOT} onChange={(e) => setLunchOT(e.target.value)} style={selectStyle}>
                  <option value="no">No</option>
                  <option value="yes">Yes — 1 hr</option>
                </select>
              </div>
              <div>
                <div style={{fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 600, marginBottom: 4}}>Overtime after 5pm</div>
                <input value={after5Label} readOnly disabled
                  style={{width: '100%', background: 'var(--color-grey-50)', color: 'var(--color-grey-600)', cursor: 'not-allowed'}}/>
                <div className="field__hint">Auto-calculated from End Time.</div>
              </div>
              <div style={{padding: '0 16px', textAlign: 'center', minWidth: 96, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'center', background: totalOT > 0 ? 'rgba(255,213,0,0.18)' : 'var(--color-grey-50)', border: '1px solid var(--border-default)', borderRadius: 8}}>
                <div style={{fontSize: 10, color: totalOT > 0 ? 'var(--color-yellow-700)' : 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700}}>Total OT</div>
                <div style={{fontSize: 18, fontWeight: 800, color: 'var(--color-navy)', marginTop: 2}}>{otLabel}</div>
              </div>
            </div>
          </div>

          <div className="field full">
            <label>Customer Name</label>
            <input defaultValue={booking.contact || ''}/>
          </div>

          <div className="field full">
            <label>Customer Signature</label>
            <canvas ref={canvasRef} className="sig-pad"
              onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
              onTouchStart={start} onTouchMove={move} onTouchEnd={end}/>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8}}>
              <div className="field__hint">{hasSig ? 'Signature captured.' : 'Customer signs above with finger or stylus.'}</div>
              <button type="button" className="btn btn--ghost" style={{height: 32, padding: '0 12px', fontSize: 12}} onClick={clear}>Clear</button>
            </div>
          </div>

          <div className="field full">
            <label>Completion Photo</label>
            {photo ? (
              // Auto-stamped on capture: GPS coordinates + date/time burned into the frame.
              <div style={{position: 'relative', borderRadius: 12, overflow: 'hidden', border: '1px solid var(--border-default)'}}>
                <div style={{height: 220, background: 'repeating-linear-gradient(135deg, #d8dde4 0 12px, #cfd5dd 12px 24px)', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                  <span style={{fontFamily: 'monospace', fontSize: 12, color: 'var(--color-grey-600)', background: 'rgba(255,255,255,0.7)', padding: '4px 10px', borderRadius: 6}}>completion photo</span>
                </div>
                <div style={{position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 14px', background: 'linear-gradient(transparent, rgba(0,0,0,0.82))', color: '#fff', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12}}>
                  <div style={{fontFamily: 'monospace', fontSize: 11, lineHeight: 1.55}}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 4, color: 'var(--color-yellow)', fontWeight: 700, marginBottom: 2}}>
                      <MapPin size={12}/> <span>{booking.location}</span>
                    </div>
                    <div>Lat {COMPLETION_GPS.lat}°&nbsp;&nbsp;·&nbsp;&nbsp;Long {COMPLETION_GPS.long}°</div>
                    <div>Alt {COMPLETION_GPS.alt} m</div>
                  </div>
                  <div style={{fontFamily: 'monospace', fontSize: 11, lineHeight: 1.55, textAlign: 'right', flexShrink: 0}}>
                    <div>{fmtDate(booking.date)}</div>
                    <div style={{fontWeight: 700}}>{fmtHM(endTime)}</div>
                    <div style={{opacity: 0.8}}>GMT+8</div>
                  </div>
                </div>
                <button type="button" className="btn btn--ghost" onClick={() => setPhoto(null)}
                  style={{position: 'absolute', top: 8, right: 8, height: 30, padding: '0 10px', fontSize: 12, background: 'rgba(255,255,255,0.92)'}}>
                  <Camera size={13}/> Retake
                </button>
              </div>
            ) : (
              <div className="upload-zone" onClick={() => setPhoto('job-completed.jpg')}>
                <Camera size={24} style={{marginBottom: 8}}/>
                <div style={{fontWeight: 600, color: 'var(--color-navy)'}}>Take or upload completion photo</div>
                <div style={{fontSize: 12, marginTop: 4}}>Auto-stamped with GPS coordinates + time on capture.</div>
              </div>
            )}
          </div>

          <div className="field full">
            <label>Site Remarks</label>
            <textarea defaultValue="All 4 columns placed and verified by site engineer. No incidents."/>
          </div>
        </div>

        <div style={{display: 'flex', gap: 12, alignItems: 'center', borderTop: '1px solid var(--border-default)', paddingTop: 24, marginTop: 24}}>
          <button type="button" className="btn btn--ghost" onClick={openWhatsApp}
            style={{gap: 8, borderColor: '#25D366', color: '#1c7a44'}}>
            <WhatsApp size={16}/> WhatsApp PDF to Sign
          </button>
          <div style={{flex: 1}}/>
          <button className="btn btn--ghost">Save Draft</button>
          <button className="btn btn--primary btn--lg" onClick={() => onSubmit && onSubmit()}>
            <Check size={16}/> Submit Completion
          </button>
        </div>
      </div>
    </div>
    {WhatsAppShareModal}
    </React.Fragment>
  );
}

Object.assign(window, { CompletionPage });
