// rwic-briefing.jsx — RWIC Job Briefing form.
//
// RWIC-first: shift fields (location, OTS, risks) carry from the shared shift
// context. The RWIC certifies the briefing was given. Contractor crew is
// a compliance-only list — they sign as attendance proof; the RWIC reviews
// training expiration before allowing them to foul track.

function ScreenBriefing({ goTo }) {
  const { user, shift, updateShift, contractorCrew, briefingSubmitted, submitBriefing } = useApp();
  const [contentRef, setContentRef] = useState(null);
  const [section, setSection] = useState('contacts');
  const [rwicSig, setRwicSig] = useState(false);

  const sections = [
    { id: 'contacts', label: 'Contacts',    icon: <IconUser size={14} /> },
    { id: 'project',  label: 'Project',     icon: <IconBriefcase size={14} /> },
    { id: 'ots',      label: 'On-track safety', icon: <IconTrack size={14} /> },
    { id: 'emergency',label: 'Emergency',   icon: <IconAlert size={14} /> },
    { id: 'risk',     label: 'Red zone',    icon: <IconShield size={14} /> },
    { id: 'crew',     label: 'Crew sign-on', icon: <IconUsers size={14} /> },
  ];

  // Required field validation summary
  const missing = [];
  if (!shift.foremanName) missing.push('Foreman name');
  if (!shift.workType) missing.push('Work description');
  if (!shift.milepost) missing.push('Milepost');
  if (!shift.traumaCenter) missing.push('Trauma center');
  if (!rwicSig) missing.push('RWIC certification signature');
  const canSubmit = missing.length === 0;

  const anyRisk = Object.values(shift.risks).includes('Yes');

  // Auto-scroll target sections into view when nav clicked
  const goSection = (id) => {
    setSection(id);
    const el = document.getElementById(`brf-${id}`);
    if (el && contentRef) contentRef.scrollTo({ top: el.offsetTop - 24, behavior: 'smooth' });
  };

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '230px 1fr 340px', overflow: 'hidden' }}>
      {/* LEFT — section nav */}
      <div style={{
        borderRight: '1px solid var(--line)',
        background: 'var(--panel-2)',
        padding: '20px 14px',
        overflowY: 'auto',
      }}>
        <div className="eyebrow" style={{ marginBottom: 10, padding: '0 6px' }}>SECTIONS</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {sections.map(s => {
            const on = section === s.id;
            return (
              <button key={s.id} onClick={() => goSection(s.id)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 12px',
                background: on ? 'var(--panel)' : 'transparent',
                border: on ? '1px solid var(--line)' : '1px solid transparent',
                borderRadius: 10, cursor: 'pointer', width: '100%', textAlign: 'left',
                color: on ? 'var(--text)' : 'var(--muted)',
                fontSize: 13.5, fontWeight: on ? 600 : 500,
              }}>
                {s.icon}
                {s.label}
              </button>
            );
          })}
        </div>

        {/* Required checklist */}
        <div style={{ marginTop: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 10, padding: '0 6px' }}>BEFORE YOU SUBMIT</div>
          <Card padding={12}>
            {['Foreman name', 'Work description', 'Milepost', 'Trauma center', 'RWIC certification signature'].map(label => {
              const ok = !missing.includes(label);
              return (
                <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', fontSize: 12.5 }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: 4, flexShrink: 0,
                    background: ok ? 'var(--good)' : '#fff',
                    border: ok ? 'none' : '1.5px solid var(--line-strong)',
                    display: 'grid', placeItems: 'center',
                  }}>
                    {ok && <IconCheck size={11} stroke={3} style={{ color: '#fff' }} />}
                  </div>
                  <span style={{ color: ok ? 'var(--text-2)' : 'var(--muted)' }}>{label}</span>
                </div>
              );
            })}
          </Card>
        </div>
      </div>

      {/* CENTER — form */}
      <div ref={setContentRef} style={{ overflowY: 'auto', padding: '20px 28px 32px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="eyebrow">JOB BRIEFING · RWIC / EIC</div>
            <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>Pre-shift safety briefing</div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
              {fmtDateLong(shift.date)} · <span className="mono">{shift.time}</span> · {shift.location}
            </div>
          </div>
          {briefingSubmitted
            ? <Badge tone="good" icon={<IconCheck size={11} />}>Certified</Badge>
            : <Badge tone="warn">Draft · auto-saved</Badge>}
        </div>

        {/* Shift-context pre-fill banner */}
        <div style={{
          background: 'var(--info-soft)', color: 'var(--info)',
          border: '1px solid rgba(29,111,184,0.25)', borderRadius: 10,
          padding: '10px 14px', marginBottom: 18,
          display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
        }}>
          <IconRefresh size={14} />
          <span><strong>Pre-filled from today's assignment.</strong> Job, foreman, OTS, and milepost carry into the Field Report and Timecard.</span>
        </div>

        {/* ── Section: Contacts ───────────────────────────── */}
        <Section id="brf-contacts" title="Contacts" eyebrow="A · WHO IS ON SITE">
          <Grid2>
            <Field label="RWIC / Flagman" required>
              <Input value={shift.flagmanName} onChange={e => updateShift({ flagmanName: e.target.value })} />
            </Field>
            <Field label="RWIC phone" hint="Carried into emergency contacts">
              <Input value={shift.flagmanPhone} onChange={e => updateShift({ flagmanPhone: e.target.value })} />
            </Field>
            <Field label="Contractor foreman" required>
              <Input value={shift.foremanName} onChange={e => updateShift({ foremanName: e.target.value })} />
            </Field>
            <Field label="Foreman phone">
              <Input value={shift.foremanPhone} onChange={e => updateShift({ foremanPhone: e.target.value })} />
            </Field>
            <Field label="Contractor company">
              <Input value={shift.contractorCompany} onChange={e => updateShift({ contractorCompany: e.target.value })} />
            </Field>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="# people on site">
                <Input type="number" value={shift.peopleOnSite} onChange={e => updateShift({ peopleOnSite: e.target.value })} />
              </Field>
              <Field label="# equipment">
                <Input type="number" value={shift.equipOnSite} onChange={e => updateShift({ equipOnSite: e.target.value })} />
              </Field>
            </div>
          </Grid2>
        </Section>

        {/* ── Section: Project ────────────────────────────── */}
        <Section id="brf-project" title="Project information" eyebrow="B · WHERE & WHAT">
          <Grid2>
            <Field label="Railroad">
              <Select options={RAILROADS} value={shift.railroad} onChange={v => updateShift({ railroad: v })} />
            </Field>
            <Field label="Subdivision">
              <Input value={shift.subdivision} onChange={e => updateShift({ subdivision: e.target.value })} />
            </Field>
            <Field label="Milepost(s)" required>
              <Input value={shift.milepost} onChange={e => updateShift({ milepost: e.target.value })} placeholder="e.g. 142.3 – 143.1" />
            </Field>
            <Field label="Weather">
              <Select options={WEATHER} value={shift.weather} onChange={v => updateShift({ weather: v })} />
            </Field>
            <Field label="Scheduled start">
              <Input type="time" value={shift.projectStart} onChange={e => updateShift({ projectStart: e.target.value })} />
            </Field>
            <Field label="Scheduled end">
              <Input type="time" value={shift.projectEnd} onChange={e => updateShift({ projectEnd: e.target.value })} />
            </Field>
          </Grid2>
          <Field label="Type of work being performed" required hint="Distance and side from nearest rail">
            <Textarea rows={3} value={shift.workType} onChange={e => updateShift({ workType: e.target.value })} />
          </Field>
        </Section>

        {/* ── Section: On-Track Safety ────────────────────── */}
        <Section id="brf-ots" title="On-track safety" eyebrow="C · OTS PROTECTION">
          <YNPicker label="On-track protection provided?" value={shift.otsProvided} onChange={v => updateShift({ otsProvided: v })} />
          {shift.otsProvided === 'Yes' && (
            <>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 8, letterSpacing: 0.2, textTransform: 'uppercase' }}>
                  Types in effect
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                  {OTS_TYPES.map(t => {
                    const on = !!shift.otsTypes[t];
                    return (
                      <button key={t} type="button"
                        onClick={() => updateShift({ otsTypes: { ...shift.otsTypes, [t]: !on } })}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 10,
                          padding: '9px 12px',
                          background: on ? 'var(--accent-soft)' : 'var(--panel)',
                          border: `1px solid ${on ? 'var(--accent)' : 'var(--line)'}`,
                          borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                          fontSize: 13, fontWeight: on ? 600 : 500,
                          color: on ? 'var(--accent-deep)' : 'var(--text-2)',
                        }}>
                        <div style={{
                          width: 16, height: 16, borderRadius: 4,
                          background: on ? 'var(--accent)' : '#fff',
                          border: on ? 'none' : '1.5px solid var(--line-strong)',
                          display: 'grid', placeItems: 'center', flexShrink: 0,
                        }}>{on && <IconCheck size={11} stroke={3} style={{ color: '#fff' }} />}</div>
                        {t}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 8, letterSpacing: 0.2, textTransform: 'uppercase' }}>
                Authority items
              </div>
              {shift.otsItems.map((item, i) => (
                <div key={item.id} style={{
                  display: 'grid', gridTemplateColumns: '90px 1fr 1fr 1fr auto', alignItems: 'flex-end', gap: 10,
                  padding: '12px 14px', background: 'var(--panel-2)',
                  border: '1px solid var(--line)', borderRadius: 10, marginBottom: 8,
                }}>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', paddingBottom: 10, letterSpacing: 1, textTransform: 'uppercase' }}>
                    Item {i + 1}
                  </div>
                  <Field label="Authority #" style={{ marginBottom: 0 }}>
                    <Input value={item.itemNum} onChange={e => {
                      const ni = shift.otsItems.map(x => x.id === item.id ? { ...x, itemNum: e.target.value } : x);
                      updateShift({ otsItems: ni });
                    }} />
                  </Field>
                  <Field label="Track(s)">
                    <Input value={item.tracks} onChange={e => {
                      const ni = shift.otsItems.map(x => x.id === item.id ? { ...x, tracks: e.target.value } : x);
                      updateShift({ otsItems: ni });
                    }} />
                  </Field>
                  <Field label="Limits">
                    <Input value={item.limits} onChange={e => {
                      const ni = shift.otsItems.map(x => x.id === item.id ? { ...x, limits: e.target.value } : x);
                      updateShift({ otsItems: ni });
                    }} />
                  </Field>
                  <button onClick={() => {
                    updateShift({ otsItems: shift.otsItems.filter(x => x.id !== item.id) });
                  }} style={{
                    background: 'transparent', border: '1px solid var(--line)', borderRadius: 8,
                    padding: '7px 10px', cursor: 'pointer', color: 'var(--muted)', marginBottom: 14,
                  }}><IconClose size={14} /></button>
                </div>
              ))}
              <button onClick={() => updateShift({
                otsItems: [...shift.otsItems, { id: Date.now(), itemNum: '', tracks: '', limits: '' }]
              })} style={{
                background: 'transparent', border: '1px dashed var(--line-strong)',
                borderRadius: 10, padding: '10px 16px', cursor: 'pointer',
                color: 'var(--accent-deep)', fontWeight: 600, fontSize: 13,
                display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 14,
              }}>
                <IconPlus size={14} /> Add authority item
              </button>

              <Field label="Predetermined place of safety (PPOS)" hint="The clear path to safety taken on train approach">
                <Input value={shift.ppos} onChange={e => updateShift({ ppos: e.target.value })} />
              </Field>
            </>
          )}
        </Section>

        {/* ── Section: Emergency ──────────────────────────── */}
        <Section id="brf-emergency" title="Emergency plan" eyebrow="D · IF SOMETHING GOES WRONG">
          <Field label="Nearest emergency / trauma center" required>
            <Textarea rows={2} value={shift.traumaCenter} onChange={e => updateShift({ traumaCenter: e.target.value })} />
          </Field>
          <Grid2>
            <Field label="Emergency response plan location">
              <Input value={shift.erLocation} onChange={e => updateShift({ erLocation: e.target.value })} />
            </Field>
            <Field label="911 caller">
              <Input value={shift.caller911} onChange={e => updateShift({ caller911: e.target.value })} />
            </Field>
            <Field label="Emergency vehicle escort">
              <Input value={shift.evEscort} onChange={e => updateShift({ evEscort: e.target.value })} />
            </Field>
            <Field label="First aid kit location">
              <Input value={shift.firstAidKit} onChange={e => updateShift({ firstAidKit: e.target.value })} />
            </Field>
            <Field label="CPR designated person">
              <Input value={shift.cprPerson} onChange={e => updateShift({ cprPerson: e.target.value })} />
            </Field>
            <Field label="CPR person phone">
              <Input value={shift.cprPhone} onChange={e => updateShift({ cprPhone: e.target.value })} />
            </Field>
          </Grid2>
        </Section>

        {/* ── Section: Red Zone / Risk ────────────────────── */}
        <Section id="brf-risk" title="Red zone & risk assessment" eyebrow="E · IS THERE A RISK OF…">
          <div style={{ background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 12, padding: '6px 16px' }}>
            {[
              ['adjTrack',     'Being struck by a train on an adjacent track?'],
              ['occupiedTrack','Being struck by a train on the track being occupied?'],
              ['ots',          'Being struck by or caught between on-track equipment?'],
              ['crossing',     'Being struck by a motorist at a crossing or highway?'],
              ['equipment',    'Being struck by material being handled by equipment?'],
              ['cranes',       'Cranes / booms in ROW that could topple into foul?'],
              ['bridge',       'Personnel falling from a bridge or elevated structure?'],
              ['cables',       'Cables & hoses over a structure that could be snagged?'],
              ['otherRisk',    'Other life-critical risk?'],
            ].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, lineHeight: 1.4 }}>{q}</div>
                <SegYN value={shift.risks[k]} onChange={v => updateShift({ risks: { ...shift.risks, [k]: v } })} />
              </div>
            ))}
          </div>
          {anyRisk && (
            <Field label="Plan of action for mitigating life-critical risk" style={{ marginTop: 14 }}>
              <Textarea rows={3} value={shift.riskPlan} onChange={e => updateShift({ riskPlan: e.target.value })} />
            </Field>
          )}
        </Section>

        {/* ── Section: Crew sign-on ────────────────────────── */}
        <Section id="brf-crew"
          title="Contractor crew · briefing acknowledgement"
          eyebrow="F · COMPLIANCE EVIDENCE">
          <div style={{
            background: 'var(--accent-soft)', color: 'var(--accent-deep)',
            border: '1px solid rgba(229,91,19,0.25)', borderRadius: 10,
            padding: '10px 14px', marginBottom: 14, fontSize: 13, lineHeight: 1.55,
          }}>
            <strong>For compliance only.</strong> The RWIC certifies the briefing was given.
            Contractor crew sign as proof of attendance and to acknowledge their training
            is current. They are not employees of {useTweakValues().tweaks.companyName}.
          </div>
          <CrewSignList crew={contractorCrew} />
        </Section>

        {/* ── Section: RWIC certification ────────────────────── */}
        <Section id="brf-cert" title="RWIC certification" eyebrow="G · CERTIFY THE BRIEFING">
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, alignItems: 'flex-start',
          }}>
            <div>
              <div style={{ fontSize: 13.5, lineHeight: 1.6, color: 'var(--text-2)' }}>
                I, <strong>{user.name}</strong> (badge <span className="mono">{user.badge}</span>),
                certify that I have conducted this job briefing in accordance with FRA 49 CFR Part 214,
                that all on-track safety information has been communicated to every person who will foul
                a track, and that each crew member has acknowledged understanding and is currently certified.
              </div>
              <div style={{ marginTop: 14, fontSize: 12, color: 'var(--muted)' }}>
                Sign once · <span className="mono">{shift.date} {shift.time}</span> · GPS will be captured on submit
              </div>
            </div>
            <div style={{ width: 340 }}>
              <div className="eyebrow" style={{ marginBottom: 6 }}>RWIC SIGNATURE</div>
              <SignaturePad onChange={setRwicSig} height={130} />
            </div>
          </div>
        </Section>

        {/* Footer / 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 }}>
              {briefingSubmitted ? 'Briefing already certified for this shift' :
                canSubmit ? 'All required fields complete' : `${missing.length} item${missing.length === 1 ? '' : 's'} remaining`}
            </div>
            {!canSubmit && !briefingSubmitted && (
              <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={<IconSignature size={16} />}
              disabled={!canSubmit || briefingSubmitted}
              onClick={() => {
                submitBriefing({
                  employeeBadge: user.badge,
                  projectNumber: shift.projectNumber,
                  date: shift.date,
                  sigCount: contractorCrew.filter(c => c.signed).length,
                  crewTotal: contractorCrew.length,
                  riskFlags: Object.entries(shift.risks).filter(([, v]) => v === 'Yes').map(([k]) => k),
                  otsTypes: Object.entries(shift.otsTypes).filter(([, v]) => v).map(([t]) => t),
                });
                goTo('today');
              }}
            >
              {briefingSubmitted ? 'Submitted' : 'Certify & submit briefing'}
            </Button>
          </div>
        </div>
      </div>

      {/* RIGHT — context preview / sticky summary */}
      <BriefingContextRail />
    </div>
  );
}

// ─── Crew sign-on list — compliance grid ───────────────────────
function CrewSignList({ crew }) {
  const [activeId, setActiveId] = useState(null);
  return (
    <Card padding={0}>
      <div style={{
        display: 'grid', gridTemplateColumns: '36px 1.4fr 1.4fr 130px 130px',
        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>Worker</span>
        <span>Company</span>
        <span>Training exp.</span>
        <span style={{ textAlign: 'right' }}>Acknowledgement</span>
      </div>
      {crew.map((c, i) => {
        const expired = new Date(c.trainingExp) < new Date();
        return (
          <div key={c.id} style={{
            display: 'grid', gridTemplateColumns: '36px 1.4fr 1.4fr 130px 130px',
            alignItems: 'center', gap: 10, padding: '12px 14px',
            borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            background: expired ? 'rgba(180,35,24,0.04)' : 'transparent',
          }}>
            <Avatar name={c.name} size={28} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>{c.name}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)' }}>Worker · {c.signed ? 'on site' : 'awaiting signature'}</div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-2)' }}>{c.company}</div>
            <div>
              <span className="mono" style={{ fontSize: 12.5, color: expired ? 'var(--bad)' : 'var(--text)' }}>
                {c.trainingExp}
              </span>
              {expired && <div style={{ fontSize: 10, color: 'var(--bad)', fontWeight: 600, marginTop: 2 }}>⚠ EXPIRED</div>}
            </div>
            <div style={{ textAlign: 'right' }}>
              {c.signed
                ? <Badge tone="good" icon={<IconCheck size={11} />}>signed · {fmtTime(c.signedAt)}</Badge>
                : (
                  <button onClick={() => setActiveId(c.id)} style={{
                    background: 'var(--accent)', color: '#fff', border: 'none',
                    padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
                    cursor: 'pointer',
                  }}>Capture signature</button>
                )}
            </div>
          </div>
        );
      })}

      {/* Sign sheet */}
      <Sheet open={!!activeId} onClose={() => setActiveId(null)}
        title={`Sign briefing — ${crew.find(c => c.id === activeId)?.name || ''}`}
        height="64%">
        <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 14, lineHeight: 1.5 }}>
          By signing, the worker confirms they have received and understood today's job briefing,
          and that their roadway worker training is current.
        </div>
        <SignaturePad height={170} />
        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <Button variant="secondary" style={{ flex: 1 }} onClick={() => setActiveId(null)}>Cancel</Button>
          <Button variant="primary" style={{ flex: 2 }} icon={<IconCheck size={16} />} onClick={() => setActiveId(null)}>
            Save signature
          </Button>
        </div>
      </Sheet>
    </Card>
  );
}

// ─── Sticky right rail with summary ────────────────────────────
function BriefingContextRail() {
  const { shift, contractorCrew } = useApp();
  const signed = contractorCrew.filter(c => c.signed).length;
  const expired = contractorCrew.filter(c => new Date(c.trainingExp) < new Date());

  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">LIVE PREVIEW · PDF EXPORT</div>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>HEADER</div>
        <div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.3 }}>{shift.projectName}</div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4, lineHeight: 1.5 }}>
          <div><span className="mono">{shift.projectNumber}</span></div>
          <div>{shift.railroad} · {shift.subdivision}</div>
          <div>MP {shift.milepost}</div>
        </div>
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>OTS PROTECTION</div>
        {Object.entries(shift.otsTypes).filter(([, v]) => v).length === 0
          ? <div style={{ fontSize: 12, color: 'var(--muted)' }}>None selected.</div>
          : Object.entries(shift.otsTypes).filter(([, v]) => v).map(([t]) => (
            <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, padding: '3px 0' }}>
              <IconCheck size={12} style={{ color: 'var(--good)' }} /> {t}
            </div>
          ))}
        {shift.otsItems.filter(x => x.itemNum).length > 0 && (
          <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)' }}>
            {shift.otsItems.filter(x => x.itemNum).map(x => (
              <div key={x.id} className="mono" style={{ fontSize: 11.5, color: 'var(--text-2)' }}>
                #{x.itemNum} · {x.tracks} · {x.limits}
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>RISKS IDENTIFIED</div>
        {Object.entries(shift.risks).filter(([, v]) => v === 'Yes').length === 0
          ? <div style={{ fontSize: 12, color: 'var(--muted)' }}>None.</div>
          : (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
              {Object.entries(shift.risks).filter(([, v]) => v === 'Yes').map(([k]) => (
                <Badge key={k} tone="bad">{riskLabel(k)}</Badge>
              ))}
            </div>
          )}
      </Card>

      <Card padding={14}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <div className="eyebrow">CREW SIGNATURES</div>
          <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--text)' }}>
            {signed} / {contractorCrew.length}
          </span>
        </div>
        <div style={{
          height: 8, background: 'var(--line)', borderRadius: 4, overflow: 'hidden',
        }}>
          <div style={{
            height: '100%', width: `${(signed / contractorCrew.length) * 100}%`,
            background: 'var(--good)', transition: 'width 200ms ease',
          }} />
        </div>
        {expired.length > 0 && (
          <div style={{ marginTop: 10, padding: '8px 10px', background: 'var(--bad-soft)', color: 'var(--bad)', borderRadius: 8, fontSize: 12, lineHeight: 1.4 }}>
            ⚠ {expired.length} worker{expired.length === 1 ? '' : 's'} have expired training. They cannot foul track.
          </div>
        )}
      </Card>
    </div>
  );
}

const riskLabel = (k) => ({
  adjTrack: 'Adjacent train', occupiedTrack: 'Occupied train', ots: 'On-track equipment',
  crossing: 'Crossing', equipment: 'Equipment swing', cranes: 'Crane / boom',
  bridge: 'Fall / elevated', cables: 'Cables / hoses', otherRisk: 'Other',
})[k] || k;

// ─── Section wrapper ───────────────────────────────────────────
function Section({ id, title, eyebrow, children }) {
  return (
    <div id={id} style={{ marginBottom: 28 }}>
      <div style={{ marginBottom: 14, paddingBottom: 10, borderBottom: '1px solid var(--line)' }}>
        <div className="eyebrow" style={{ marginBottom: 2 }}>{eyebrow}</div>
        <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.2 }}>{title}</div>
      </div>
      {children}
    </div>
  );
}

const Grid2 = ({ children }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 4 }}>
    {children}
  </div>
);

// Yes/No radio pill
function YNPicker({ label, value, onChange }) {
  return (
    <Field label={label}>
      <SegControl
        options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]}
        value={value} onChange={onChange}
      />
    </Field>
  );
}

// Compact inline Yes/No
function SegYN({ value, onChange }) {
  return (
    <div style={{
      display: 'inline-flex', background: '#fff',
      border: '1px solid var(--line)', borderRadius: 8, padding: 2,
    }}>
      {['Yes', 'No'].map(v => {
        const on = value === v;
        return (
          <button key={v} type="button" onClick={() => onChange(v)} style={{
            padding: '5px 14px', border: 'none',
            borderRadius: 6, cursor: 'pointer',
            background: on ? (v === 'Yes' ? 'var(--bad-soft)' : 'var(--panel-2)') : 'transparent',
            color: on ? (v === 'Yes' ? 'var(--bad)' : 'var(--text-2)') : 'var(--muted)',
            fontSize: 12.5, fontWeight: on ? 700 : 500, minWidth: 50,
          }}>{v}</button>
        );
      })}
    </div>
  );
}

Object.assign(window, { ScreenBriefing });
