// role-officer.jsx — Officer view: full-access company exec dashboard.
// KPIs across the business + activity feed + open exceptions.

function RoleOfficer() {
  const { employees, timecards, exceptions, payrollRuns, audit } = useAdmin();

  // KPIs
  const onDuty = employees.filter(e => e.status === 'on-duty').length;
  const openExceptions = exceptions.length;
  const criticalExceptions = exceptions.filter(e => e.severity === 'critical' || e.severity === 'high').length;
  const periodHours = timecards.reduce((s, t) => s + t.total, 0);
  const periodGross = timecards.reduce((s, t) => {
    const e = employees.find(x => x.id === t.employeeId);
    return s + t.total * (e?.baseRate || 0);
  }, 0);
  const pendingApproval = timecards.filter(t => t.status === 'pending-ops' || t.status === 'pending-acct').length;
  const complianceScore = Math.round(((timecards.length - exceptions.filter(e => e.kind === 'briefing-missing' || e.kind === 'photo-missing').length) / timecards.length) * 100);
  const nextRun = payrollRuns.find(r => r.status === 'processing') || payrollRuns[0];

  return (
    <>
      <PageHeader
        eyebrow="OFFICER VIEW · FULL ACCESS"
        title="Company at a glance"
        subtitle="Pay period 2026-05-18 → 2026-05-31 · 8 active RWICs across 6 jobs in 5 states"
        right={
          <>
            <Pill tone="good"><StatusDot tone="good" size={6} pulse /> 5 of 6 jobs on schedule</Pill>
            <Button variant="secondary" size="md" icon={<IconDownload size={14} />}>Export brief</Button>
          </>
        }
      />
      <PageBody>
        {/* KPI grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, marginBottom: 22 }}>
          <KPI label="RWICs on duty" value={onDuty} sub={`of ${employees.length}`} tone="dark" icon={<IconUsersBig size={16} />} footer="Live across 5 states" />
          <KPI label="Open exceptions" value={openExceptions} sub={criticalExceptions > 0 ? `${criticalExceptions} critical` : 'all low'} tone={criticalExceptions > 0 ? 'bad' : 'neutral'} icon={<IconAlert size={16} />} />
          <KPI label="Period hours" value={A_fmtNum(periodHours, 1)} sub="this period" icon={<IconClock size={16} />} delta="+8.2%" deltaTone="good" />
          <KPI label="Gross labor" value={A_fmtCurrency(periodGross)} sub="period to date" tone="accent" icon={<IconDollar size={16} />} />
          <KPI label="Compliance" value={`${complianceScore}%`} sub="briefings + photos" tone={complianceScore > 92 ? 'good' : 'warn'} icon={<IconShield size={16} />} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 22 }}>
          {/* LEFT — operations health */}
          <div>
            <AdminSection title="Live operations · this minute"
              action={<Button variant="ghost" size="sm" iconRight={<IconChevronRight size={12} />}>Open dispatch</Button>}>
              <LiveOperationsMap />
            </AdminSection>

            <AdminSection title="Open exceptions"
              action={<Button variant="ghost" size="sm" iconRight={<IconChevronRight size={12} />}>All exceptions</Button>}>
              <ExceptionsList limit={5} />
            </AdminSection>
          </div>

          {/* RIGHT — financial + activity */}
          <div>
            <AdminSection title="Next payroll run">
              <PayrollPreview run={nextRun} pending={pendingApproval} />
            </AdminSection>

            <AdminSection title="Hours by client · period">
              <HoursByClient />
            </AdminSection>

            <AdminSection title="Recent activity"
              action={<Button variant="ghost" size="sm" iconRight={<IconChevronRight size={12} />}>Full audit</Button>}>
              <AuditList items={audit.slice(0, 5)} />
            </AdminSection>
          </div>
        </div>
      </PageBody>
    </>
  );
}

// ── Live operations map ──────────────────────────────────────
function LiveOperationsMap() {
  const { employees, jobs } = useAdmin();
  const onDuty = employees.filter(e => e.status === 'on-duty');
  return (
    <div style={{
      background: 'var(--panel)', border: '1px solid var(--line)',
      borderRadius: 12, overflow: 'hidden', display: 'grid',
      gridTemplateColumns: '1.4fr 1fr',
    }}>
      {/* Map */}
      <div style={{
        background: 'linear-gradient(180deg, #C9D4C0 0%, #DCE4D2 100%)',
        position: 'relative', minHeight: 280, overflow: 'hidden',
      }}>
        <svg width="100%" height="100%" viewBox="0 0 600 280" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0 }}>
          {/* US-ish background lines */}
          <g fill="none" stroke="#a8b59c" strokeWidth="0.5" opacity="0.6">
            {Array.from({ length: 10 }).map((_, i) => (
              <path key={i} d={`M0 ${30 + i * 26} Q 150 ${20 + i * 26} 300 ${30 + i * 26} T 600 ${28 + i * 26}`} />
            ))}
          </g>
          {/* Track lines connecting markers */}
          <g stroke="#3a4451" strokeWidth="1.5" fill="none">
            <path d="M 60 130 Q 200 100 380 150 Q 480 180 540 130" />
            <path d="M 60 130 Q 100 200 180 230" />
          </g>
          <g stroke="#fff" strokeWidth="0.8" strokeDasharray="3 4" fill="none">
            <path d="M 60 130 Q 200 100 380 150 Q 480 180 540 130" />
          </g>
        </svg>
        {/* Markers — one dot per on-duty employee, roughly placed by state */}
        {[
          { s: 'WA', x: 100, y: 80,  e: ['e-2241', 'e-1907'] },
          { s: 'OR', x: 100, y: 130, e: ['e-3025'] },
          { s: 'MT', x: 230, y: 90,  e: [] },
          { s: 'CA', x: 90,  y: 200, e: ['e-5512'] },
          { s: 'UT', x: 200, y: 180, e: ['e-7733'] },
          { s: 'NV', x: 130, y: 170, e: ['e-8814'] },
        ].map(m => m.e.length > 0 && (
          <div key={m.s} style={{
            position: 'absolute', left: m.x, top: m.y,
            transform: 'translate(-50%, -100%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 14,
              background: 'var(--accent)', color: '#fff',
              border: '3px solid #fff', boxShadow: '0 4px 10px rgba(0,0,0,0.3)',
              display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
            }}>{m.e.length}</div>
            <div style={{ width: 2, height: 8, background: 'var(--accent)' }} />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, color: '#fff', background: '#0F172A', padding: '1px 5px', borderRadius: 3, marginTop: 2 }}>{m.s}</span>
          </div>
        ))}
        <div style={{ position: 'absolute', top: 12, left: 12 }}>
          <Pill tone="dark"><StatusDot tone="good" size={6} pulse /> {onDuty.length} on duty · live GPS</Pill>
        </div>
      </div>
      {/* List */}
      <div style={{ borderLeft: '1px solid var(--line)', maxHeight: 280, overflowY: 'auto' }}>
        {onDuty.map((e, i) => (
          <div key={e.id} style={{
            padding: '10px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'var(--accent-soft)', color: 'var(--accent-deep)',
              display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
              flexShrink: 0,
            }}>{e.avatar}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.name}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)' }}>{e.role} · {e.homeBase}</div>
            </div>
            <Pill tone="good"><StatusDot tone="good" size={6} pulse /> {e.resident}</Pill>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Exceptions list ──────────────────────────────────────────
function ExceptionsList({ limit }) {
  const { exceptions, employees, setEmployeeDrawer } = useAdmin();
  const items = limit ? exceptions.slice(0, limit) : exceptions;
  return (
    <div style={{
      background: 'var(--panel)', border: '1px solid var(--line)',
      borderRadius: 12, overflow: 'hidden',
    }}>
      {items.map((ex, i) => {
        const e = employees.find(x => x.id === ex.empId);
        return (
          <div key={ex.id} onClick={() => e && setEmployeeDrawer(e)} style={{
            padding: '12px 16px',
            borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            display: 'flex', alignItems: 'center', gap: 12,
            cursor: 'pointer',
          }}>
            <SeverityDot severity={ex.severity} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 1 }}>
                {EXCEPTION_LABELS[ex.kind]} · {e?.name || '—'}
              </div>
              <div style={{ fontSize: 12, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {ex.detail}
              </div>
            </div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--muted-2)' }}>{ex.age}</span>
          </div>
        );
      })}
    </div>
  );
}

// ── Payroll preview card ─────────────────────────────────────
function PayrollPreview({ run, pending }) {
  const { setPayrollWizard } = useAdmin();
  if (!run) return null;
  return (
    <div style={{
      background: '#0F172A', color: '#fff', borderRadius: 14, padding: '18px 20px',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: -50, right: -50, width: 200, height: 200, borderRadius: '50%', background: 'var(--accent)', opacity: 0.16, filter: 'blur(8px)' }} />
      <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>NEXT RUN · {run.target.toUpperCase()}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
        <span className="mono tnum" style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.8 }}>{A_fmtCurrency(run.gross)}</span>
        <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>gross</span>
      </div>
      <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
        Pay date <span className="mono">{run.payDate}</span> · {run.employees} employees · {A_fmtNum(run.hours, 1)} hrs
      </div>
      <div style={{ marginTop: 14, padding: '10px 12px', background: 'rgba(255,255,255,0.06)', borderRadius: 8, fontSize: 12.5, position: 'relative' }}>
        <strong style={{ color: '#fff' }}>{pending}</strong>
        <span style={{ color: 'rgba(255,255,255,0.65)' }}> timecards pending approval before run.</span>
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 12, position: 'relative' }}>
        <Button variant="primary" size="sm" style={{ flex: 1 }} onClick={() => setPayrollWizard(true)}>Open payroll</Button>
        <Button variant="secondary" size="sm" style={{ background: 'rgba(255,255,255,0.08)', borderColor: 'rgba(255,255,255,0.15)', color: '#fff', flex: 1 }}>Preview taxes</Button>
      </div>
    </div>
  );
}

// ── Hours by client (mini bars) ──────────────────────────────
function HoursByClient() {
  const { timecards, jobs, clients } = useAdmin();
  const byClient = {};
  for (const t of timecards) {
    const job = jobs.find(j => j.id === t.jobId);
    const cl = clients.find(c => c.id === job?.clientId);
    if (!cl) continue;
    byClient[cl.id] = byClient[cl.id] || { name: cl.name, railroad: cl.railroad, hours: 0, billed: 0, rate: cl.billRate };
    byClient[cl.id].hours += t.total;
    byClient[cl.id].billed += t.total * cl.billRate;
  }
  const rows = Object.values(byClient).sort((a, b) => b.hours - a.hours);
  const max = Math.max(...rows.map(r => r.hours));
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '12px 16px' }}>
      {rows.map((r, i) => (
        <div key={r.name} style={{
          padding: '9px 0',
          borderTop: i === 0 ? 'none' : '1px solid var(--line)',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <div>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{r.name}</span>
              <Pill tone="neutral" style={{ marginLeft: 6 }}>{r.railroad}</Pill>
            </div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600 }}>
              {A_fmtNum(r.hours, 1)}h <span style={{ color: 'var(--muted)', fontSize: 12 }}>· {A_fmtCurrency(r.billed)}</span>
            </div>
          </div>
          <ProgressBar value={r.hours} max={max} tone="accent" />
        </div>
      ))}
    </div>
  );
}

// ── Audit list ───────────────────────────────────────────────
function AuditList({ items }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12 }}>
      {items.map((it, i) => (
        <div key={it.id} style={{
          padding: '11px 14px',
          borderTop: i === 0 ? 'none' : '1px solid var(--line)',
          display: 'grid', gridTemplateColumns: '70px 1fr', gap: 10, alignItems: 'flex-start',
        }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
            {it.ts.slice(11, 16)}
            <div style={{ fontSize: 10, color: 'var(--muted-2)' }}>{it.ts.slice(5, 10)}</div>
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>
              <span className="mono" style={{
                fontSize: 10.5, fontWeight: 700, marginRight: 6,
                padding: '1px 6px', borderRadius: 4,
                background: it.role === 'master' ? 'var(--bad-soft)' : 'var(--panel-3)',
                color: it.role === 'master' ? 'var(--bad)' : 'var(--text-2)',
              }}>{it.event}</span>
              {it.actor}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>{it.detail}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { RoleOfficer, LiveOperationsMap, ExceptionsList, PayrollPreview, HoursByClient, AuditList });
