// rwic-report.jsx — Daily Field Report (RWIC end-of-shift).
//
// RWIC-focused: employee's account of the day. Carries the briefing context
// (railroad, MP, OTS, work type). Train movements and switch handling are
// FRA-required compliance fields. Photos are minimum-4 (FRA requirement
// observed in many client SOPs).

function ScreenReport({ goTo }) {
  const { user, shift, updateShift, briefingSubmitted, reportSubmitted, submitReport, clockState, liveHrs } = useApp();

  // Local-only report state — submitted forms go to a backend; pre-fill from shift ctx
  const [r, setR] = useState({
    shiftType: 'New Shift',
    lunchTaken: 'No',
    lunchTotal: '0.00',
    hoursWorked: liveHrs ? liveHrs.toFixed(2) : '0.00',
    timetable: '8',
    bulletinNum: 'DOB-1142',
    generalOrders: 'GBO-22-08 (heat advisory)',
    contractorAttendance: 'Showed Up',
    initialBriefing: 'Yes',
    followUpBriefing: 'No',
    briefingContent: 'Safety procedures, on-track protection, PPE, critical exposures, lifesaving processes.',
    trainMovements: 'Yes',
    trainLog: [
      { id: 1, trainNum: 'Q-EVELAU-12', timeIn: '07:42', timeOut: '07:46' },
      { id: 2, trainNum: 'M-SEAPSC-14', timeIn: '10:18', timeOut: '10:23' },
    ],
    switchesHandled: 'No',
    trackDelays: 'No',
    contractorDelays: 'No',
    rulesViolations: 'No',
    photoDesc: '',
    contractorRepName: shift.foremanName || '',
    contractorRepPhone: shift.foremanPhone || '',
  });
  const set = (k, v) => setR(p => ({ ...p, [k]: v }));

  // Photos — minimum 4 with named slots
  const [photos, setPhotos] = useState([
    { slot: 'Pre-work — track view', dataUrl: null },
    { slot: 'Pre-work — workers in PPE', dataUrl: null },
    { slot: 'Mid-shift — work area', dataUrl: null },
    { slot: 'Post-work — restored track', dataUrl: null },
  ]);

  // Simulated photo capture (since real camera unavailable in preview)
  const captureSim = (idx) => {
    setPhotos(p => {
      const n = [...p];
      // generate a colored striped placeholder data URL
      const c = createCanvas(420, 280);
      const ctx = c.getContext('2d');
      const ts = new Date().toLocaleTimeString();
      const grad = ctx.createLinearGradient(0, 0, 420, 280);
      grad.addColorStop(0, '#5a4d3a'); grad.addColorStop(1, '#2a2a2a');
      ctx.fillStyle = grad; ctx.fillRect(0, 0, 420, 280);
      ctx.fillStyle = 'rgba(255,255,255,0.08)';
      for (let i = 0; i < 12; i++) ctx.fillRect(0, i * 24, 420, 12);
      ctx.fillStyle = '#fff';
      ctx.font = 'bold 16px Inter, sans-serif';
      ctx.fillText(p[idx].slot, 18, 32);
      ctx.font = '12px JetBrains Mono, monospace';
      ctx.fillStyle = 'rgba(255,255,255,0.6)';
      ctx.fillText(`MP ${shift.milepost.split('–')[0].trim()}  •  ${ts}`, 18, 260);
      ctx.fillText(`47.7128° N, 121.3525° W`, 18, 244);
      n[idx] = { ...n[idx], dataUrl: c.toDataURL('image/jpeg', 0.85) };
      return n;
    });
  };
  const clearPhoto = (idx) => setPhotos(p => { const n = [...p]; n[idx] = { ...n[idx], dataUrl: null }; return n; });
  const addPhotoSlot = () => setPhotos(p => p.length >= 10 ? p : [...p, { slot: `Photo ${p.length + 1}`, dataUrl: null }]);

  const photoCount = photos.filter(p => p.dataUrl).length;

  // Sigs
  const [contractorSig, setContractorSig] = useState(false);
  const [rwicSig, setRwicSig] = useState(false);

  const missing = [];
  if (!shift.workType) missing.push('Work description');
  if (photoCount < 4) missing.push(`${4 - photoCount} more photo${4 - photoCount === 1 ? '' : 's'}`);
  if (!rwicSig) missing.push('RWIC signature');
  if (!contractorSig) missing.push('Contractor rep signature');
  const canSubmit = missing.length === 0;

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 340px', overflow: 'hidden' }}>
      <div style={{ overflowY: 'auto', padding: '20px 28px 32px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="eyebrow">DAILY FIELD REPORT · END OF SHIFT</div>
            <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>{shift.projectName}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
              <span className="mono">{shift.projectNumber}</span> · {shift.subdivision} · MP {shift.milepost}
            </div>
          </div>
          {reportSubmitted
            ? <Badge tone="good" icon={<IconCheck size={11} />}>Submitted</Badge>
            : <Badge tone="warn">Draft</Badge>}
        </div>

        {/* Banner — required briefing first */}
        {!briefingSubmitted && (
          <div style={{
            background: 'var(--warn-soft)', color: 'var(--warn)',
            border: '1px solid rgba(180,83,9,0.3)', borderRadius: 10,
            padding: '10px 14px', marginBottom: 16, fontSize: 13,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <IconAlert size={14} />
            <span><strong>Job briefing not certified yet.</strong> Some clients require the briefing on file before the field report can be submitted.</span>
          </div>
        )}

        {/* ── Shift summary ───────────────────────────────── */}
        <Section title="Shift summary" eyebrow="A · TIME ACCOUNTED FOR">
          <Grid2>
            <Field label="Shift type">
              <Select options={['New Shift', 'Continuation']} value={r.shiftType} onChange={v => set('shiftType', v)} />
            </Field>
            <Field label="Contractor attendance">
              <Select options={['Showed Up', 'No Show', 'Late Arrival', 'Left Early']} value={r.contractorAttendance} onChange={v => set('contractorAttendance', v)} />
            </Field>
            <Field label="Lunch taken?">
              <SegControl options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]} value={r.lunchTaken} onChange={v => set('lunchTaken', v)} />
            </Field>
            <Field label="Total hours worked" hint="From timecard">
              <Input className="mono" value={r.hoursWorked} onChange={e => set('hoursWorked', e.target.value)} />
            </Field>
            <Field label="Timetable #">
              <Input value={r.timetable} onChange={e => set('timetable', e.target.value)} />
            </Field>
            <Field label="Daily operating bulletin #">
              <Input value={r.bulletinNum} onChange={e => set('bulletinNum', e.target.value)} />
            </Field>
          </Grid2>
          <Field label="General orders in effect">
            <Input value={r.generalOrders} onChange={e => set('generalOrders', e.target.value)} />
          </Field>
        </Section>

        {/* ── Work performed ──────────────────────────────── */}
        <Section title="Work performed in railroad right-of-way" eyebrow="B · DETAILED NARRATIVE">
          <Field label="Description" hint="Distance and side from nearest rail; what was accomplished today">
            <Textarea rows={4} value={shift.workType} onChange={e => updateShift({ workType: e.target.value })} />
          </Field>
          <Grid2>
            <Field label="Initial job briefing performed?">
              <SegControl options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]} value={r.initialBriefing} onChange={v => set('initialBriefing', v)} />
            </Field>
            <Field label="Follow-up briefing performed?">
              <SegControl options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]} value={r.followUpBriefing} onChange={v => set('followUpBriefing', v)} />
            </Field>
          </Grid2>
          <Field label="Briefing(s) consisted of">
            <Textarea rows={2} value={r.briefingContent} onChange={e => set('briefingContent', e.target.value)} />
          </Field>
        </Section>

        {/* ── Train movements ─────────────────────────────── */}
        <Section title="Train & MofW movements" eyebrow="C · MOVEMENT LOG">
          <Field label="Movements through working limits?">
            <SegControl options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]} value={r.trainMovements} onChange={v => set('trainMovements', v)} />
          </Field>

          {r.trainMovements === 'Yes' && (
            <Card padding={0}>
              <div style={{
                display: 'grid', gridTemplateColumns: '60px 1.5fr 1fr 1fr 50px',
                gap: 10, padding: '10px 14px',
                background: 'var(--panel-2)', borderBottom: '1px solid var(--line)',
                fontSize: 11, fontWeight: 600, color: 'var(--muted)', letterSpacing: 0.5, textTransform: 'uppercase',
              }}>
                <span>#</span><span>Train / MofW</span><span>Time in</span><span>Time out</span><span />
              </div>
              {r.trainLog.map((t, i) => (
                <div key={t.id} style={{
                  display: 'grid', gridTemplateColumns: '60px 1.5fr 1fr 1fr 50px',
                  alignItems: 'center', gap: 10, padding: '10px 14px',
                  borderTop: i === 0 ? 'none' : '1px solid var(--line)',
                }}>
                  <span className="mono" style={{ color: 'var(--muted)', fontSize: 12 }}>{String(i + 1).padStart(2, '0')}</span>
                  <Input value={t.trainNum} onChange={e => set('trainLog', r.trainLog.map(x => x.id === t.id ? { ...x, trainNum: e.target.value } : x))} />
                  <Input type="time" value={t.timeIn} onChange={e => set('trainLog', r.trainLog.map(x => x.id === t.id ? { ...x, timeIn: e.target.value } : x))} />
                  <Input type="time" value={t.timeOut} onChange={e => set('trainLog', r.trainLog.map(x => x.id === t.id ? { ...x, timeOut: e.target.value } : x))} />
                  <button onClick={() => set('trainLog', r.trainLog.filter(x => x.id !== t.id))} style={{
                    background: 'transparent', border: '1px solid var(--line)', borderRadius: 8,
                    padding: '6px 8px', cursor: 'pointer', color: 'var(--muted)',
                  }}><IconClose size={12} /></button>
                </div>
              ))}
              <div style={{ padding: 10, borderTop: '1px solid var(--line)' }}>
                <button onClick={() => set('trainLog', [...r.trainLog, { id: Date.now(), trainNum: '', timeIn: '', timeOut: '' }])} style={{
                  background: 'transparent', border: '1px dashed var(--line-strong)', borderRadius: 8,
                  padding: '7px 14px', cursor: 'pointer', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 12.5,
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  <IconPlus size={12} /> Add movement
                </button>
              </div>
            </Card>
          )}
        </Section>

        {/* ── Switch handling + delays + violations ────────── */}
        <Section title="Switches & delays" eyebrow="D · COMPLIANCE QUESTIONS">
          <div style={{
            background: 'var(--panel-2)', border: '1px solid var(--line)',
            borderRadius: 12, padding: '6px 16px',
          }}>
            {[
              ['switchesHandled',   'Any switches handled during this shift?'],
              ['trackDelays',       'Track time delays?'],
              ['contractorDelays',  'Contractor train delays?'],
              ['rulesViolations',   'Rules violations observed?'],
            ].map(([k, q], i, all) => (
              <div key={k} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '11px 0',
                borderBottom: i === all.length - 1 ? 'none' : '1px solid var(--line)',
              }}>
                <div style={{ flex: 1, fontSize: 13.5 }}>{q}</div>
                <SegYN value={r[k]} onChange={v => set(k, v)} />
              </div>
            ))}
          </div>
        </Section>

        {/* ── Photos ───────────────────────────────────────── */}
        <Section
          title="Project photos"
          eyebrow={`E · MINIMUM 4 REQUIRED · ${photoCount}/${photos.length} CAPTURED`}
        >
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {photos.map((ph, idx) => (
              <PhotoSlot key={idx}
                photo={ph}
                idx={idx + 1}
                required={idx < 4}
                onCapture={() => captureSim(idx)}
                onClear={() => clearPhoto(idx)}
              />
            ))}
          </div>
          {photos.length < 10 && (
            <button onClick={addPhotoSlot} style={{
              marginTop: 12, background: 'transparent',
              border: '1px dashed var(--line-strong)', borderRadius: 10,
              padding: '8px 14px', cursor: 'pointer', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 13,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <IconPlus size={14} /> Add photo slot ({10 - photos.length} remaining)
            </button>
          )}
          <Field label="Photo description / notes" style={{ marginTop: 14 }}>
            <Textarea rows={2} value={r.photoDesc} onChange={e => set('photoDesc', e.target.value)} placeholder="Optional captions, conditions, anomalies…" />
          </Field>
        </Section>

        {/* ── Sign-off ───────────────────────────────────── */}
        <Section title="End-of-shift sign-off" eyebrow="F · CERTIFY THE RECORD">
          <div style={{
            background: 'var(--bad-soft)', color: 'var(--bad)',
            border: '1px solid rgba(180,35,24,0.2)', borderRadius: 10,
            padding: '10px 14px', marginBottom: 14, fontSize: 12.5, lineHeight: 1.6,
          }}>
            This report is signed at <strong>END of shift</strong>, only after the State/Contractor representative
            has agreed with all contents — including start/end times and work description.
          </div>

          <Grid2>
            <Field label="State / contractor rep name">
              <Input value={r.contractorRepName} onChange={e => set('contractorRepName', e.target.value)} />
            </Field>
            <Field label="Phone">
              <Input value={r.contractorRepPhone} onChange={e => set('contractorRepPhone', e.target.value)} />
            </Field>
          </Grid2>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 6 }}>STATE / CONTRACTOR — COMPLIANCE</div>
              <SignaturePad onChange={setContractorSig} height={130} />
              <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>
                Acknowledges agreement with the day's report. Compliance evidence only.
              </div>
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 6 }}>RWIC — CERTIFIES REPORT</div>
              <SignaturePad onChange={setRwicSig} height={130} />
              <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>
                {user.name} · {user.badge} · GPS captured on submit
              </div>
            </div>
          </div>
        </Section>

        {/* Submit bar */}
        <div style={{
          marginTop: 24, padding: 18,
          background: canSubmit ? 'var(--good-soft)' : 'var(--panel-2)',
          border: `1px solid ${canSubmit ? 'var(--good)' : 'var(--line)'}`,
          borderRadius: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>
              {reportSubmitted ? 'Field report already submitted' :
                canSubmit ? 'Ready to submit' : `${missing.length} item${missing.length === 1 ? '' : 's'} remaining`}
            </div>
            {!canSubmit && !reportSubmitted && (
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Missing: {missing.join(' · ')}</div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="secondary" onClick={() => goTo('today')}>Back to today</Button>
            <Button variant="primary" size="lg" icon={<IconCheck size={16} />}
              disabled={!canSubmit || reportSubmitted}
              onClick={() => {
                submitReport({
                  employeeBadge: user.badge,
                  projectNumber: shift.projectNumber,
                  date: shift.date,
                  photoCount,
                  trainCount: r.trainLog.filter(t => t.trainNum).length,
                  hours: parseFloat(r.hoursWorked) || (liveHrs || 0),
                  violations: r.rulesViolations === 'Yes',
                });
                goTo('today');
              }}>
              {reportSubmitted ? 'Submitted' : 'Submit field report'}
            </Button>
          </div>
        </div>
      </div>

      {/* RIGHT — context rail */}
      <ReportContextRail r={r} photos={photos} />
    </div>
  );
}

// ─── Photo slot ────────────────────────────────────────────────
function PhotoSlot({ photo, idx, required, onCapture, onClear }) {
  const filled = !!photo.dataUrl;
  return (
    <div style={{
      background: filled ? '#0E1418' : 'var(--panel-2)',
      border: `1px ${filled ? 'solid' : 'dashed'} ${filled ? 'var(--accent)' : 'var(--line-strong)'}`,
      borderRadius: 10, overflow: 'hidden', position: 'relative',
      aspectRatio: '4 / 3',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        position: 'absolute', top: 8, left: 8, zIndex: 2,
        display: 'flex', alignItems: 'center', gap: 5,
      }}>
        <span className="mono" style={{
          fontSize: 10, fontWeight: 700,
          padding: '2px 6px', borderRadius: 4,
          background: filled ? 'rgba(0,0,0,0.55)' : 'var(--panel)',
          color: filled ? '#fff' : 'var(--text-2)',
        }}>{String(idx).padStart(2, '0')}</span>
        {required && !filled && (
          <span style={{ fontSize: 10, color: 'var(--bad)', fontWeight: 700 }}>REQUIRED</span>
        )}
      </div>
      {filled ? (
        <>
          <img src={photo.dataUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            padding: '20px 10px 8px',
            background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.75))',
            color: '#fff', fontSize: 11, fontWeight: 500,
            display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          }}>
            <span>{photo.slot}</span>
            <button onClick={onClear} style={{
              background: 'rgba(255,255,255,0.15)', border: 'none',
              padding: '3px 8px', borderRadius: 4, cursor: 'pointer',
              color: '#fff', fontSize: 11, fontWeight: 500,
            }}>Remove</button>
          </div>
        </>
      ) : (
        <button onClick={onCapture} style={{
          flex: 1, background: 'transparent', border: 'none', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
          color: 'var(--muted)', padding: 12, textAlign: 'center',
        }}>
          <IconCamera size={24} />
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-2)' }}>{photo.slot}</div>
          <div style={{ fontSize: 10.5 }}>Tap to capture</div>
        </button>
      )}
    </div>
  );
}

// ─── Context rail (report) ─────────────────────────────────────
function ReportContextRail({ r, photos }) {
  const { shift, liveHrs, clockState } = useApp();
  const photoCount = photos.filter(p => p.dataUrl).length;
  const trains = r.trainLog.filter(t => t.trainNum).length;

  return (
    <div style={{
      borderLeft: '1px solid var(--line)', background: 'var(--panel-2)',
      overflowY: 'auto', padding: '20px 18px 24px',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div className="eyebrow">REPORT AT A GLANCE</div>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>HOURS</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: -1 }}>{(liveHrs || 0).toFixed(2)}</span>
          <span style={{ fontSize: 13, color: 'var(--muted)' }}>hrs</span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
          {clockState.breakMinutes}m break · GPS continuous
        </div>
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>PHOTO EVIDENCE</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span className="mono" style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5 }}>{photoCount}</span>
          <span style={{ fontSize: 13, color: 'var(--muted)' }}>/ {photos.length}</span>
        </div>
        <div style={{
          marginTop: 8, height: 6, borderRadius: 3, background: 'var(--line)', overflow: 'hidden',
        }}>
          <div style={{
            width: `${Math.min(100, (photoCount / 4) * 100)}%`, height: '100%',
            background: photoCount >= 4 ? 'var(--good)' : 'var(--warn)',
            transition: 'width 200ms',
          }} />
        </div>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>Minimum 4 to submit</div>
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>TRAINS LOGGED</div>
        <span className="mono" style={{ fontSize: 28, fontWeight: 700 }}>{trains}</span>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>in working limits</div>
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>COMPLIANCE FLAGS</div>
        {['switchesHandled', 'trackDelays', 'contractorDelays', 'rulesViolations'].map(k => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0', fontSize: 12.5 }}>
            <span style={{ color: 'var(--muted)' }}>{({switchesHandled:'Switches handled',trackDelays:'Track delays',contractorDelays:'Contractor delays',rulesViolations:'Rules violations'})[k]}</span>
            <Badge tone={r[k] === 'Yes' ? 'warn' : 'good'}>{r[k]}</Badge>
          </div>
        ))}
      </Card>
    </div>
  );
}

// Reuse Section, Grid2, SegYN from briefing — defined globally
function createCanvas(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }

Object.assign(window, { ScreenReport });
