// ELS HRM — Module 08: Chấm Công (Attendance) — All Screens — Tailwind utility classes

// shadcn table styling reproduced via arbitrary child variants (1 className, structure untouched)
const TABLE_CLS = "w-full border-collapse text-sm "
  + "[&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:bg-muted [&_thead_th]:px-3.5 [&_thead_th]:py-2.5 [&_thead_th]:text-left [&_thead_th]:text-xs [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-[0.04em] [&_thead_th]:text-muted-foreground [&_thead_th]:whitespace-nowrap "
  + "[&_tbody_td]:border-b [&_tbody_td]:border-border [&_tbody_td]:px-3.5 [&_tbody_td]:py-3 [&_tbody_td]:align-middle [&_tbody_td]:text-foreground "
  + "[&_tbody_tr:last-child_td]:border-0 [&_tbody_tr:hover]:bg-muted";

const TABLE_CLS_COMPACT = "w-full border-collapse text-sm "
  + "[&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:bg-muted [&_thead_th]:px-3.5 [&_thead_th]:py-2.5 [&_thead_th]:text-left [&_thead_th]:text-xs [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-[0.04em] [&_thead_th]:text-muted-foreground [&_thead_th]:whitespace-nowrap "
  + "[&_tbody_td]:border-b [&_tbody_td]:border-border [&_tbody_td]:px-3 [&_tbody_td]:py-2 [&_tbody_td]:align-middle [&_tbody_td]:text-foreground "
  + "[&_tbody_tr:last-child_td]:border-0 [&_tbody_tr:hover]:bg-muted";

const CARD = "rounded-xl border border-border bg-card shadow-xs";
const CARD_HEAD = "flex items-center justify-between gap-3 border-b border-border px-5 py-4";
const CARD_TITLE = "text-md font-semibold text-foreground";
// Recipe input dùng lại nhiều lần trong màn Cấu hình / form (đồng bộ input mockup).
const INPUT_CLS = "h-9 w-full rounded-md border border-input bg-transparent px-3 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring";

// Pill toggle (switch) — dùng ở màn Cấu hình cho các cờ bật/tắt.
const Toggle = ({ on = true }) => {
  const [v, setV] = React.useState(on);
  return (
    <button type="button" onClick={() => setV(!v)}
      className={"relative h-5 w-9 shrink-0 cursor-pointer rounded-full transition-colors " + (v ? "bg-primary" : "bg-border-strong")}>
      <span className={"absolute top-0.5 size-4 rounded-full bg-white shadow-xs transition-all " + (v ? "left-[18px]" : "left-0.5")} />
    </button>
  );
};

// Trường số có đơn vị + gợi ý — dùng lại trong màn Cấu hình.
const NumField = ({ label, value, unit, hint }) => (
  <div>
    <label className="mb-[5px] block text-xs font-medium">{label}</label>
    <div className="relative flex items-center">
      <input className={INPUT_CLS + " pr-14 tabular-nums"} type="number" defaultValue={value} />
      {unit && <span className="pointer-events-none absolute right-3 text-xs text-muted-foreground">{unit}</span>}
    </div>
    {hint && <div className="mt-1 text-xs text-muted-foreground">{hint}</div>}
  </div>
);

const ATT_LOGS = [
  { id:'a01', emp:'Nguyễn Thị Lan',  date:'16/05/2026', in:'08:02', out:'17:35', dur:'9h 33m', late:false, early:false, status:'COMPLETE'         },
  { id:'a02', emp:'Trần Minh Tuấn',  date:'16/05/2026', in:'08:42', out:'18:10', dur:'9h 28m', late:true,  early:false, status:'COMPLETE'         },
  { id:'a03', emp:'Lê Thị Hương',    date:'16/05/2026', in:'07:55', out:null,    dur:null,      late:false, early:false, status:'PUNCHED_IN'       },
  { id:'a04', emp:'Phạm Đức Long',   date:'16/05/2026', in:null,    out:null,    dur:null,      late:false, early:false, status:'ON_LEAVE'         },
  { id:'a05', emp:'Võ Thị Thu',      date:'16/05/2026', in:'09:15', out:'15:30', dur:'6h 15m',  late:true,  early:true,  status:'COMPLETE'         },
  { id:'a06', emp:'Đỗ Văn Hùng',    date:'16/05/2026', in:'08:00', out:'17:00', dur:'9h 00m',  late:false, early:false, status:'COMPLETE'         },
  { id:'a07', emp:'Bùi Thị Linh',   date:'16/05/2026', in:null,    out:null,    dur:null,      late:false, early:false, status:'FORGOT_PUNCH_OUT' },
  { id:'a08', emp:'Ngô Minh Khoa',  date:'16/05/2026', in:'08:05', out:'17:05', dur:'9h 00m',  late:false, early:false, status:'COMPLETE'         },
];

const ATT_ST = {
  COMPLETE:         { label:'Đầy đủ',        v:'success', icon:'check-circle' },
  PUNCHED_IN:       { label:'Đang làm việc', v:'info',    icon:'clock'        },
  ON_LEAVE:         { label:'Nghỉ phép',     v:'warning', icon:'umbrella'     },
  FORGOT_PUNCH_OUT: { label:'Quên chấm ra',  v:'danger',  icon:'alert-circle' },
  ABSENT:           { label:'Vắng mặt',      v:'danger',  icon:'x-circle'     },
};

// History for detail view
const ATT_HISTORY_30 = [
  { date:'16/05', day:'T6', in:'08:02', out:'17:35', dur:'9h33m', status:'COMPLETE', late:false },
  { date:'15/05', day:'T5', in:'08:10', out:'17:28', dur:'9h18m', status:'COMPLETE', late:false },
  { date:'14/05', day:'T4', in:'08:42', out:'18:05', dur:'9h23m', status:'COMPLETE', late:true  },
  { date:'13/05', day:'T3', in:'07:58', out:'17:15', dur:'9h17m', status:'COMPLETE', late:false },
  { date:'12/05', day:'T2', in:'08:05', out:'17:30', dur:'9h25m', status:'COMPLETE', late:false },
  { date:'09/05', day:'T6', in:null,    out:null,    dur:null,    status:'ABSENT',   late:false },
  { date:'08/05', day:'T5', in:'08:00', out:'17:00', dur:'9h00m', status:'COMPLETE', late:false },
  { date:'07/05', day:'T4', in:'08:30', out:'17:45', dur:'9h15m', status:'COMPLETE', late:true  },
];

// Danh mục ca làm việc (work_shifts) — màn Cấu hình
const WORK_SHIFTS = [
  { id:'ws1', name:'Ca Hành chính (T2–T6)', range:'08:00 – 17:00', brk:60, type:'Chuẩn',     emp:198, active:true  },
  { id:'ws2', name:'Ca Sáng',               range:'06:00 – 14:00', brk:30, type:'Xoay ca',   emp:24,  active:true  },
  { id:'ws3', name:'Ca Đêm',                range:'22:00 – 06:00', brk:45, type:'Ca đêm',    emp:13,  active:true  },
  { id:'ws4', name:'Ca Linh hoạt',          range:'09:00 – 18:00', brk:60, type:'Linh hoạt', emp:12,  active:false },
];

// Tổng hợp giờ công theo kỳ (PayrollExportRecord) — màn Tổng hợp & Xuất
const SUMMARY_ROWS = [
  { num:'NV-0007', emp:'Nguyễn Thị Lan',  regular:'176h 00m', ot:'8h 30m',  late:1, early:0, days:22 },
  { num:'NV-0012', emp:'Trần Minh Tuấn',  regular:'168h 20m', ot:'12h 10m', late:4, early:1, days:22 },
  { num:'NV-0021', emp:'Lê Thị Hương',    regular:'171h 45m', ot:'4h 00m',  late:0, early:0, days:21 },
  { num:'NV-0034', emp:'Phạm Đức Long',   regular:'160h 00m', ot:'0h 00m',  late:0, early:2, days:20 },
  { num:'NV-0045', emp:'Võ Thị Thu',      regular:'152h 30m', ot:'2h 15m',  late:3, early:5, days:19 },
  { num:'NV-0058', emp:'Đỗ Văn Hùng',    regular:'176h 00m', ot:'6h 45m',  late:0, early:0, days:22 },
];

// ─── 01: Attendance Dashboard (Manager) ──────────────────────────────────────
const AttDashboardScreen = ({ dark=false }) => (
  <HRMShell active="attendance" dark={dark}
    title="Chấm công nhân viên"
    crumbs={['Chấm công']}
    meta="Hôm nay · 16/05/2026"
    actions={<>
      <Btn variant="outline" size="sm" icon="download">Xuất báo cáo</Btn>
      <Btn variant="outline" size="sm" icon="inbox">Yêu cầu chờ duyệt (3)</Btn>
    </>}>

    {/* Stats */}
    <div className="mb-4 grid grid-cols-4 gap-3">
      {[
        { label:'Có mặt',          val:'204', delta:'82.6%',      dir:'up',   icon:'check-circle', ib:'var(--color-success-soft)',     ic:'var(--color-success)'        },
        { label:'Đang làm việc',   val:'197', delta:'Đang punch-in',dir:'up', icon:'clock',        ib:'var(--color-info-soft)',        ic:'var(--color-info)'           },
        { label:'Trễ giờ',         val:'8',   delta:'3.3%',       dir:'down', icon:'alert-circle', ib:'var(--color-warning-soft)',     ic:'oklch(0.55 0.158 65)'  },
        { label:'Nghỉ phép/Vắng',  val:'43',  delta:'17.4%',      dir:'down', icon:'umbrella',     ib:'var(--color-muted)',            ic:'var(--color-muted-foreground)'},
      ].map((s,i)=><StatCard key={i} label={s.label} value={s.val} delta={s.delta} deltaDir={s.dir} icon={s.icon} iconBg={s.ib} iconColor={s.ic} />)}
    </div>

    {/* Real-time bar */}
    <div className={CARD + " mb-3.5 flex items-center gap-5 px-5 py-3.5"}>
      <div className="flex-1">
        <div className="mb-1.5 flex justify-between text-sm">
          <span className="font-semibold">Tỷ lệ có mặt hôm nay</span>
          <span className="font-bold text-success">82.6%</span>
        </div>
        <div className="flex h-4 gap-0.5 overflow-hidden rounded-md">
          {[
            { pct:79.8, color:'var(--color-success)',     label:'Đang làm' },
            { pct:4.9,  color:'var(--color-warning)',     label:'Nghỉ phép'},
            { pct:3.3,  color:'var(--color-destructive)', label:'Vắng'     },
            { pct:12,   color:'var(--color-muted)',        label:'Chưa đến' },
          ].map((s,i)=>(
            <div key={i} title={s.label} className="min-w-0.5" style={{ width:`${s.pct}%`, background:s.color }} />
          ))}
        </div>
        <div className="mt-2 flex gap-4 text-xs">
          {[
            { color:'var(--color-success)', label:'Đang làm (197)' },
            { color:'var(--color-warning)', label:'Nghỉ phép (12)' },
            { color:'var(--color-destructive)', label:'Vắng mặt (8)' },
            { color:'var(--color-muted)', label:'Chưa đến (30)' },
          ].map((l,i)=>(
            <div key={i} className="flex items-center gap-1">
              <span className="size-2.5 shrink-0 rounded-[2px]" style={{ background:l.color }} />
              <span className="text-muted-foreground">{l.label}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="h-[60px] w-px bg-border" />
      <div className="min-w-[100px] text-center">
        <div className="mb-1 text-xs text-muted-foreground">Cập nhật lần cuối</div>
        <div className="text-md font-bold">09:42:31</div>
        <div className="mt-0.5 text-xs text-muted-foreground">Tự động làm mới</div>
      </div>
    </div>

    {/* Filter bar */}
    <div className={CARD + " mb-3 flex items-center gap-2.5 px-3.5 py-2.5"}>
      <div className="relative flex w-60 items-center">
        <Icon name="search" size={13} className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground" />
        <input className="h-8 w-full rounded-md border border-input bg-transparent pl-8 pr-3 text-xs text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring" placeholder="Tìm nhân viên..." />
      </div>
      <Select className="h-8 text-xs" style={{width:148}} defaultValue="Tất cả trạng thái" options={['Tất cả trạng thái', ...Object.values(ATT_ST).map(v=>v.label)]} />
      <Select className="h-8 text-xs" style={{width:148}} defaultValue="Tất cả phòng ban" options={['Tất cả phòng ban','Engineering','Nhân sự','Marketing']} />
      <Btn variant="outline" size="sm" icon="filter">Lọc</Btn>
      <div className="flex-1" />
      <span className="text-xs text-muted-foreground">8 nhân viên</span>
    </div>

    {/* Table */}
    <div className="overflow-hidden rounded-lg border border-border bg-card">
      <table className={TABLE_CLS}>
        <thead>
          <tr>
            <th>Nhân viên</th>
            <th style={{ textAlign:'center' }}>Giờ vào</th>
            <th style={{ textAlign:'center' }}>Giờ ra</th>
            <th style={{ textAlign:'center' }}>Tổng giờ</th>
            <th>Trạng thái</th>
            <th>Ghi chú</th>
            <th>Thao tác</th>
          </tr>
        </thead>
        <tbody>
          {ATT_LOGS.map(a=>{
            const st=ATT_ST[a.status];
            return (
              <tr key={a.id}>
                <td>
                  <div className="flex items-center gap-[9px]">
                    <div className="relative">
                      <Avatar name={a.emp} size="sm" />
                      {a.status==='PUNCHED_IN' && <span className="absolute bottom-0 right-0 size-2 rounded-full border-2 border-card bg-success" />}
                    </div>
                    <span className="text-sm font-medium">{a.emp}</span>
                  </div>
                </td>
                <td className="text-center">
                  {a.in ? (
                    <div className="inline-flex items-center gap-[5px] font-mono text-sm font-semibold tabular-nums">
                      {a.in}
                      {a.late && <span className="rounded-full bg-warning-soft px-[5px] py-px text-2xs font-medium text-[oklch(0.55_0.158_65)]">Trễ</span>}
                    </div>
                  ) : <span className="text-sm text-muted-foreground">—</span>}
                </td>
                <td className={"text-center font-mono text-sm tabular-nums " + (a.out ? "font-semibold text-foreground" : "text-muted-foreground")}>
                  {a.out||'—'}
                  {a.early && <span className="ml-[5px] rounded-full bg-info-soft px-[5px] py-px text-2xs font-medium text-info">Sớm</span>}
                </td>
                <td className={"text-center text-sm font-bold tabular-nums " + (a.dur ? "text-foreground" : "text-muted-foreground")}>
                  {a.dur||'—'}
                </td>
                <td><Badge variant={st.v} dot>{st.label}</Badge></td>
                <td className="text-xs text-muted-foreground">
                  {a.status==='FORGOT_PUNCH_OUT'?'Nhắc nhở đã gửi':a.status==='ON_LEAVE'?'AL - Phép năm':'—'}
                </td>
                <td>
                  {/* Xem chi tiết (Audit Trail MV-3) — KHÔNG sửa trực tiếp (AC-3); mọi thay đổi qua yêu cầu sửa */}
                  <div className="flex gap-[3px]">
                    <Btn variant="ghost" size="sm" iconOnly icon="eye" title="Xem chi tiết & lịch sử thay đổi" />
                    <Btn variant="ghost" size="sm" iconOnly icon="more-vertical" />
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  </HRMShell>
);

// ─── 02: Punch In/Out (Employee ESS) ──────────────────────────────────────────
const AttPunchScreen = () => {
  const [punched, setPunched] = React.useState(false);
  const now = '09:42';
  return (
    <HRMShell active="attendance"
      user={{ name:'Trần Minh Tuấn', role:'Employee' }}
      title="Chấm công"
      crumbs={['Chấm công']}>
      <div className="mx-auto max-w-[680px]">
        {/* Main punch card */}
        <div className={CARD + " mb-4 p-10 text-center"}>
          <div className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-muted-foreground">
            Thứ Sáu, 16 Tháng 5 · 2026
          </div>
          <div className="mb-1 text-[72px] font-extrabold leading-none tracking-[-0.03em] tabular-nums text-foreground">
            {now}
          </div>
          <div className="mb-8 text-base text-muted-foreground">
            {!punched ? 'Chưa chấm công hôm nay' : 'Đã chấm vào lúc 08:42 · Đang làm việc 1h 00m'}
          </div>

          {/* Big punch button */}
          <button onClick={()=>setPunched(!punched)} className="mx-auto mb-6 flex size-[180px] cursor-pointer flex-col items-center justify-center gap-2 rounded-full border-none text-white transition-all duration-300" style={{
            background: punched
              ? 'linear-gradient(135deg, #0C4B5E, #1B7A9A)'
              : 'linear-gradient(135deg, #F26522, #c4480f)',
            boxShadow: punched
              ? '0 12px 40px -8px rgba(12,75,94,0.5), 0 0 0 8px rgba(12,75,94,0.12)'
              : '0 12px 40px -8px rgba(242,101,34,0.6), 0 0 0 8px rgba(242,101,34,0.14)',
          }}>
            <Icon name={punched?'log-out':'clock'} size={36} />
            <span className="text-lg font-bold tracking-[-0.01em]">
              {punched ? 'Chấm Ra' : 'Chấm Vào'}
            </span>
          </button>

          {/* Vị trí: chỉ tọa độ thô, KHÔNG dịch địa chỉ (reverse-geocode) — finding 11 */}
          <div className="flex items-center justify-center gap-1.5 text-sm text-muted-foreground">
            <Icon name="map-pin" size={13} />
            {!punched ? 'Tọa độ được ghi nhận khi chấm công (nếu bạn cho phép)' : 'Đã ghi tọa độ · 21.0285, 105.8542'}
          </div>
          {punched && (
            <div className="mt-1 text-2xs text-muted-foreground">Hệ thống chỉ lưu tọa độ, không chuyển thành địa chỉ.</div>
          )}
        </div>

        {/* Today summary */}
        <div className={CARD + " mb-3.5 p-5"}>
          <div className="mb-3.5 text-sm font-bold">Hôm nay · 16/05/2026</div>
          <div className="grid grid-cols-4 gap-3">
            {[
              { label:'Giờ vào',     val: punched?'08:42':'—',  color:punched?'var(--color-success)':'var(--color-muted-foreground)' },
              { label:'Giờ ra',      val:'—',                   color:'var(--color-muted-foreground)' },
              { label:'Tổng giờ',   val: punched?'1h 00m':'—', color:punched?'var(--color-primary)':'var(--color-muted-foreground)'  },
              { label:'Trạng thái', val: punched?'Đang làm':'Chưa vào',color:punched?'var(--color-success)':'var(--color-muted-foreground)' },
            ].map((s,i)=>(
              <div key={i} className="rounded-lg bg-muted p-3 text-center">
                <div className="text-xl font-bold tabular-nums" style={{ color:s.color }}>{s.val}</div>
                <div className="mt-1 text-xs text-muted-foreground">{s.label}</div>
              </div>
            ))}
          </div>
        </div>

        {/* History */}
        <div className={CARD + " overflow-hidden"}>
          <div className={CARD_HEAD}>
            <div className={CARD_TITLE}>Lịch sử 5 ngày gần nhất</div>
            <Btn variant="ghost" size="sm">Xem tất cả →</Btn>
          </div>
          <table className={TABLE_CLS_COMPACT}>
            <thead>
              <tr>
                <th>Ngày</th>
                <th style={{ textAlign:'center' }}>Vào</th>
                <th style={{ textAlign:'center' }}>Ra</th>
                <th style={{ textAlign:'center' }}>Tổng</th>
                <th>Trạng thái</th>
              </tr>
            </thead>
            <tbody>
              {ATT_HISTORY_30.slice(0,5).map((h,i)=>(
                <tr key={i}>
                  <td className="text-sm"><strong>{h.day}</strong> {h.date}</td>
                  <td className={"text-center font-mono text-sm tabular-nums " + (h.in ? (h.late ? "font-semibold text-[oklch(0.55_0.158_65)]" : "font-semibold text-success") : "text-muted-foreground")}>{h.in||'—'}</td>
                  <td className={"text-center font-mono text-sm tabular-nums text-foreground " + (h.out ? "font-semibold" : "font-normal")}>{h.out||'—'}</td>
                  <td className="text-center text-sm font-bold tabular-nums">{h.dur||'—'}</td>
                  <td>
                    <Badge variant={ATT_ST[h.status].v} dot>{ATT_ST[h.status].label}</Badge>
                    {h.late && <span className="ml-1.5 text-xs text-[oklch(0.55_0.158_65)]">Trễ</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </HRMShell>
  );
};

// ─── 03: Correction Request ───────────────────────────────────────────────────
const AttCorrectionScreen = () => (
  <HRMShell active="attendance"
    user={{ name:'Bùi Thị Linh', role:'Employee' }}
    title="Yêu cầu điều chỉnh chấm công"
    crumbs={['Chấm công','Điều chỉnh']}
    actions={<>
      <Btn variant="outline" size="sm">Hủy</Btn>
      <Btn variant="primary"  size="sm">Gửi yêu cầu</Btn>
    </>}>
    <div className="grid grid-cols-[1fr_300px] gap-[18px]">
      <div className={CARD + " p-6"}>
        {/* Current record */}
        <div className="mb-[22px] flex gap-2.5 rounded-md bg-warning-soft px-[18px] py-3.5 border border-[oklch(0.835_0.158_80_/_0.3)]">
          <Icon name="alert-circle" size={16} className="mt-0.5 shrink-0 text-[oklch(0.55_0.158_65)]" />
          <div>
            <div className="mb-1 text-sm font-bold text-[oklch(0.45_0.1_65)]">Dữ liệu chấm công bất thường</div>
            <div className="text-xs leading-[1.5] text-[oklch(0.45_0.1_65)]">
              Ngày 15/05/2026 — Hệ thống không ghi nhận được giờ ra (chấm vào lúc 08:10 nhưng không có giờ ra). Vui lòng gửi yêu cầu điều chỉnh kèm lý do.
            </div>
          </div>
        </div>

        {/* Date & type */}
        <div className="mb-4 grid grid-cols-2 gap-3.5">
          <div>
            <label className="mb-[5px] block text-xs font-medium">Ngày cần điều chỉnh *</label>
            <input className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring" type="date" defaultValue="2026-05-15" />
          </div>
          <div>
            <label className="mb-[5px] block text-xs font-medium">Loại điều chỉnh *</label>
            <Select className="w-full" placeholder="— Chọn loại —" defaultValue="Bổ sung giờ ra bị thiếu" options={['Bổ sung giờ ra bị thiếu','Sửa giờ vào sai','Sửa giờ ra sai','Thêm bản ghi mới']} />
          </div>
        </div>

        {/* Current vs requested */}
        <div className="mb-4">
          <div className="mb-3 text-sm font-bold">Dữ liệu hiện tại vs. Yêu cầu</div>
          <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3.5">
            <div className="rounded-md bg-destructive-soft p-4 border border-[oklch(0.601_0.215_12_/_0.2)]">
              <div className="mb-2 text-xs font-bold uppercase tracking-[0.05em] text-destructive">Hiện tại (sai)</div>
              <div className="text-sm">Vào: <strong>08:10</strong></div>
              <div className="text-sm text-muted-foreground">Ra: <strong>—</strong> (thiếu)</div>
              <div className="text-sm text-muted-foreground">Tổng: <strong>—</strong></div>
            </div>
            <Icon name="arrow-right" size={20} className="text-muted-foreground" />
            <div className="rounded-md bg-success-soft p-4 border border-[oklch(0.711_0.180_148_/_0.2)]">
              <div className="mb-2 text-xs font-bold uppercase tracking-[0.05em] text-success">Yêu cầu sửa</div>
              <div className="text-sm">Vào: <strong>08:10</strong></div>
              <div className="text-sm">Ra: <strong>17:30</strong></div>
              <div className="text-sm">Tổng: <strong>9h 20m</strong></div>
            </div>
          </div>
        </div>

        {/* Corrected times */}
        <div className="mb-4 grid grid-cols-2 gap-3.5">
          <div>
            <label className="mb-[5px] block text-xs font-medium">Giờ vào đúng</label>
            <input className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring" type="time" defaultValue="08:10" />
            <div className="mt-1 text-xs text-muted-foreground">Giữ nguyên</div>
          </div>
          <div>
            <label className="mb-[5px] block text-xs font-medium">Giờ ra đúng *</label>
            <input className="h-9 w-full rounded-md border bg-transparent px-3 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring" type="time" defaultValue="17:30" style={{ borderColor:'var(--color-primary)' }} />
          </div>
        </div>

        <div className="mb-4">
          <label className="mb-[5px] block text-xs font-medium">Lý do điều chỉnh *</label>
          <textarea className="h-20 w-full resize-none rounded-md border border-input bg-transparent px-3 pt-2 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
            defaultValue="Ngày 15/05 đã làm việc đến 17:30 nhưng quên chấm ra do có cuộc họp khẩn. Đề nghị quản lý xác nhận qua camera an ninh văn phòng." />
        </div>

        <div>
          <label className="mb-[5px] block text-xs font-medium">Tài liệu đính kèm <span className="font-normal text-muted-foreground">(bằng chứng)</span></label>
          <div className="cursor-pointer rounded-md border-2 border-dashed border-border-strong p-[18px] text-center">
            <Icon name="upload" size={18} className="mb-1.5 text-muted-foreground" />
            <div className="text-sm text-muted-foreground">Ảnh chụp màn hình, email, hoặc tài liệu chứng minh</div>
          </div>
        </div>
      </div>

      {/* Right */}
      <div className="flex flex-col gap-3">
        <div className={CARD + " p-[18px]"}>
          <div className="mb-3 text-sm font-bold">Lịch sử 5 ngày</div>
          {ATT_HISTORY_30.slice(1,6).map((h,i)=>(
            <div key={i} className={"flex items-center gap-2.5 py-[7px] text-xs " + (i<4 ? "border-b border-border" : "")}>
              <div className="w-9 text-center">
                <div className="font-bold">{h.day}</div>
                <div className="text-xs text-muted-foreground">{h.date}</div>
              </div>
              <div className="flex-1">
                <div className="font-mono text-xs tabular-nums">
                  {h.in||'—'} → {h.out||'—'}
                </div>
                <div className="mt-px text-xs text-muted-foreground">{h.dur||'Thiếu dữ liệu'}</div>
              </div>
              <Badge variant={ATT_ST[h.status].v} dot style={{ fontSize: 'var(--text-2xs)' }}></Badge>
            </div>
          ))}
        </div>
        {/* Quy trình 3 bước — bỏ bước "Admin cập nhật" (finding 15): duyệt = hệ thống tự áp dụng trong cùng transaction */}
        <div className={CARD + " p-3.5"}>
          <div className="mb-2.5 text-xs font-bold uppercase tracking-[0.07em] text-muted-foreground">Quy trình xử lý</div>
          {[
            { n:'1', label:'Gửi yêu cầu điều chỉnh' },
            { n:'2', label:'Quản lý xem xét & duyệt' },
            { n:'3', label:'Hệ thống tự cập nhật bản ghi' },
          ].map((s,i)=>(
            <div key={i} className={"flex gap-[9px] py-1.5 text-xs " + (i<2 ? "border-b border-dashed border-border" : "")}>
              <div className="grid size-5 shrink-0 place-items-center rounded-full bg-primary-soft text-xs font-bold text-primary">{s.n}</div>
              {s.label}
            </div>
          ))}
        </div>
      </div>
    </div>
  </HRMShell>
);

// ─── 04: Team Member Detail + Audit Trail (Manager · MV-3) ────────────────────
const AttTeamDetailScreen = () => (
  <HRMShell active="attendance"
    title="Chi tiết chấm công"
    crumbs={['Chấm công','Đội ngũ','Lê Thị Hương']}
    meta="21/04/2026"
    actions={<Btn variant="outline" size="sm" icon="chevron-left">Quay lại danh sách</Btn>}>
    <div className="grid grid-cols-[1fr_320px] gap-[18px]">

      {/* Left — Audit Trail timeline */}
      <div className={CARD + " overflow-hidden"}>
        <div className={CARD_HEAD}>
          <div>
            <div className={CARD_TITLE}>Lịch sử thay đổi bản ghi</div>
            <div className="mt-0.5 text-xs text-muted-foreground">Lê Thị Hương · 21/04/2026 · Múi giờ ICT (UTC+7)</div>
          </div>
          <Badge variant="info" dot>Đã hiệu chỉnh</Badge>
        </div>

        <div className="p-5">
          <div className="relative pl-6">
            {/* rail */}
            <span className="absolute bottom-2 left-[7px] top-2 w-px bg-border" />

            {/* Punch IN */}
            <div className="relative mb-5">
              <span className="absolute -left-6 top-1 grid size-3.5 place-items-center rounded-full border-2 border-success bg-card"><span className="size-1.5 rounded-full bg-success" /></span>
              <div className="mb-1 flex items-center gap-2">
                <span className="text-xs font-bold uppercase tracking-[0.05em] text-success">Chấm vào</span>
                <span className="font-mono text-md font-bold tabular-nums line-through decoration-destructive/60">08:03</span>
                <Badge variant="neutral">Đã hiệu chỉnh</Badge>
              </div>
              {/* Metadata đối soát/bảo mật: thiết bị (device_info) + IP máy chủ (ip_address) */}
              <div className="text-xs text-muted-foreground">Thiết bị: iPhone 14 · IP: 203.0.113.47 · Ghi chú: "Máy quét ghi sai giờ"</div>

              {/* Nested correction */}
              <div className="mt-2.5 rounded-md border border-border bg-muted/60 p-3">
                <div className="mb-1.5 flex items-center gap-2 text-xs font-bold">
                  <Icon name="edit" size={13} className="text-primary" />
                  Yêu cầu sửa #CR-042
                  <Badge variant="success" dot>Đã duyệt</Badge>
                </div>
                <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">
                  <div>Giờ sửa: <strong className="font-mono tabular-nums text-success">07:58</strong></div>
                  <div>Lý do: <strong className="text-foreground">Máy quét sai giờ (clock_error)</strong></div>
                  <div>Duyệt bởi: <strong className="text-foreground">Trần Minh (Quản lý)</strong></div>
                  <div>Ngày duyệt: <strong className="text-foreground">21/04/2026 09:15</strong></div>
                </div>
              </div>
            </div>

            {/* Punch OUT */}
            <div className="relative">
              <span className="absolute -left-6 top-1 grid size-3.5 place-items-center rounded-full border-2 border-info bg-card"><span className="size-1.5 rounded-full bg-info" /></span>
              <div className="mb-1 flex items-center gap-2">
                <span className="text-xs font-bold uppercase tracking-[0.05em] text-info">Chấm ra</span>
                <span className="font-mono text-md font-bold tabular-nums">17:15</span>
                <Badge variant="success" dot>Đúng giờ</Badge>
              </div>
              <div className="text-xs text-muted-foreground">Thiết bị: MacBook Pro · IP: 203.0.113.88 · Ghi chú: — · Trạng thái: hoạt động</div>
            </div>
          </div>

          {/* Duration footer */}
          <div className="mt-5 flex items-center justify-between rounded-md bg-primary-soft px-4 py-3">
            <span className="text-sm font-semibold text-primary">Tổng giờ làm việc</span>
            <div className="text-right">
              <div className="font-mono text-lg font-bold tabular-nums text-primary">9h 17m</div>
              <div className="text-2xs text-muted-foreground">tính theo giờ vào đã sửa 07:58 → ra 17:15</div>
            </div>
          </div>
        </div>
      </div>

      {/* Right — info + note */}
      <div className="flex flex-col gap-3">
        <div className={CARD + " p-[18px]"}>
          <div className="flex items-center gap-3">
            <Avatar name="Lê Thị Hương" size="lg" />
            <div className="min-w-0">
              <div className="truncate text-sm font-bold">Lê Thị Hương</div>
              <div className="text-xs text-muted-foreground">NV-0021 · Engineering</div>
            </div>
          </div>
          <div className="mt-3.5 grid grid-cols-2 gap-y-2 text-xs">
            <span className="text-muted-foreground">Ca làm việc</span><span className="text-right font-medium">Ca Hành chính</span>
            <span className="text-muted-foreground">Giờ chuẩn (tuần)</span><span className="text-right font-mono font-medium tabular-nums">42h 30m</span>
            <span className="text-muted-foreground">Lượt đi muộn</span><span className="text-right font-medium">0</span>
            <span className="text-muted-foreground">Quản lý</span><span className="text-right font-medium">Trần Minh</span>
          </div>
        </div>

        {/* MV-5 add note */}
        <div className={CARD + " p-[18px]"}>
          <div className="mb-2 text-sm font-bold">Thêm ghi chú quản lý</div>
          <textarea className="h-20 w-full resize-none rounded-md border border-input bg-transparent px-3 pt-2 text-base text-foreground shadow-xs transition-colors placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
            placeholder="Ghi chú hiển thị công khai cho nhân viên và nhân sự…" />
          <div className="mt-2 flex justify-end">
            <Btn variant="primary" size="sm">Lưu ghi chú</Btn>
          </div>
        </div>

        {/* AC-3 notice */}
        <div className="flex gap-2 rounded-md bg-muted px-3.5 py-3 text-xs text-muted-foreground">
          <Icon name="info" size={14} className="mt-0.5 shrink-0" />
          <span>Giao diện quản lý chỉ để xem. Không thể sửa trực tiếp dữ liệu chấm công — mọi thay đổi phải qua yêu cầu điều chỉnh.</span>
        </div>
      </div>
    </div>
  </HRMShell>
);

// ─── 05: Attendance Configuration (Admin · ATT-CONFIG) ────────────────────────
// Bố cục tabs — theo concept AdminTabBar của màn Cấu hình (module 12): 2 tab
// "Chính sách chấm công" / "Ca làm việc"; nút hành động ở header đổi theo tab.
const AttConfigScreen = () => {
  const [tab, setTab] = React.useState('policy');
  const CFG_TABS = [
    { id:'policy', label:'Chính sách chấm công', icon:'settings' },
    { id:'shifts', label:'Ca làm việc',          icon:'clock'    },
  ];
  return (
    <HRMShell active="attendance"
      title="Cấu hình chấm công"
      crumbs={['Chấm công','Cấu hình']}
      actions={tab==='policy'
        ? <>
            <Btn variant="outline" size="sm">Hoàn tác</Btn>
            <Btn variant="primary"  size="sm" icon="check">Lưu thay đổi</Btn>
          </>
        : <Btn variant="primary" size="sm" icon="plus">Thêm ca</Btn>}>
      <div className="flex flex-col overflow-hidden rounded-xl border border-border bg-card shadow-xs">

        {/* Tab bar — theo AdminTabBar (module 12) */}
        <div className="flex shrink-0 items-center gap-0.5 border-b border-border bg-card px-2">
          {CFG_TABS.map(t=>{
            const on = t.id===tab;
            return (
              <div key={t.id} onClick={()=>setTab(t.id)}
                className={"relative flex cursor-pointer items-center gap-1.5 px-3.5 py-2.5 text-sm transition-colors "
                  + (on ? "font-semibold text-primary" : "font-medium text-muted-foreground hover:text-foreground")}>
                <Icon name={t.icon} size={14} />
                {t.label}
                {on && <span className="absolute inset-x-2.5 -bottom-px h-[2px] rounded-t-sm bg-primary" />}
              </div>
            );
          })}
        </div>

        {/* Tab 1 — Chính sách chấm công tổ chức */}
        {tab==='policy' && (
          <div className="p-5">
            <div className="mb-4 flex items-center gap-2 text-xs text-muted-foreground">
              <Icon name="info" size={13} className="shrink-0" />
              Áp dụng đồng nhất toàn tổ chức · không cấu hình theo phòng ban · mọi thay đổi được ghi nhật ký.
            </div>
            {/* Grace toggle */}
            <div className="mb-4 flex items-start gap-3 rounded-md border border-border bg-muted/50 px-4 py-3">
              <Toggle on={true} />
              <div>
                <div className="text-sm font-semibold">Bật đánh dấu đi muộn linh hoạt (grace period)</div>
                <div className="text-xs text-muted-foreground">Khi tắt, mọi check-in sau giờ ca đều tính đúng giờ (bỏ qua ngưỡng linh hoạt).</div>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-x-4 gap-y-4">
              <NumField label="Thời gian linh hoạt (grace)" value={15} unit="phút" hint="0–60 · mặc định 15" />
              <NumField label="Dung sai chồng ca" value={30} unit="phút" hint="0–120 · nhỏ hơn ⇒ cảnh báo chồng ca" />
              <NumField label="Giờ tối đa mỗi phiên" value={16} unit="giờ" hint="1–24 · mặc định 16" />
              <NumField label="Cửa sổ yêu cầu sửa công" value={30} unit="ngày" hint="1–365 · mặc định 30" />
              <NumField label="Chấm vào sớm tối đa" value={60} unit="phút" hint="trước giờ bắt đầu ca" />
              <NumField label="Chấm ra muộn tối đa" value={120} unit="phút" hint="sau giờ kết thúc ca" />
              <div className="col-span-3 flex items-start gap-2 rounded-md border border-border bg-muted/50 px-4 py-3 text-xs text-muted-foreground">
                <Icon name="globe" size={14} className="mt-0.5 shrink-0 text-info" />
                <span>Múi giờ áp cho chấm công là <strong className="text-foreground">múi giờ hệ thống</strong> — một múi giờ dùng chung toàn hệ thống, đặt tại <strong className="text-foreground">Hệ thống › Cấu hình hệ thống › Múi giờ</strong> (không cấu hình theo địa điểm/tổ chức). Business Day cố định tại thời điểm ghi log — đổi múi giờ không sửa dữ liệu quá khứ.</span>
              </div>
            </div>
          </div>
        )}

        {/* Tab 2 — Ca làm việc (work_shifts) */}
        {tab==='shifts' && (
          <>
            <div className="flex items-center gap-2 border-b border-border px-5 py-2.5 text-xs text-muted-foreground">
              <Icon name="info" size={13} className="shrink-0" />
              Bắt buộc: mỗi nhân viên phải được gán một ca làm việc.
            </div>
            <table className={TABLE_CLS}>
              <thead>
                <tr>
                  <th>Tên ca</th>
                  <th style={{ textAlign:'center' }}>Giờ vào – ra</th>
                  <th style={{ textAlign:'center' }}>Nghỉ</th>
                  <th>Loại</th>
                  <th style={{ textAlign:'center' }}>NV gán</th>
                  <th>Trạng thái</th>
                  <th>Thao tác</th>
                </tr>
              </thead>
              <tbody>
                {WORK_SHIFTS.map(s=>(
                  <tr key={s.id}>
                    <td className="text-sm font-medium">{s.name}</td>
                    <td className="text-center font-mono text-sm tabular-nums">{s.range}</td>
                    <td className="text-center font-mono text-sm tabular-nums text-muted-foreground">{s.brk}′</td>
                    <td><Badge variant="neutral">{s.type}</Badge></td>
                    <td className="text-center text-sm font-semibold tabular-nums">{s.emp}</td>
                    <td><Badge variant={s.active?'success':'neutral'} dot>{s.active?'Đang dùng':'Tạm ẩn'}</Badge></td>
                    <td>
                      <div className="flex gap-[3px]">
                        <Btn variant="ghost" size="sm" iconOnly icon="edit" />
                        <Btn variant="ghost" size="sm" iconOnly icon="more-vertical" />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="flex items-center gap-2 border-t border-border px-5 py-3 text-xs text-muted-foreground">
              <Icon name="check-circle" size={14} className="text-success" />
              247/247 nhân viên đã được gán ca làm việc.
            </div>
          </>
        )}
      </div>
    </HRMShell>
  );
};

// ─── 06: Summary & Payroll Export (Admin/HR · ATT-SUMMARY) ────────────────────
const AttSummaryScreen = () => (
  <HRMShell active="attendance"
    title="Tổng hợp giờ công"
    crumbs={['Chấm công','Tổng hợp']}
    actions={<>
      <Btn variant="outline" size="sm" icon="file-text">Xuất CSV</Btn>
      <Btn variant="primary"  size="sm" icon="download">Xuất dữ liệu lương</Btn>
    </>}>

    {/* Filter bar — chỉ chọn kỳ; KHÔNG lọc phòng ban (cổng kết xuất trả toàn tổ chức, BE không hỗ trợ lọc) */}
    <div className={CARD + " mb-3.5 flex items-center gap-2.5 px-3.5 py-2.5"}>
      <span className="text-xs font-medium text-muted-foreground">Kỳ</span>
      <Select className="h-8 text-xs" style={{width:168}} defaultValue="Tháng 05/2026" options={['Tháng 05/2026','Tháng 04/2026','Quý 2/2026','Tùy chọn khoảng…']} />
      <Btn variant="outline" size="sm" icon="filter">Áp dụng</Btn>
      <div className="flex-1" />
      <span className="text-xs text-muted-foreground">01/05 – 31/05/2026 · 6 nhân viên</span>
    </div>

    {/* Stats */}
    <div className="mb-4 grid grid-cols-4 gap-3">
      <StatCard label="Tổng giờ chuẩn" value="1.004h" icon="clock"        iconBg="var(--color-primary-soft)" iconColor="var(--color-primary)" />
      <StatCard label="Tổng giờ tăng ca" value="33h 40m" icon="trending-up" iconBg="var(--color-info-soft)"    iconColor="var(--color-info)" />
      <StatCard label="Tổng lượt đi muộn" value="8" icon="alert-circle"    iconBg="var(--color-warning-soft)" iconColor="oklch(0.55 0.158 65)" />
      <StatCard label="Nhân viên trong kỳ" value="6" icon="users"          iconBg="var(--color-muted)"        iconColor="var(--color-muted-foreground)" />
    </div>

    {/* Table — PayrollExportRecord */}
    <div className="overflow-hidden rounded-lg border border-border bg-card">
      <table className={TABLE_CLS}>
        <thead>
          <tr>
            <th>Mã NV</th>
            <th>Nhân viên</th>
            <th style={{ textAlign:'center' }}>Giờ chuẩn</th>
            <th style={{ textAlign:'center' }}>Giờ tăng ca</th>
            <th style={{ textAlign:'center' }}>Lượt muộn</th>
            <th style={{ textAlign:'center' }}>Lượt về sớm</th>
            <th style={{ textAlign:'center' }}>Ngày công</th>
          </tr>
        </thead>
        <tbody>
          {SUMMARY_ROWS.map(r=>(
            <tr key={r.num}>
              <td className="font-mono text-sm tabular-nums text-muted-foreground">{r.num}</td>
              <td>
                <div className="flex items-center gap-[9px]">
                  <Avatar name={r.emp} size="sm" />
                  <span className="text-sm font-medium">{r.emp}</span>
                </div>
              </td>
              <td className="text-center font-mono text-sm font-semibold tabular-nums">{r.regular}</td>
              <td className={"text-center font-mono text-sm tabular-nums " + (r.ot==='0h 00m' ? "text-muted-foreground" : "font-semibold text-info")}>{r.ot}</td>
              <td className="text-center text-sm tabular-nums">
                {r.late>0 ? <span className="font-semibold text-[oklch(0.55_0.158_65)]">{r.late}</span> : <span className="text-muted-foreground">0</span>}
              </td>
              <td className="text-center text-sm tabular-nums">
                {r.early>0 ? <span className="font-semibold text-foreground">{r.early}</span> : <span className="text-muted-foreground">0</span>}
              </td>
              <td className="text-center text-sm font-bold tabular-nums">{r.days}</td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="flex items-center gap-2 border-t border-border px-5 py-3 text-xs text-muted-foreground">
        <Icon name="info" size={14} />
        v1: kết xuất chỉ đọc (read-only), chưa khóa kỳ lương. Nguồn dữ liệu: bảng tổng hợp AttendanceSummary.
      </div>
    </div>
  </HRMShell>
);

// ─── 07: Empty State ──────────────────────────────────────────────────────────
const AttEmptyScreen = () => (
  <HRMShell active="attendance" title="Chấm công" crumbs={['Chấm công']}>
    <div className={CARD + " flex min-h-[440px] flex-col items-center justify-center p-12"}>
      <svg width="80" height="80" viewBox="0 0 80 80" fill="none" className="mb-6">
        <circle cx="40" cy="40" r="40" fill="var(--color-muted)" />
        <circle cx="40" cy="40" r="22" fill="none" stroke="var(--color-border-strong)" strokeWidth="2.5" />
        <path d="M40 26v14l8 8" stroke="var(--color-border-strong)" strokeWidth="2.5" strokeLinecap="round" />
        <circle cx="58" cy="58" r="12" fill="var(--color-primary-soft)" stroke="var(--color-primary)" strokeWidth="2" />
        <path d="M54 58h8M58 54v8" stroke="var(--color-primary)" strokeWidth="2" strokeLinecap="round" />
      </svg>
      <div className="mb-2.5 text-xl font-bold">Chưa có dữ liệu chấm công</div>
      <div className="mb-7 max-w-[420px] text-center text-base leading-[1.65] text-muted-foreground">
        Dữ liệu chấm công được ghi nhận khi nhân viên chấm vào/ra qua ứng dụng. Hãy cấu hình chính sách &amp; ca làm việc để bắt đầu, hoặc chấm công thay nhân viên khi cần.
      </div>
      <div className="flex gap-2.5">
        <Btn variant="outline" icon="settings">Cấu hình chấm công</Btn>
        <Btn variant="primary"  icon="edit">Chấm công thay nhân viên</Btn>
      </div>
    </div>
  </HRMShell>
);

// ─── 08: Dark Mode ────────────────────────────────────────────────────────────
const AttDarkScreen = () => <AttDashboardScreen dark />;

Object.assign(window, {
  AttDashboardScreen, AttPunchScreen, AttCorrectionScreen,
  AttTeamDetailScreen, AttConfigScreen, AttSummaryScreen,
  AttEmptyScreen, AttDarkScreen,
});
