/* global React, window */
const { useState: useRepState, useEffect: useRepEffect } = React;

// Circular face avatar (clickable → profile).
function RepAvatar({ id, size = 36 }) {
  const [err, setErr] = useRepState(false);
  const src = (err || !id) ? '/img/avatar-person.svg' : `/faces/${id}.jpg`;
  return <img src={src} alt="" onError={() => setErr(true)}
    onClick={() => id && window.openProfile && window.openProfile(id)} title={id ? 'ดูโปรไฟล์' : ''}
    style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: 'none',
      cursor: id ? 'pointer' : 'default', border: '1px solid var(--line)' }} />;
}

const REP_STATUS = {
  present: { l: 'มา', cls: 'c-green', bg: 'var(--mint)' },
  in_only: { l: 'ยังไม่ออก', cls: 'c-amber', bg: 'var(--yellow)' },
  absent:  { l: 'ขาด', cls: 'c-coral', bg: 'var(--coral)' },
  leave:   { l: 'ลา', cls: 'c-violet', bg: 'var(--magenta)' },
  holiday: { l: 'หยุด', cls: 'c-gray', bg: 'var(--line-2)' },
  off:     { l: 'หยุด', cls: 'c-gray', bg: 'var(--line-2)' },
};
const repFmtDate = (iso) => { const [y, m, d] = iso.split('-').map(Number); return `${d}/${m}/${y + 543}`; };
const repShift = (iso, n) => { const d = new Date(iso + 'T00:00:00'); d.setDate(d.getDate() + n); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
const repShiftMonth = (iso, n) => { const d = new Date(iso.slice(0, 7) + '-01T00:00:00'); d.setMonth(d.getMonth() + n); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-01`; };

// รายงาน — รายวัน / รายสัปดาห์ / รายเดือน: KPI + กราฟแนวโน้ม + อัตรามาต่อกอง + ตารางรายคน + Excel
function ReportPage({ role }) {
  const today = window.TODAY || new Date().toISOString().slice(0, 10);
  const [period, setPeriod] = useRepState(() => { try { return localStorage.getItem('fit.rep.period') || 'day'; } catch (_) { return 'day'; } });
  const [date, setDate] = useRepState(today);
  const [deptFilter, setDeptFilter] = useRepState('all');
  const [q, setQ] = useRepState('');
  const [statusF, setStatusF] = useRepState('all');
  const [rep, setRep] = useRepState(null);
  const [loading, setLoading] = useRepState(true);
  const [sortKey, setSortKey] = useRepState('name');

  const load = async () => {
    setLoading(true);
    const p = new URLSearchParams({ period, date });
    if (deptFilter !== 'all') p.set('department_id', deptFilter);
    const r = await fetch('/api/attendance/report?' + p, { credentials: 'include' });
    if (r.ok) setRep(await r.json());
    setLoading(false);
  };
  useRepEffect(() => { load(); try { localStorage.setItem('fit.rep.period', period); } catch (_) {} }, [period, date, deptFilter]);

  const step = (n) => setDate(period === 'month' ? repShiftMonth(date, n) : repShift(date, period === 'week' ? 7 * n : n));
  const exportXlsx = () => { const p = new URLSearchParams({ period, date, format: 'xlsx' }); if (deptFilter !== 'all') p.set('department_id', deptFilter); window.open('/api/attendance/report?' + p, '_blank'); };

  const kpi = rep ? rep.kpi : null;
  const isDay = period === 'day';
  const qq = q.trim().toLowerCase();
  const dayCell = (r) => (rep && r.cells[rep.from]) || null;
  const rowKind = (r) => { if (isDay) { const c = dayCell(r); if (!c) return 'none'; if ((c.s === 'present' || c.s === 'in_only') && c.late) return 'late'; return c.s; } return null; };
  let rows = rep ? rep.rows.filter((r) => !qq || [r.employee_id, r.first_name, r.last_name, r.department_name, r.position].some((v) => String(v || '').toLowerCase().includes(qq))) : [];
  if (isDay && statusF !== 'all') rows = rows.filter((r) => { const k = rowKind(r); return statusF === 'present' ? (k === 'present' || k === 'in_only') : k === statusF; });
  if (!isDay && statusF !== 'all') rows = rows.filter((r) => statusF === 'late' ? r.late > 0 : statusF === 'absent' ? r.absent > 0 : statusF === 'leave' ? r.leave > 0 : true);
  const sorters = {
    name: (a, b) => (a.department_name || '').localeCompare(b.department_name || '', 'th') || a.first_name.localeCompare(b.first_name, 'th'),
    late: (a, b) => (isDay ? ((dayCell(b) || {}).late || 0) - ((dayCell(a) || {}).late || 0) : b.late - a.late),
    absent: (a, b) => b.absent - a.absent, rate: (a, b) => (a.rate ?? 101) - (b.rate ?? 101),
    in: (a, b) => (((dayCell(a) || {}).in) || '99:99').localeCompare(((dayCell(b) || {}).in) || '99:99'),
  };
  rows = [...rows].sort(sorters[sortKey] || sorters.name);

  const Kpi = ({ label, value, sub, color, icon, onClick, active }) => (
    <button onClick={onClick} className="gv-card" style={{ padding: '14px 16px', textAlign: 'left', border: active ? `2px solid ${color}` : '1px solid var(--line)', cursor: onClick ? 'pointer' : 'default', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface)' }}>
      <div style={{ width: 40, height: 40, borderRadius: 12, background: color, opacity: .15, position: 'absolute' }}/>
      <div style={{ width: 40, height: 40, borderRadius: 12, display: 'grid', placeItems: 'center', fontSize: 19, position: 'relative' }}>{icon}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12, color: 'var(--ink-4)', fontWeight: 600 }}>{label}</div>
        <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 800, lineHeight: 1.1, color }}>{value}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--ink-5)' }}>{sub}</div>}
      </div>
    </button>
  );

  return (
    <div data-screen-label="Report">
      {/* header + controls */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 12, flexWrap: 'wrap', marginBottom: 14 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>รายงานการมาทำงาน</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>{rep ? rep.label : '…'}{rep && deptFilter !== 'all' ? ` · ${((window.DEPARTMENTS || []).find((d) => String(d.id) === deptFilter) || {}).name || ''}` : ''}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <div className="gv-seg">
            {[['day', 'รายวัน'], ['week', 'รายสัปดาห์'], ['month', 'รายเดือน']].map(([k, l]) => <button key={k} className={period === k ? 'on' : ''} onClick={() => setPeriod(k)}>{l}</button>)}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <button className="gv-btn no sm" onClick={() => step(-1)} title="ก่อนหน้า">◀</button>
            {period === 'month'
              ? <input className="gv-input" type="month" value={date.slice(0, 7)} onChange={(e) => setDate(e.target.value + '-01')} style={{ width: 150 }}/>
              : <input className="gv-input" type="date" value={date} onChange={(e) => e.target.value && setDate(e.target.value)} style={{ width: 150 }}/>}
            <button className="gv-btn no sm" onClick={() => step(1)} title="ถัดไป">▶</button>
            <button className="gv-btn no sm" onClick={() => setDate(today)}>วันนี้</button>
          </div>
          {role !== 'manager' && (
            <select className="gv-select" value={deptFilter} onChange={(e) => setDeptFilter(e.target.value)} style={{ width: 170 }}>
              <option value="all">ทุกกอง</option>
              {(window.DEPARTMENTS || []).map((d) => <option key={d.id} value={String(d.id)}>{d.name}</option>)}
            </select>
          )}
          <button className="gv-btn dark sm" onClick={exportXlsx} disabled={!rep}>⬇ Excel</button>
        </div>
      </div>

      {/* KPI */}
      {kpi && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 10, marginBottom: 14, position: 'relative' }}>
          <Kpi icon="👥" label="พนักงาน" value={kpi.employees} sub={isDay ? 'คน' : `${kpi.workdays} วัน-คนทำงาน`} color="var(--navy)" onClick={() => setStatusF('all')} active={statusF === 'all'}/>
          <Kpi icon="✅" label={isDay ? 'มาทำงาน' : 'มาทำงาน (วัน-คน)'} value={kpi.present} sub={kpi.rate != null ? `อัตรามา ${kpi.rate}%` : '—'} color="var(--mint-ink)" onClick={() => setStatusF('present')} active={statusF === 'present'}/>
          <Kpi icon="⏰" label="สาย" value={kpi.late} sub={kpi.late_min ? `รวม ${kpi.late_hours} ชม.` : 'ครั้ง'} color="var(--yellow-ink)" onClick={() => setStatusF('late')} active={statusF === 'late'}/>
          <Kpi icon="❌" label="ขาด" value={kpi.absent} sub={isDay ? 'คน' : 'วัน-คน'} color="var(--coral-ink)" onClick={() => setStatusF('absent')} active={statusF === 'absent'}/>
          <Kpi icon="🌴" label="ลา" value={kpi.leave} sub={isDay ? 'คน' : 'วัน-คน'} color="var(--magenta-ink)" onClick={() => setStatusF('leave')} active={statusF === 'leave'}/>
          <Kpi icon="🕘" label="OT" value={kpi.ot_hours} sub="ชั่วโมง" color="var(--primary-ink)"/>
        </div>
      )}

      {/* charts */}
      {rep && (
        <div style={{ display: 'grid', gridTemplateColumns: isDay ? '1fr' : '1.6fr 1fr', gap: 14, marginBottom: 14 }}>
          {!isDay && <RepTrend rep={rep} onPick={(d) => { setPeriod('day'); setDate(d); }}/>}
          <RepDeptBars rep={rep}/>
        </div>
      )}

      {/* table */}
      <div className="gv-card">
        <div className="gv-card-h" style={{ flexWrap: 'wrap', gap: 10 }}>
          <b>รายชื่อ <span style={{ fontWeight: 400, color: 'var(--ink-4)', fontSize: 12.5 }}>· {rows.length} คน</span></b>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            <input className="gv-input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="ค้นชื่อ / รหัส / กอง" style={{ width: 180 }}/>
            <select className="gv-select" value={sortKey} onChange={(e) => setSortKey(e.target.value)} style={{ width: 'auto' }}>
              <option value="name">เรียงตามกอง/ชื่อ</option>
              {isDay && <option value="in">เรียงเวลาเข้า</option>}
              <option value="late">สายมากสุดก่อน</option>
              {!isDay && <option value="absent">ขาดมากสุดก่อน</option>}
              {!isDay && <option value="rate">อัตรามาน้อยสุดก่อน</option>}
            </select>
          </div>
        </div>
        <div style={{ overflowX: 'auto', maxHeight: 'calc(100vh - 300px)', overflowY: 'auto' }}>
          {loading || !rep ? <div className="gv-empty">กำลังโหลด…</div>
            : rows.length === 0 ? <div className="gv-empty">— ไม่มีข้อมูล —</div>
            : isDay ? <RepDayTable rows={rows} date={rep.from} rowKind={rowKind}/>
            : period === 'week' ? <RepWeekTable rows={rows} rep={rep}/>
            : <RepMonthTable rows={rows} rep={rep}/>}
        </div>
      </div>
    </div>
  );
}

// กราฟแท่งซ้อนต่อวัน (มา / สาย / ขาด / ลา) — SVG ล้วน ไม่ใช้ไลบรารี
function RepTrend({ rep, onPick }) {
  const days = rep.per_day;
  const max = Math.max(1, ...days.map((d) => d.total));
  const W = 100, H = 46, gap = days.length > 14 ? 0.6 : 1.4;
  const bw = (W - gap * (days.length - 1)) / days.length;
  const [hover, setHover] = useRepState(null);
  return (
    <div className="gv-card" style={{ padding: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <b style={{ fontSize: 14 }}>แนวโน้มรายวัน</b>
        <div style={{ display: 'flex', gap: 10, fontSize: 11.5, color: 'var(--ink-4)' }}>
          {[['มาตรงเวลา', 'var(--mint)'], ['สาย', 'var(--yellow)'], ['ลา', 'var(--magenta)'], ['ขาด', 'var(--coral)']].map(([l, c]) => <span key={l}><i style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 3, background: c, marginRight: 4 }}/>{l}</span>)}
        </div>
      </div>
      <div style={{ position: 'relative' }}>
        <svg viewBox={`0 0 ${W} ${H + 8}`} style={{ width: '100%', height: 170, display: 'block' }} preserveAspectRatio="none">
          {days.map((d, i) => {
            const x = i * (bw + gap);
            const segs = [[d.present - d.late, 'var(--mint)'], [d.late, 'var(--yellow)'], [d.leave, 'var(--magenta)'], [d.absent, 'var(--coral)']];
            let y = H;
            return (
              <g key={d.date} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} onClick={() => onPick(d.date)} style={{ cursor: 'pointer' }}>
                <rect x={x} y={0} width={bw} height={H} fill={d.weekend || d.holiday ? 'var(--surface-2)' : 'transparent'} rx={0.6}/>
                {segs.map(([v, c], k) => { if (!v) return null; const h = (v / max) * H; y -= h; return <rect key={k} x={x} y={y} width={bw} height={h} fill={c} opacity={hover === null || hover === i ? 1 : .45}/>; })}
                <text x={x + bw / 2} y={H + 6} textAnchor="middle" fontSize={days.length > 14 ? 2.4 : 3.2} fill="var(--ink-5)">{days.length > 14 ? (d.day % 2 ? d.day : '') : d.dow_th}</text>
              </g>
            );
          })}
        </svg>
        {hover !== null && (() => { const d = days[hover]; return (
          <div style={{ position: 'absolute', left: `${Math.min(80, (hover / days.length) * 100)}%`, top: 0, background: 'var(--navy)', color: '#fff', borderRadius: 10, padding: '6px 10px', fontSize: 11.5, pointerEvents: 'none', whiteSpace: 'nowrap' }}>
            <b>{repFmtDate(d.date)} ({d.dow_th}){d.holiday ? ` · ${d.holiday}` : ''}</b><br/>มา {d.present} · สาย {d.late} · ลา {d.leave} · ขาด {d.absent}
          </div>); })()}
      </div>
      <div style={{ fontSize: 11, color: 'var(--ink-5)', marginTop: 4 }}>คลิกแท่งเพื่อดูรายวัน · พื้นเทา = วันหยุด</div>
    </div>
  );
}

// อัตรามาทำงานต่อกอง
function RepDeptBars({ rep }) {
  const list = rep.by_department;
  return (
    <div className="gv-card" style={{ padding: 16 }}>
      <b style={{ fontSize: 14 }}>อัตรามาทำงานตามกอง</b>
      <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 9 }}>
        {list.length === 0 && <div className="gv-empty">—</div>}
        {list.map((d) => (
          <div key={d.name}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 3 }}>
              <span style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '60%' }}>{d.name}</span>
              <span className="tnum" style={{ color: 'var(--ink-4)' }}>{d.rate != null ? `${d.rate}%` : '—'} · มา {d.present}{d.late ? ` · สาย ${d.late}` : ''}{d.absent ? ` · ขาด ${d.absent}` : ''} / {d.employees} คน</span>
            </div>
            <div className="gv-bar" style={{ height: 8 }}><i style={{ width: `${d.rate || 0}%`, background: d.rate == null ? 'var(--line-2)' : d.rate >= 90 ? 'var(--mint)' : d.rate >= 70 ? 'var(--yellow)' : 'var(--coral)' }}/></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RepName({ r }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <RepAvatar id={r.employee_id} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: 'nowrap' }}>{r.title}{r.first_name} {r.last_name}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-4)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 220 }}>{r.employee_id}{r.department_name ? ` · ${r.department_name}` : ''}</div>
      </div>
    </div>
  );
}

// รายวัน: เข้า/ออก/สถานะ/สาย/ชม.ทำงาน
function RepDayTable({ rows, date, rowKind }) {
  return (
    <table className="gv-tbl">
      <thead><tr><th>พนักงาน</th><th>ตำแหน่ง</th><th style={{ textAlign: 'center' }}>สถานะ</th><th style={{ textAlign: 'center' }}>เข้า</th><th style={{ textAlign: 'center' }}>ออก</th><th style={{ textAlign: 'center' }}>สาย</th><th style={{ textAlign: 'center' }}>ชม.ทำงาน</th><th style={{ textAlign: 'center' }}>OT</th></tr></thead>
      <tbody>
        {rows.map((r) => {
          const c = r.cells[date]; const k = rowKind(r);
          const st = !c ? { l: 'ไม่มีข้อมูล', cls: 'c-gray' } : k === 'late' ? { l: `สาย ${c.late} น.`, cls: 'c-amber' } : (REP_STATUS[c.s] || { l: c.s, cls: 'c-gray' });
          return (
            <tr key={r.employee_id}>
              <td><RepName r={r}/></td>
              <td style={{ fontSize: 12.5, color: 'var(--ink-4)' }}>{r.position || '—'}</td>
              <td style={{ textAlign: 'center' }}><span className={`gv-chip ${st.cls}`}>{st.l}</span></td>
              <td className="tnum" style={{ textAlign: 'center', fontWeight: 600, color: k === 'late' ? 'var(--yellow-ink)' : 'var(--ink)' }}>{c && c.in ? c.in : '—'}</td>
              <td className="tnum" style={{ textAlign: 'center' }}>{c && c.out ? c.out : (c && c.s === 'in_only' ? <span style={{ color: 'var(--yellow-ink)', fontSize: 12 }}>ยังไม่ออก</span> : '—')}</td>
              <td className="tnum" style={{ textAlign: 'center', color: c && c.late ? 'var(--yellow-ink)' : 'var(--ink-5)' }}>{c && c.late ? `${c.late} น.` : ''}</td>
              <td className="tnum" style={{ textAlign: 'center' }}>{c && c.work ? (c.work / 60).toFixed(1) : ''}</td>
              <td className="tnum" style={{ textAlign: 'center', color: c && c.ot ? 'var(--mint-ink)' : 'var(--ink-5)' }}>{c && c.ot ? `${c.ot} น.` : ''}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// รายสัปดาห์: 7 ช่อง จ–อา ต่อคน (จุดสี + เวลาเข้า) + สรุป
function RepWeekTable({ rows, rep }) {
  const cellOf = (c, d) => {
    if (!c) return <span style={{ color: 'var(--ink-5)' }}>{d.future ? '' : '·'}</span>;
    const late = (c.s === 'present' || c.s === 'in_only') && c.late;
    const bg = late ? 'var(--yellow-soft)' : c.s === 'present' ? 'var(--mint-soft)' : c.s === 'in_only' ? 'var(--yellow-soft)' : c.s === 'absent' ? 'var(--coral-soft)' : c.s === 'leave' ? 'var(--magenta-soft)' : 'var(--surface-2)';
    const fg = late ? 'var(--yellow-ink)' : c.s === 'present' ? 'var(--mint-ink)' : c.s === 'in_only' ? 'var(--yellow-ink)' : c.s === 'absent' ? 'var(--coral-ink)' : c.s === 'leave' ? 'var(--magenta-ink)' : 'var(--ink-5)';
    const txt = (c.s === 'present' || c.s === 'in_only') ? (c.in || '✓') : (REP_STATUS[c.s] || {}).l || c.s;
    return <span className="tnum" title={`${c.in || ''}${c.out ? ' – ' + c.out : ''}${late ? ` · สาย ${c.late} น.` : ''}`} style={{ display: 'inline-block', minWidth: 50, padding: '4px 6px', borderRadius: 8, background: bg, color: fg, fontSize: 12, fontWeight: 600 }}>{txt}{late ? <small style={{ fontWeight: 400 }}> +{c.late}</small> : ''}</span>;
  };
  return (
    <table className="gv-tbl">
      <thead><tr>
        <th>พนักงาน</th>
        {rep.days.map((d) => <th key={d.date} style={{ textAlign: 'center', background: d.weekend || d.holiday ? 'var(--surface-2)' : undefined }} title={d.holiday || ''}>{d.dow_th} {d.day}{d.holiday ? ' 🎌' : ''}</th>)}
        <th style={{ textAlign: 'center' }}>มา</th><th style={{ textAlign: 'center' }}>สาย</th><th style={{ textAlign: 'center' }}>ขาด</th><th style={{ textAlign: 'center' }}>ลา</th>
      </tr></thead>
      <tbody>
        {rows.map((r) => (
          <tr key={r.employee_id}>
            <td><RepName r={r}/></td>
            {rep.days.map((d) => <td key={d.date} style={{ textAlign: 'center', padding: '8px 6px' }}>{cellOf(r.cells[d.date], d)}</td>)}
            <td className="tnum" style={{ textAlign: 'center', fontWeight: 700, color: 'var(--mint-ink)' }}>{r.present}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.late ? 'var(--yellow-ink)' : 'var(--ink-5)' }}>{r.late || ''}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.absent ? 'var(--coral-ink)' : 'var(--ink-5)' }}>{r.absent || ''}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.leave ? 'var(--magenta-ink)' : 'var(--ink-5)' }}>{r.leave || ''}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// รายเดือน: สรุปต่อคน + แถบวันเล็กๆ (heat strip) + อัตรามา
function RepMonthTable({ rows, rep }) {
  const strip = (r) => (
    <div style={{ display: 'flex', gap: 2 }} title="แถบวัน: เขียว=มา เหลือง=สาย แดง=ขาด ม่วง=ลา เทา=หยุด">
      {rep.days.map((d) => {
        const c = r.cells[d.date];
        const col = !c ? (d.weekend || d.holiday ? 'var(--line)' : (d.future ? 'transparent' : 'var(--line)')) : ((c.s === 'present' || c.s === 'in_only') ? (c.late ? 'var(--yellow)' : 'var(--mint)') : c.s === 'absent' ? 'var(--coral)' : c.s === 'leave' ? 'var(--magenta)' : 'var(--line-2)');
        return <i key={d.date} style={{ width: 6, height: 16, borderRadius: 2, background: col, border: d.future ? '1px dashed var(--line)' : 'none', boxSizing: 'border-box' }} title={`${repFmtDate(d.date)}${c && c.in ? ' เข้า ' + c.in : ''}${c && c.late ? ' สาย ' + c.late : ''}`}/>;
      })}
    </div>
  );
  return (
    <table className="gv-tbl">
      <thead><tr>
        <th>พนักงาน</th><th>รายวัน</th>
        <th style={{ textAlign: 'center' }}>มา</th><th style={{ textAlign: 'center' }}>สาย</th><th style={{ textAlign: 'center' }}>ขาด</th><th style={{ textAlign: 'center' }}>ลา</th><th style={{ textAlign: 'center' }}>OT (ชม.)</th><th style={{ minWidth: 120 }}>อัตรามา</th>
      </tr></thead>
      <tbody>
        {rows.map((r) => (
          <tr key={r.employee_id}>
            <td><RepName r={r}/></td>
            <td>{strip(r)}</td>
            <td className="tnum" style={{ textAlign: 'center', fontWeight: 700, color: 'var(--mint-ink)' }}>{r.present}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.late ? 'var(--yellow-ink)' : 'var(--ink-5)' }}>{r.late ? `${r.late}${r.late_min ? ` (${r.late_min} น.)` : ''}` : ''}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.absent ? 'var(--coral-ink)' : 'var(--ink-5)' }}>{r.absent || ''}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.leave ? 'var(--magenta-ink)' : 'var(--ink-5)' }}>{r.leave || ''}</td>
            <td className="tnum" style={{ textAlign: 'center', color: r.ot_hours ? 'var(--mint-ink)' : 'var(--ink-5)' }}>{r.ot_hours || ''}</td>
            <td>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div className="gv-bar" style={{ flex: 1, height: 8 }}><i style={{ width: `${r.rate || 0}%`, background: r.rate == null ? 'var(--line-2)' : r.rate >= 90 ? 'var(--mint)' : r.rate >= 70 ? 'var(--yellow)' : 'var(--coral)' }}/></div>
                <span className="tnum" style={{ fontSize: 12, width: 36, textAlign: 'right' }}>{r.rate != null ? `${r.rate}%` : '—'}</span>
              </div>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

window.ReportPage = ReportPage;
