/* global React, window */
const { useState: useRtState, useEffect: useRtEffect } = React;

function rtName(s) {
  if (s.employee && (s.employee.first_name || s.employee.last_name)) return `${s.employee.first_name || ''} ${s.employee.last_name || ''}`.trim();
  if (s.first_name || s.last_name) return `${s.first_name || ''} ${s.last_name || ''}`.trim();
  return s.employee_name || 'ไม่รู้จัก';
}
function rtId(s) { return s.employee?.id || s.employeeId || s.employee_id || null; }
function rtTime(s) {
  const d = s.time instanceof Date ? s.time : (s.scan_time ? new Date(String(s.scan_time).replace(' ', 'T')) : new Date());
  const p = (n) => String(n).padStart(2, '0');
  return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function rtDir(s) { return (s.direction || s.type) === 'out' ? 'out' : 'in'; }
function rtPct(c) { const v = parseFloat(c); if (Number.isNaN(v)) return null; return v <= 1 ? v * 100 : v; }
function rtPhoto(s) {
  if (s.photo_url) return s.photo_url;
  if (s.employee && s.employee.photo_path) return `/faces/${s.employee.photo_path}`;
  const id = rtId(s);
  return id ? `/faces/${id}.jpg` : null;
}

// Circular avatar with the person's face; falls back to the person-icon placeholder.
function RtAvatar({ scan, size = 46 }) {
  const [err, setErr] = useRtState(false);
  const src = err ? '/img/avatar-person.svg' : (rtPhoto(scan) || '/img/avatar-person.svg');
  const eid = rtId(scan);
  return <img src={src} alt="" onError={() => setErr(true)}
    onClick={() => eid && window.openProfile && window.openProfile(eid)} title={eid ? 'ดูโปรไฟล์' : ''}
    style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: 'none', cursor: eid ? 'pointer' : 'default',
      border: '2px solid var(--surface)', boxShadow: '0 0 0 1px var(--line)' }} />;
}

function RtStat({ k, v, u }) {
  return (
    <div className="gv-card" style={{ padding: '16px 20px', boxShadow: 'var(--shadow-sm)' }}>
      <div style={{ fontSize: 12.5, color: 'var(--ink-4)', fontWeight: 500 }}>{k}</div>
      <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, marginTop: 4, lineHeight: 1 }}>
        {v}{u && <small style={{ fontSize: 13, color: 'var(--ink-4)', fontWeight: 500, marginLeft: 4 }}>{u}</small>}
      </div>
    </div>
  );
}

// สแกนสด / LIVE — soft hrzoft realtime stream with circular face avatars.
function RealtimePage() {
  const [logs, setLogs] = useRtState(window.RECENT_SCANS || []);

  useRtEffect(() => {
    if (!window.scanStream) return undefined;
    return window.scanStream.subscribe((scan) => setLogs((prev) => [scan, ...prev].slice(0, 50)));
  }, []);

  const devices = window.DEVICES || [];
  const online = devices.filter((d) => { const t = d.last_seen ? Date.parse(String(d.last_seen).replace(' ', 'T')) : 0; return t && (Date.now() - t) < 5 * 60 * 1000; }).length;
  const confVals = logs.map((l) => rtPct(l.confidence)).filter((n) => n != null && n > 0);
  const avgConf = confVals.length ? (confVals.reduce((a, b) => a + b, 0) / confVals.length).toFixed(1) : '—';
  const ins = logs.filter((l) => rtDir(l) === 'in').length;

  const stats = [
    { k: 'สแกนเซสชันนี้', v: logs.length, u: 'ครั้ง' },
    { k: 'แม่นยำเฉลี่ย', v: avgConf === '—' ? '—' : avgConf + '%', u: '' },
    { k: 'เข้างาน', v: ins, u: 'ครั้ง' },
    { k: 'อุปกรณ์ออนไลน์', v: `${online}/${devices.length}`, u: '' },
  ];

  return (
    <div data-screen-label="Realtime">
      <div style={{ marginBottom: 18 }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>สแกนเรียลไทม์ / Live</h1>
        <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>เหตุการณ์การสแกนใบหน้าจากเครื่อง แบบเรียลไทม์</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {stats.map((s) => <RtStat key={s.k} {...s} />)}
      </div>

      <div className="gv-card">
        <div className="gv-card-h">
          <b style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--coral)', animation: 'osblink 1.3s infinite', display: 'inline-block' }} />
            สตรีมการสแกนสด
          </b>
          <span className="gv-chip c-green">{logs.length} เหตุการณ์</span>
        </div>
        <div className="gv-card-b" style={{ paddingTop: 6 }}>
          {logs.length === 0 ? (
            <div className="gv-empty">— รอการสแกน · เชื่อมต่อเครื่องแล้วเหตุการณ์จะขึ้นที่นี่ —</div>
          ) : logs.map((f, i) => {
            const dir = rtDir(f);
            const pct = rtPct(f.confidence);
            return (
              <div key={i} className="gv-row" style={{ animation: i === 0 ? 'osslide .4s ease' : 'none' }}>
                <RtAvatar scan={f} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{rtName(f)}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 1 }}>
                    {(f.department?.name || f.department_name || '—')}{rtId(f) ? ` · ${rtId(f)}` : ''}{f.device_name ? ` · ${f.device_name}` : ''}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  {pct != null && <span className="tnum" style={{ fontSize: 12.5, color: 'var(--mint-ink)', fontWeight: 600 }}>{pct.toFixed(1)}%</span>}
                  <span className={`gv-chip ${dir === 'out' ? 'c-blue' : 'c-green'}`}>{dir === 'out' ? 'ออกงาน' : 'เข้างาน'}</span>
                  <span className="tnum" style={{ fontSize: 15, fontWeight: 700, minWidth: 74, textAlign: 'right' }}>{rtTime(f)}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.RealtimePage = RealtimePage;
