// role-safety.jsx — Safety/Compliance role: briefing audits, training,
// FRA-style reporting summary.

function RoleSafety() {
  const { employees, exceptions, timecards, submissions } = useAdmin();
  const [tab, setTab] = useState('overview');
  const pendingSubs = submissions.filter(s => s.status === 'pending-review').length;
  const briefingMissing = exceptions.filter(e => e.kind === 'briefing-missing').length;
  const trainingExpiring = employees.filter(e => {
    const d = new Date(e.certExpires);
    return d > new Date() && d < new Date('2026-08-22');
  }).length;
  const trainingExpired = employees.filter(e => new Date(e.certExpires) < new Date('2026-05-22')).length;
  const photoCompliance = Math.round((1 - exceptions.filter(e => e.kind === 'photo-missing').length / timecards.length) * 100);
  return (
    <>
      <PageHeader
        eyebrow="SAFETY & COMPLIANCE"
        title="Compliance posture"
        subtitle="FRA 49 CFR Part 214 · briefings, training, photo evidence, and rules-violation log."
        right={<Button variant="secondary" size="md" icon={<IconDownload size={14} />}>FRA report</Button>}
      />
      <div style={{ padding: '14px 32px 0', borderBottom: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', gap: 4 }}>
        {[
          { id: 'overview', label: 'Overview' },
          { id: 'submissions', label: 'Field submissions', badge: pendingSubs },
          { id: 'training', label: 'Training matrix' },
        ].map(t => {
          const on = tab === t.id;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '10px 14px', background: 'transparent', border: 'none',
              borderBottom: on ? '2px solid var(--accent)' : '2px solid transparent',
              marginBottom: -1, display: 'inline-flex', alignItems: 'center', gap: 7,
              color: on ? 'var(--text)' : 'var(--muted)', fontWeight: on ? 600 : 500, fontSize: 13.5,
            }}>
              {t.label}
              {t.badge > 0 && <span style={{ background: 'var(--bad)', color: '#fff', fontSize: 10.5, fontWeight: 700, fontFamily: 'var(--font-mono)', padding: '0 6px', borderRadius: 8 }}>{t.badge}</span>}
            </button>
          );
        })}
      </div>
      <PageBody>
        {tab === 'submissions' && <FieldSubmissionsQueue />}
        {tab === 'training' && (
          <AdminSection title="Training certification matrix"
            action={<Button variant="ghost" size="sm" icon={<IconDownload size={12} />}>Export</Button>}>
            <TrainingMatrix />
          </AdminSection>
        )}
        {tab === 'overview' && (
        <>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
          <KPI label="Briefings missing today" value={briefingMissing} sub="on active jobs" tone={briefingMissing > 0 ? 'bad' : 'good'} icon={<IconShield size={16} />} />
          <KPI label="Training expired" value={trainingExpired} sub="cannot foul track" tone={trainingExpired > 0 ? 'bad' : 'good'} icon={<IconAlert size={16} />} />
          <KPI label="Training expiring < 90d" value={trainingExpiring} sub="schedule recert" tone={trainingExpiring > 0 ? 'warn' : 'good'} icon={<IconClock size={16} />} />
          <KPI label="Photo compliance" value={`${photoCompliance}%`} sub="of submitted reports" tone={photoCompliance > 90 ? 'good' : 'warn'} icon={<IconClipboard size={16} />} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 22 }}>
          <div>
            <AdminSection title="Training certification matrix"
              action={<Button variant="ghost" size="sm" icon={<IconDownload size={12} />}>Export</Button>}>
              <TrainingMatrix />
            </AdminSection>
          </div>
          <div>
            <AdminSection title="Open safety exceptions">
              <ExceptionsList />
            </AdminSection>
            <AdminSection title="Rules-violation log (last 30 days)">
              <ViolationLog />
            </AdminSection>
          </div>
        </div>
        </>
        )}
      </PageBody>
    </>
  );
}

// ── Training matrix ─────────────────────────────────────────
function TrainingMatrix() {
  const { employees } = useAdmin();
  // Mock per-railroad cert grid
  const certs = ['BNSF RWP', 'UP RWP', 'CSX FCI', 'NS RWP', 'EIC', 'CPR/First Aid'];
  // Generate deterministic statuses
  const matrixOf = (e) => certs.map((c, i) => {
    const seed = (e.id.charCodeAt(2) + i * 7) % 10;
    if (seed < 1) return { status: 'expired', date: '2025-12-18' };
    if (seed < 3) return { status: 'expiring', date: '2026-07-30' };
    if (seed < 7) return { status: 'current', date: '2027-05-12' };
    return { status: 'na' };
  });
  const cell = (s) => {
    if (s.status === 'na') return <span style={{ color: 'var(--muted-2)' }}>—</span>;
    const tone = { current: 'good', expiring: 'warn', expired: 'bad' }[s.status];
    return <Pill tone={tone}>{s.status === 'na' ? 'n/a' : s.date.slice(2, 7).replace('-', '/')}</Pill>;
  };
  return (
    <div style={{
      background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12,
      overflow: 'auto',
    }}>
      <table style={{ width: '100%', fontSize: 12 }}>
        <thead>
          <tr style={{ background: 'var(--panel-2)', borderBottom: '1px solid var(--line)' }}>
            <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Employee</th>
            {certs.map(c => (
              <th key={c} style={{ padding: '10px 8px', textAlign: 'center', fontSize: 10.5, color: 'var(--muted)', fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>{c}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {employees.map((e, i) => {
            const row = matrixOf(e);
            return (
              <tr key={e.id} style={{ borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <td style={{ padding: '10px 14px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 24, height: 24, borderRadius: 12, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>{e.avatar}</div>
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 600 }}>{e.name.split(' ')[0]} {e.name.split(' ').pop().charAt(0)}.</div>
                      <div style={{ fontSize: 10.5, color: 'var(--muted)' }}>{e.role}</div>
                    </div>
                  </div>
                </td>
                {row.map((s, j) => (
                  <td key={j} style={{ padding: '10px 6px', textAlign: 'center' }}>{cell(s)}</td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ── Violations log ──────────────────────────────────────────
function ViolationLog() {
  const items = [
    { ts: '2026-05-19', who: 'Northwest Track', what: 'Worker fouled track without verbal authority', who2: 'D. Reyes', sev: 'high' },
    { ts: '2026-05-14', who: 'Pacific Rail Welding', what: 'PPE missing — high-vis vest', who2: 'M. Halverson', sev: 'med' },
    { ts: '2026-05-09', who: 'BridgePro West', what: 'PPOS not communicated before fouling', who2: 'A. Vargas', sev: 'high' },
  ];
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12 }}>
      {items.map((v, i) => (
        <div key={i} style={{
          padding: '12px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <SeverityDot severity={v.sev} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{v.what}</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>
              {v.who} · documented by {v.who2}
            </div>
          </div>
          <span className="mono" style={{ fontSize: 11, color: 'var(--muted-2)' }}>{v.ts.slice(5)}</span>
        </div>
      ))}
    </div>
  );
}

// ── Field submissions queue (briefings + reports from tablets) ──
function FieldSubmissionsQueue() {
  const { submissions, employees, jobs, reviewSubmission, toast, launchDoc } = useAdmin();
  const [filter, setFilter] = useState('pending-review');

  const counts = {
    'pending-review': submissions.filter(s => s.status === 'pending-review').length,
    'accepted':       submissions.filter(s => s.status === 'accepted').length,
    'flagged':        submissions.filter(s => s.status === 'flagged').length,
  };
  const rows = submissions.filter(s => filter === 'all' ? true : s.status === filter);

  const act = (id, status) => {
    reviewSubmission(id, status);
    toast(status === 'accepted' ? 'Submission accepted into compliance record' : 'Submission flagged for follow-up', status === 'accepted' ? 'success' : 'warn');
  };

  return (
    <>
      {/* How it works banner */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16,
        padding: '11px 16px', borderRadius: 10, background: 'var(--info-soft)', border: '1px solid rgba(29,111,184,0.25)',
      }}>
        <IconShield size={16} style={{ color: 'var(--info)' }} />
        <span style={{ fontSize: 13, color: 'var(--info)' }}>
          Job briefings and daily field reports submitted on the field tablet land here for compliance review.
          Auto-flags fire on incomplete signatures, sub-minimum photos, multiple red-zone risks, or reported rules violations.
        </span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <FilterChip active={filter==='pending-review'} onClick={() => setFilter('pending-review')} count={counts['pending-review']}>Pending review</FilterChip>
        <FilterChip active={filter==='accepted'} onClick={() => setFilter('accepted')} count={counts['accepted']}>Accepted</FilterChip>
        <FilterChip active={filter==='flagged'} onClick={() => setFilter('flagged')} count={counts['flagged']}>Flagged</FilterChip>
        <FilterChip active={filter==='all'} onClick={() => setFilter('all')} count={submissions.length}>All</FilterChip>
      </div>

      {rows.length === 0 ? (
        <div style={{
          padding: '44px 28px', textAlign: 'center', background: 'var(--panel)',
          border: '1px dashed var(--line-strong)', borderRadius: 12,
        }}>
          <div style={{ width: 52, height: 52, borderRadius: 26, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', margin: '0 auto 12px', color: 'var(--muted)' }}>
            <IconClipboard size={26} />
          </div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>No {filter === 'all' ? '' : filter.replace('-', ' ')} submissions</div>
          <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4, maxWidth: 420, margin: '4px auto 0', lineHeight: 1.5 }}>
            When an RWIC certifies a briefing or submits a field report on the tablet, it appears here within seconds.
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map(s => {
            const e = employees.find(x => x.id === s.employeeId);
            const job = jobs.find(j => j.id === s.jobId);
            const mgr = (typeof managerForJob === 'function' && job) ? managerForJob(job.id) : null;
            const isBriefing = s.kind === 'briefing';
            return (
              <div key={s.id} style={{
                background: 'var(--panel)', border: `1px solid ${s.autoFlag ? 'var(--warn)' : 'var(--line)'}`,
                borderLeft: `4px solid ${isBriefing ? 'var(--info)' : 'var(--accent)'}`,
                borderRadius: 12, padding: '14px 18px',
              }}>
                <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.6fr 1fr auto', gap: 16, alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 40, height: 40, borderRadius: 10, background: isBriefing ? 'var(--info-soft)' : 'var(--accent-soft)', color: isBriefing ? 'var(--info)' : 'var(--accent-deep)', display: 'grid', placeItems: 'center' }}>
                      {isBriefing ? <IconShield size={20} /> : <IconClipboard size={20} />}
                    </div>
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ fontWeight: 700, fontSize: 14 }}>{isBriefing ? 'Job Briefing' : 'Field Report'}</span>
                        <Pill tone="accent">tablet</Pill>
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--muted)' }}>{e?.name} · {A_fmtDateShort(s.date)} · <span className="mono">{job?.id}</span></div>
                    </div>
                  </div>

                  {/* Detail chips */}
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {isBriefing ? (
                      <>
                        <Pill tone={s.sigCount < s.crewTotal ? 'warn' : 'good'}>{s.sigCount}/{s.crewTotal} signed</Pill>
                        {s.riskFlags.length > 0 && <Pill tone="bad">{s.riskFlags.length} risks</Pill>}
                        {s.otsTypes.length > 0 && <Pill tone="neutral">{s.otsTypes.length} OTS</Pill>}
                      </>
                    ) : (
                      <>
                        <Pill tone={s.photoCount < 4 ? 'bad' : 'good'}>{s.photoCount} photos</Pill>
                        <Pill tone="neutral">{s.trainCount} trains</Pill>
                        <Pill tone="neutral">{A_fmtNum(s.hours, 1)}h</Pill>
                        {s.violations && <Pill tone="bad">violation</Pill>}
                      </>
                    )}
                  </div>

                  {/* Routing + flag */}
                  <div>
                    {mgr && <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>crew under <span style={{ color: 'var(--indigo)', fontWeight: 600 }}>{mgr.name.split(' ')[0]} {mgr.name.split(' ').pop().charAt(0)}.</span></div>}
                    {s.autoFlag && <div style={{ fontSize: 11.5, color: 'var(--warn)', fontWeight: 600, marginTop: 2 }}>⚠ {s.autoFlag}</div>}
                  </div>

                  {/* Actions */}
                  <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button variant="ghost" size="sm" icon={<IconDownload size={12} />} onClick={() => {
                      const doc = isBriefing
                        ? buildBriefingDoc({ company: 'RailFlagsPro LLC', sub: s, employee: e, job })
                        : buildReportDoc({ company: 'RailFlagsPro LLC', sub: s, employee: e, job });
                      launchDoc(doc);
                    }}>Record</Button>
                    {s.status === 'pending-review' ? (
                      <>
                        <Button variant="secondary" size="sm" onClick={() => act(s.id, 'flagged')}>Flag</Button>
                        <Button variant="primary" size="sm" icon={<IconCheck size={12} />} onClick={() => act(s.id, 'accepted')}>Accept</Button>
                      </>
                    ) : (
                      <Pill tone={s.status === 'accepted' ? 'good' : 'bad'}>{s.status === 'accepted' ? 'Accepted' : 'Flagged'}</Pill>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </>
  );
}

Object.assign(window, { RoleSafety, FieldSubmissionsQueue });