// rwic-today.jsx — The Today/Home dashboard for the RWIC tablet.
// Anchors the whole experience: clock status, current job, briefing/report
// progress, expected trains, GPS pin, quick actions.

function ScreenToday({ goTo }) {
  const { user, job, shift, clockState, liveHrs, clockIn, clockOut, toggleBreak,
          briefingSubmitted, briefingSubmittedAt, briefingSigCount, contractorCrew,
          reportSubmitted, reportSubmittedAt, timecardSubmitted, timecardSubmittedAt,
          switchCode, history, now } = useApp();

  const isOn = clockState.status !== 'off';
  const onBreak = clockState.status === 'break';

  const currentAC = codeByValue(clockState.currentCode);

  // Days the RWIC has been on this assignment (for context strip)
  const startedAgo = (iso) => {
    if (!iso) return '—';
    const m = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
    if (m < 1) return 'just now';
    if (m < 60) return `${m}m ago`;
    return `${Math.floor(m / 60)}h ${m % 60}m ago`;
  };

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 380px', gap: 0, overflow: 'hidden' }}>
      {/* LEFT — primary column */}
      <div style={{ overflowY: 'auto', padding: '20px 24px 24px' }}>
        {/* Greeting + date strip */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>RWIC · {user.badge}</div>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, lineHeight: 1.1 }}>
              Good morning, {user.name.split(' ')[0]}.
            </div>
            <div style={{ fontSize: 14, color: 'var(--muted)', marginTop: 4 }}>
              {fmtDateLong(shift.date)} · {job.location}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Badge tone="good" icon={<IconLocation size={12} />}>GPS Locked</Badge>
            <Badge tone="info" icon={<StatusDot tone="info" size={6} />}>Cascade Desk online</Badge>
          </div>
        </div>

        {/* CLOCK CARD — hero */}
        <ClockCard
          isOn={isOn}
          onBreak={onBreak}
          liveHrs={liveHrs}
          startedAt={clockState.startedAt}
          currentAC={currentAC}
          breakMin={clockState.breakMinutes}
          clockIn={() => clockIn('F10')}
          clockOut={clockOut}
          toggleBreak={toggleBreak}
          switchCode={switchCode}
        />

        {/* Today's compliance progress */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 14 }}>
          <ComplianceTile
            title="Job Briefing"
            sub={briefingSubmitted ? `Certified ${startedAgo(briefingSubmittedAt)}` : 'Required before fouling track'}
            status={briefingSubmitted ? 'done' : 'todo'}
            progress={briefingSubmitted ? `${briefingSigCount} of ${contractorCrew.length} signed` : `${briefingSigCount} of ${contractorCrew.length} signed`}
            onClick={() => goTo('briefing')}
            icon={<IconShield size={20} />}
          />
          <ComplianceTile
            title="Field Report"
            sub={reportSubmitted ? `Submitted ${startedAgo(reportSubmittedAt)}` : 'Complete at end of shift'}
            status={reportSubmitted ? 'done' : isOn ? 'todo' : 'locked'}
            progress={reportSubmitted ? 'Photos · 4 / 4 minimum' : isOn ? '0 of 4 photos' : 'Available after clock-in'}
            onClick={() => goTo('report')}
            icon={<IconClipboard size={20} />}
          />
          <ComplianceTile
            title="Timecard"
            sub={timecardSubmitted ? `Submitted ${startedAgo(timecardSubmittedAt)}` : `${liveHrs.toFixed(2)} hrs logged today`}
            status={timecardSubmitted ? 'done' : isOn ? 'todo' : 'todo'}
            progress={`${clockState.activityLog.length + (isOn ? 1 : 0)} activity ${(clockState.activityLog.length + (isOn ? 1 : 0)) === 1 ? 'block' : 'blocks'}`}
            onClick={() => goTo('timecard')}
            icon={<IconClock size={20} />}
          />
        </div>

        {/* Today's job — full card */}
        <Card padding={0} style={{ marginTop: 16, overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, padding: '18px 20px 14px' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 12, flexShrink: 0,
              background: 'var(--accent-soft)', color: 'var(--accent-deep)',
              display: 'grid', placeItems: 'center',
            }}>
              <IconTrack size={28} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="eyebrow" style={{ marginBottom: 2 }}>TODAY'S ASSIGNMENT · {job.projectNumber}</div>
              <div style={{ fontWeight: 700, fontSize: 18, letterSpacing: -0.2 }}>{job.projectName}</div>
              <div style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 2, lineHeight: 1.5 }}>{job.workType}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
              <Badge tone="dark">{job.railroad}</Badge>
              <span className="mono" style={{ fontSize: 11.5, color: 'var(--muted)' }}>{job.scheduled.start}–{job.scheduled.end}</span>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', borderTop: '1px solid var(--line)' }}>
            <InfoCell label="Subdivision" value={job.subdivision} />
            <InfoCell label="Milepost" value={job.milepost} divider />
            <InfoCell label="Contractor" value={job.contractor.company} divider />
            <InfoCell label="Foreman" value={`${job.contractor.foreman} · ${job.contractor.foremanPhone}`} divider />
          </div>
        </Card>

        {/* Expected train movements */}
        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: -0.2 }}>Expected train movements</div>
          <span className="eyebrow">PER BULLETIN DOB-1142</span>
        </div>
        <Card padding={0}>
          {job.expectedTrains.map((t, i) => (
            <div key={t.train} style={{
              display: 'grid', gridTemplateColumns: '52px 1fr auto auto', alignItems: 'center', gap: 14,
              padding: '12px 18px',
              borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 10,
                background: t.dir === 'EB' ? 'var(--info-soft)' : 'var(--accent-soft)',
                color: t.dir === 'EB' ? 'var(--info)' : 'var(--accent-deep)',
                display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13,
              }}>{t.dir}</div>
              <div>
                <div className="mono" style={{ fontWeight: 600, fontSize: 14 }}>{t.train}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>
                  {t.dir === 'EB' ? 'Eastbound' : 'Westbound'} · Track 1
                </div>
              </div>
              <span className="mono" style={{ fontSize: 18, fontWeight: 700 }}>{t.eta}</span>
              <Badge tone="neutral">scheduled</Badge>
            </div>
          ))}
        </Card>
      </div>

      {/* RIGHT — sidebar column */}
      <div style={{
        borderLeft: '1px solid var(--line)', background: 'var(--panel-2)',
        overflowY: 'auto', padding: '20px 20px 24px',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        {/* Live GPS card */}
        <GpsMiniMap label={job.location} />

        {/* Emergency call-down */}
        <Card padding={14}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>EMERGENCY CALL-DOWN</div>
          <CallRow label="911" sub="EvergreenHealth Monroe · 25 min" tel="911" tone="bad" />
          <CallRow label="GPR Dispatcher" sub="Cascade Desk · 24/7" tel="1-800-555-7411" tone="info" />
          <CallRow label="Foreman" sub={`${job.contractor.foreman} · ${job.contractor.company}`} tel={job.contractor.foremanPhone} tone="accent" last />
        </Card>

        {/* Crew snapshot */}
        <Card padding={0}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 14px 8px',
          }}>
            <div className="eyebrow">CREW ON SITE · COMPLIANCE</div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{contractorCrew.filter(c => c.signed).length}/{contractorCrew.length}</span>
          </div>
          <div style={{ borderTop: '1px solid var(--line)' }}>
            {contractorCrew.slice(0, 5).map((c, i) => (
              <div key={c.id} style={{
                padding: '9px 14px',
                display: 'flex', alignItems: 'center', gap: 10,
                borderTop: i === 0 ? 'none' : '1px solid var(--line)',
              }}>
                <Avatar name={c.name} size={28} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {c.company}
                  </div>
                </div>
                {c.signed
                  ? <Badge tone="good" icon={<IconCheck size={10} />}>signed</Badge>
                  : <Badge tone="warn">pending</Badge>}
              </div>
            ))}
          </div>
          <div style={{ padding: 10, borderTop: '1px solid var(--line)' }}>
            <button onClick={() => goTo('briefing')} style={{
              background: 'transparent', border: 'none', padding: 6, width: '100%',
              cursor: 'pointer', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 13,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              Manage briefing signatures <IconChevronRight size={14} />
            </button>
          </div>
        </Card>

        {/* Last 5 shifts */}
        <Card padding={0}>
          <div style={{ padding: '12px 14px 8px' }} className="eyebrow">RECENT SHIFTS</div>
          <div style={{ borderTop: '1px solid var(--line)' }}>
            {history.slice(0, 5).map((h, i) => {
              const ac = codeByValue(h.code);
              return (
                <div key={h.date} style={{
                  display: 'grid', gridTemplateColumns: 'auto 1fr auto', alignItems: 'center', gap: 10,
                  padding: '9px 14px',
                  borderTop: i === 0 ? 'none' : '1px solid var(--line)',
                }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--muted)', minWidth: 50 }}>{h.date.slice(5)}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      <span className="mono" style={{ color: GROUP_COLORS[ac?.group || 'Field'], fontWeight: 700, marginRight: 6 }}>{h.code}</span>
                      {ac?.short || ac?.label}
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--muted-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {h.job}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{h.hours.toFixed(1)}h</span>
                    {h.ot > 0 && <div style={{ fontSize: 10, color: 'var(--warn)' }}>+{h.ot.toFixed(1)} OT</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

// ─── Clock card ────────────────────────────────────────────────
function ClockCard({ isOn, onBreak, liveHrs, startedAt, currentAC, breakMin, clockIn, clockOut, toggleBreak, switchCode }) {
  const [switchOpen, setSwitchOpen] = useState(false);
  const overEight = liveHrs > 8;

  return (
    <div style={{
      background: isOn
        ? 'linear-gradient(135deg, #15191F 0%, #1F2933 100%)'
        : 'var(--panel)',
      color: isOn ? '#fff' : 'var(--text)',
      borderRadius: 18,
      border: isOn ? '1px solid #2a3340' : '1px solid var(--line)',
      padding: '20px 24px',
      position: 'relative',
      overflow: 'hidden',
      boxShadow: isOn ? '0 12px 30px rgba(0,0,0,0.25)' : 'var(--shadow-sm)',
    }}>
      {isOn && (
        <div style={{
          position: 'absolute', top: -60, right: -80, width: 280, height: 280,
          borderRadius: '50%', background: 'var(--accent)', opacity: 0.18, filter: 'blur(8px)',
        }} />
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <StatusDot tone={isOn ? (onBreak ? 'warn' : 'good') : 'muted'} pulse={isOn && !onBreak} size={10} />
          <span className="eyebrow" style={{ color: isOn ? 'rgba(255,255,255,0.7)' : 'var(--muted)' }}>
            {isOn ? (onBreak ? 'On break' : 'On the clock') : 'Off duty'}
          </span>
          {isOn && (
            <span className="mono" style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginLeft: 8 }}>
              since {fmtTime(startedAt)}
            </span>
          )}
        </div>
        {isOn && overEight && (
          <Badge tone="warn">{`+${(liveHrs - 8).toFixed(1)}h OT`}</Badge>
        )}
      </div>

      {/* Big clock or CTA */}
      <div style={{ marginTop: 14, display: 'flex', alignItems: 'flex-end', gap: 28, position: 'relative' }}>
        {isOn ? (
          <>
            <div className="mono tnum" style={{ fontSize: 84, fontWeight: 600, letterSpacing: -2, lineHeight: 0.95 }}>
              {fmtClock(liveHrs)}
              <span style={{ display: 'inline-block', width: 4, marginLeft: 4, opacity: 0.7, animation: 'blink-cursor 1.2s steps(2) infinite' }}>|</span>
            </div>
            <div style={{ paddingBottom: 6, flex: 1 }}>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginBottom: 4 }}>CURRENT ACTIVITY</div>
              <button onClick={() => setSwitchOpen(true)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 14px',
                background: 'rgba(255,255,255,0.08)',
                border: '1px solid rgba(255,255,255,0.16)',
                borderRadius: 12, color: '#fff', cursor: 'pointer',
              }}>
                <span className="mono" style={{
                  fontSize: 12, fontWeight: 700,
                  background: 'var(--accent)', padding: '3px 7px', borderRadius: 5,
                }}>{currentAC?.code}</span>
                <span style={{ fontSize: 13.5, fontWeight: 500 }}>{currentAC?.short || currentAC?.label}</span>
                <IconChevronRight size={14} style={{ opacity: 0.6 }} />
              </button>
              {breakMin > 0 && (
                <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.5)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 5 }}>
                  <IconPause size={11} /> {breakMin}m break taken
                </div>
              )}
            </div>
          </>
        ) : (
          <>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, marginBottom: 2 }}>
                Start of shift
              </div>
              <div style={{ fontSize: 13.5, color: 'var(--muted)' }}>
                Clock in to enable the briefing and field report.
              </div>
            </div>
          </>
        )}
      </div>

      {/* Action row */}
      <div style={{ display: 'flex', gap: 10, marginTop: 18, position: 'relative' }}>
        {isOn ? (
          <>
            <Button
              variant={onBreak ? 'success' : 'secondary'}
              size="lg"
              icon={onBreak ? <IconPlay size={16} /> : <IconPause size={16} />}
              style={{
                flex: 1,
                background: onBreak ? undefined : 'rgba(255,255,255,0.10)',
                color: '#fff',
                borderColor: 'rgba(255,255,255,0.16)',
              }}
              onClick={toggleBreak}
            >
              {onBreak ? 'Resume work' : 'Take break'}
            </Button>
            <Button
              variant="primary"
              size="lg"
              icon={<IconStop size={14} />}
              style={{ flex: 2 }}
              onClick={clockOut}
            >
              Clock out
            </Button>
          </>
        ) : (
          <Button variant="dark" size="lg" icon={<IconPlay size={16} />} onClick={clockIn} style={{ width: '100%' }}>
            Clock in · GPS will be captured
          </Button>
        )}
      </div>

      <SwitchActivitySheet
        open={switchOpen}
        currentCode={currentAC?.code}
        onClose={() => setSwitchOpen(false)}
        onPick={(c) => { switchCode(c); setSwitchOpen(false); }}
      />
    </div>
  );
}

// ─── Activity-switch sheet ─────────────────────────────────────
function SwitchActivitySheet({ open, currentCode, onClose, onPick }) {
  const [q, setQ] = useState('');
  const [picked, setPicked] = useState(null);

  useEffect(() => { if (open) { setQ(''); setPicked(null); } }, [open]);

  if (!open) return null;

  const matches = ACTIVITY_CODES.filter(t => {
    if (!q) return true;
    const s = q.toLowerCase();
    return t.code.toLowerCase().includes(s) || t.label.toLowerCase().includes(s) || (t.short || '').toLowerCase().includes(s);
  });
  const grouped = GROUP_ORDER.map(g => [g, matches.filter(m => m.group === g)]).filter(([, items]) => items.length);

  return (
    <Sheet open={open} onClose={onClose} title="Switch activity code" height="86%">
      <div className="eyebrow" style={{ marginTop: -6, marginBottom: 10 }}>
        Closes the current block and starts a new one
      </div>
      <div style={{ position: 'relative', marginBottom: 14 }}>
        <IconSearch size={16} style={{ position: 'absolute', top: 12, left: 12, color: 'var(--muted)' }} />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search code or activity…"
          style={{
            width: '100%', padding: '10px 12px 10px 38px',
            border: '1px solid var(--line-strong)', borderRadius: 10,
            fontSize: 14, fontFamily: 'inherit', background: 'var(--panel)', outline: 'none',
          }}
        />
      </div>
      <div style={{ maxHeight: 380, overflowY: 'auto', margin: '0 -4px', padding: '0 4px' }}>
        {grouped.map(([g, items]) => (
          <div key={g} style={{ marginBottom: 12 }}>
            <div style={{
              position: 'sticky', top: 0, background: 'var(--panel)', zIndex: 1,
              padding: '8px 4px', display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <span className="eyebrow" style={{ color: GROUP_COLORS[g] }}>{g}</span>
              <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{items.length}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {items.map(t => {
                const on = picked === t.code;
                const current = t.code === currentCode;
                return (
                  <button key={t.code}
                    disabled={current}
                    onClick={() => setPicked(t.code)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '10px 12px',
                      background: on ? 'var(--accent-soft)' : 'transparent',
                      border: `1px solid ${on ? 'var(--accent)' : 'transparent'}`,
                      borderRadius: 10, cursor: current ? 'default' : 'pointer',
                      textAlign: 'left', width: '100%',
                      opacity: current ? 0.45 : 1,
                    }}>
                    <span className="mono" style={{
                      fontSize: 12, fontWeight: 700,
                      padding: '4px 8px', borderRadius: 5,
                      background: on ? 'var(--accent)' : 'var(--panel-2)',
                      color: on ? '#fff' : 'var(--text-2)',
                      minWidth: 48, textAlign: 'center', flexShrink: 0,
                    }}>{t.code}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{t.label}</div>
                    </div>
                    {current && <Badge tone="neutral">Current</Badge>}
                    {on && <IconCheckCircle size={18} style={{ color: 'var(--accent)' }} />}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        <Button variant="secondary" style={{ flex: 1 }} onClick={onClose}>Cancel</Button>
        <Button variant="primary" disabled={!picked} icon={<IconCheck size={16} />} style={{ flex: 2 }}
          onClick={() => picked && onPick(picked)}>
          Switch{picked ? ` · ${picked}` : ''}
        </Button>
      </div>
    </Sheet>
  );
}

// ─── Compliance tile ───────────────────────────────────────────
function ComplianceTile({ title, sub, status, progress, onClick, icon }) {
  // status: 'todo' | 'done' | 'locked'
  const tones = {
    todo:   { bg: 'var(--panel)',        border: '1px solid var(--line)',           dot: 'var(--warn)', pillTone: 'warn',    pillTxt: 'Not signed' },
    done:   { bg: 'var(--good-soft)',    border: '1px solid var(--good)',           dot: 'var(--good)', pillTone: 'good',    pillTxt: 'Complete' },
    locked: { bg: 'var(--panel-2)',      border: '1px dashed var(--line-strong)',   dot: 'var(--muted-2)', pillTone: 'neutral', pillTxt: 'Locked' },
  }[status] || {};
  const isLocked = status === 'locked';
  return (
    <button onClick={() => !isLocked && onClick()} disabled={isLocked} style={{
      background: tones.bg, border: tones.border, borderRadius: 14,
      padding: '14px 16px', textAlign: 'left',
      cursor: isLocked ? 'not-allowed' : 'pointer',
      opacity: isLocked ? 0.7 : 1,
      display: 'flex', flexDirection: 'column', gap: 8,
      transition: 'all 120ms ease',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10,
          background: status === 'done' ? '#fff' : 'var(--panel-2)',
          color: status === 'done' ? 'var(--good)' : 'var(--text-2)',
          display: 'grid', placeItems: 'center',
        }}>{icon}</div>
        <Badge tone={tones.pillTone}>{tones.pillTxt}</Badge>
      </div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 16, letterSpacing: -0.2 }}>{title}</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>{sub}</div>
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--muted-2)', marginTop: 2 }}>{progress}</div>
    </button>
  );
}

// ─── Info cell (table-style stat in a card footer) ─────────────
const InfoCell = ({ label, value, divider }) => (
  <div style={{
    padding: '12px 16px',
    borderLeft: divider ? '1px solid var(--line)' : 'none',
  }}>
    <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
    <div style={{ fontSize: 13.5, fontWeight: 600, marginTop: 3, lineHeight: 1.3 }}>{value}</div>
  </div>
);

// ─── Mini GPS map ──────────────────────────────────────────────
function GpsMiniMap({ label }) {
  return (
    <Card padding={0} style={{ overflow: 'hidden' }}>
      <div style={{ position: 'relative', height: 140, background: 'linear-gradient(180deg, #C9D4C0 0%, #DCE4D2 100%)', overflow: 'hidden' }}>
        {/* Pretend topo lines */}
        <svg width="100%" height="100%" viewBox="0 0 380 140" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0 }}>
          <g fill="none" stroke="#a8b59c" strokeWidth="0.6" opacity="0.6">
            <path d="M0 100 Q 80 70 160 80 T 380 70" />
            <path d="M0 110 Q 80 88 160 95 T 380 88" />
            <path d="M0 125 Q 80 105 160 110 T 380 102" />
            <path d="M0 60 Q 100 30 200 40 T 380 30" />
          </g>
          {/* River */}
          <path d="M-20 130 Q 60 100 140 110 Q 220 120 300 90 Q 360 70 400 80"
            stroke="#7ea3c7" strokeWidth="6" fill="none" opacity="0.7" />
          {/* Track line */}
          <line x1="0" y1="78" x2="380" y2="68" stroke="#3a4451" strokeWidth="2" />
          <line x1="0" y1="78" x2="380" y2="68" stroke="#fff" strokeWidth="1" strokeDasharray="6 8" />
          {/* Roads */}
          <path d="M0 120 L 380 130" stroke="#d4c89e" strokeWidth="3" />
        </svg>
        {/* Pin */}
        <div style={{
          position: 'absolute', left: '52%', top: '50%', transform: 'translate(-50%, -100%)',
          display: 'flex', flexDirection: 'column', alignItems: 'center',
        }}>
          <div style={{
            width: 26, height: 26, borderRadius: '50%',
            background: 'var(--accent)',
            border: '3px solid #fff',
            boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
          }} />
          <div style={{
            width: 2, height: 10, background: 'var(--accent)', marginTop: -1,
          }} />
        </div>
        {/* Pulse ring */}
        <div style={{
          position: 'absolute', left: '52%', top: '50%', transform: 'translate(-50%, -100%)',
          width: 60, height: 60, borderRadius: '50%',
          background: 'var(--accent)', opacity: 0.18,
          animation: 'pulse-dot 2s ease-in-out infinite',
        }} />
        <Badge tone="dark" style={{ position: 'absolute', top: 10, left: 10 }}>
          <StatusDot tone="good" size={6} pulse /> Live GPS
        </Badge>
      </div>
      <div style={{ padding: '10px 14px' }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>LAST FIX · 6s AGO</div>
        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{label}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
          47.7128°N · 121.3525°W · ±4m
        </div>
      </div>
    </Card>
  );
}

// ─── Call row ──────────────────────────────────────────────────
function CallRow({ label, sub, tel, tone = 'info', last }) {
  const tones = { bad: { bg: 'var(--bad-soft)', fg: 'var(--bad)' }, info: { bg: 'var(--info-soft)', fg: 'var(--info)' }, accent: { bg: 'var(--accent-soft)', fg: 'var(--accent-deep)' } }[tone];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '8px 0',
      borderBottom: last ? 'none' : '1px solid var(--line)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: tones.bg, color: tones.fg,
        display: 'grid', placeItems: 'center',
      }}>
        <PhoneIcon />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{label}</div>
        <div style={{ fontSize: 11.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</div>
      </div>
      <div className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{tel}</div>
    </div>
  );
}

const PhoneIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z" />
  </svg>
);

Object.assign(window, { ScreenToday });
