/* =========================================================================
   screens-ops.jsx — Attendance / Check-in (+ OT) and Payroll summary
   ========================================================================= */

/* ====================== ATTENDANCE ====================== */
function Attendance(){
  const { db, upsertAttendance } = useDB();
  const [date,setDate] = uS(ymd(TODAY));
  const [group,setGroup] = uS('all');
  const [savedFlash,setSavedFlash] = uS(false);
  const groups = ['all', ...Array.from(new Set(db.workers.map(w=>w.group).filter(Boolean)))];

  const workers = db.workers.filter(w=>w.active && (group==='all'||w.group===group));
  const attMap = Object.fromEntries(db.attendance.filter(a=>a.date===date).map(a=>[a.workerId,a]));

  const dt = parseYMD(date);
  const isSunday = dt.getDay()===0;
  const holiday = holidayByDate(db, date);

  const def = (extra)=>({ date, workerId:extra.workerId, siteId:db.sites.find(s=>s.active)?.id, taskId:'', status:'full', otHours:0, otFlat:0, advance:0, note:'', ...extra });
  const setStatus = (w, status)=>{
    const ex = attMap[w.id] || def({ workerId:w.id });
    // เลือก "ขาดงาน" → ล้างหน้างาน/ประเภทงาน/OT (ไม่ต้องระบุหน้างานเพราะไม่ได้มาทำ)
    if(status==='absent') upsertAttendance({ ...ex, status, siteId:'', taskId:'', otHours:0, advance:0 });
    else upsertAttendance({ ...ex, status });
  };
  const setSite = (w, siteId)=>{ const ex=attMap[w.id]; upsertAttendance(ex?{...ex, siteId}:def({workerId:w.id, siteId})); };
  const setTask = (w, taskId)=>{ const ex=attMap[w.id]; upsertAttendance(ex?{...ex, taskId}:def({workerId:w.id, taskId})); };
  const setOt = (w, otHours)=>{ const ex=attMap[w.id]; upsertAttendance(ex?{...ex, otHours:Math.max(0,otHours)}:def({workerId:w.id, otHours:Math.max(0,otHours)})); };
  const setAdvance = (w, advance)=>{ const ex=attMap[w.id]; upsertAttendance(ex?{...ex, advance:Math.max(0,advance)}:def({workerId:w.id, advance:Math.max(0,advance)})); };
  const setNote = (w, note)=>{ const ex=attMap[w.id]; upsertAttendance(ex?{...ex, note}:def({workerId:w.id, note})); };

  const markAll = ()=> workers.forEach(w=>{ if(!attMap[w.id]) setStatus(w,'full'); });
  const goDay = (delta)=> setDate(ymd(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()+delta)));
  const confirmNext = ()=>{ setSavedFlash(true); setTimeout(()=>setSavedFlash(false), 2200); goDay(1); };

  const present = workers.filter(w=>attMap[w.id] && attMap[w.id].status!=='absent').length;
  const pending = workers.filter(w=>!attMap[w.id]).length;
  const dayLabel = isSunday ? 'วันอาทิตย์ (วันหยุดประจำ)' : holiday ? 'วันหยุด' : 'วันทำงาน';

  return (
    <div data-screen>
      <PageHead title="ลงเวลาเข้างาน" sub="เลือกวัน · กำหนดหน้างาน · บันทึก OT / เบิกเงิน / หมายเหตุ รายคน · ลงย้อนหลังและแก้ไขได้ตลอด"
        actions={<>
          <Button variant="dark" icon="check" onClick={markAll}>ลงเต็มวันทั้งหมด</Button>
          <Button icon="arrow" onClick={confirmNext}>ยืนยัน &amp; วันถัดไป</Button>
        </>} />

      {savedFlash && (
        <div className="mb-4 flex items-center gap-2 bg-ok/12 border border-ok/40 text-ok rounded-lg px-4 py-2.5 text-sm font-medium">
          <Icon name="check" size={16}/> บันทึกการลงเวลาเรียบร้อยแล้ว — ไปยังวันถัดไป
        </div>
      )}

      <Card pad={false} className="mb-5">
        <div className="flex flex-wrap items-center gap-4 p-4">
          <div className="flex items-center gap-2">
            <button onClick={()=>goDay(-1)} className="tap p-2 rounded-md border border-line text-haze hover:text-chalk"><Icon name="arrow" size={16} className="rotate-180"/></button>
            <div className="bg-ink border border-line rounded-lg px-4 py-2 text-center min-w-[180px]">
              <div className={`text-xs ${isSunday||holiday?'text-warn':'text-haze'}`}>{dayLabel}</div>
              <div className="font-display font-semibold">{thaiDateLong(date)}</div>
            </div>
            <button onClick={()=>goDay(1)} className="tap p-2 rounded-md border border-line text-haze hover:text-chalk"><Icon name="arrow" size={16}/></button>
            <input type="date" value={date} onChange={e=>setDate(e.target.value)} className="bg-ink border border-line rounded-lg px-3 py-2 text-sm text-haze [color-scheme:dark]"/>
          </div>
          <div className="flex-1"></div>
          <div className="flex items-center gap-4 text-sm">
            <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-ok"></span>มา {present}</span>
            <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-line"></span>ยังไม่ลง {pending}</span>
          </div>
          <Select value={group} onChange={e=>setGroup(e.target.value)} className="!py-2 min-w-[160px]">
            {groups.map(g=><option key={g} value={g}>{g==='all'?'ทุกกลุ่มแรงงาน':g}</option>)}
          </Select>
        </div>
      </Card>

      {holiday && (
        <Card className="mb-5 border-warn/40 bg-warn/[0.06]">
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-warn/15 border border-warn/40 text-warn flex items-center justify-center shrink-0"><Icon name="calendar" size={18}/></div>
            <div className="text-sm">
              <div className="font-display font-bold text-warn">วันหยุด: {holiday.name}</div>
              <div className="text-haze mt-0.5">{holiday.reason || 'ทุกคนหยุดงาน'} — ปกติไม่ต้องลงเวลา แต่ถ้ามีคนมาทำงานวันหยุด สามารถกด "มาเต็มวัน/ครึ่งวัน" ให้คนนั้นได้เลย (นับเป็นทำงานวันหยุด)</div>
            </div>
          </div>
        </Card>
      )}

      <div className="space-y-3">
        {workers.map(w=>{
          const a = attMap[w.id];
          const logged = !!a;
          const absent = a?.status==='absent';
          return (
            <Card key={w.id} pad={false} className={`overflow-hidden ${logged?'border-line':'opacity-95'}`}>
              <div className="flex flex-col lg:flex-row lg:items-center gap-4 p-4">
                <div className="flex items-center gap-3 lg:w-52 shrink-0">
                  <Avatar name={w.name} photo={w.photo} size={42}/>
                  <div className="min-w-0">
                    <div className="font-medium truncate flex items-center gap-2">{w.name}</div>
                    <div className="text-xs text-haze flex items-center gap-2"><TypeBadge type={w.type}/>{w.group}</div>
                  </div>
                </div>

                {/* status */}
                <div className="flex gap-1.5">
                  {Object.values(STATUS).map(st=>(
                    <button key={st.key} onClick={()=>setStatus(w,st.key)}
                      className={`tap text-sm font-medium px-3 py-2 rounded-lg border ${a?.status===st.key
                        ? (st.tone==='ok'?'border-ok bg-ok/15 text-ok':st.tone==='warn'?'border-warn bg-warn/15 text-warn':'border-bad bg-bad/15 text-bad')
                        : 'border-line text-haze hover:border-haze/50'}`}>
                      {st.th}
                    </button>
                  ))}
                </div>

                {/* site + task */}
                <div className="flex-1 grid sm:grid-cols-2 gap-2 min-w-[240px]">
                  <Select value={a?.siteId||''} onChange={e=>setSite(w,e.target.value)} className="!py-2" disabled={absent}>
                    <option value="">— เลือกหน้างาน —</option>
                    {db.sites.filter(s=>s.active).map(s=><option key={s.id} value={s.id}>{s.code} · {s.name}</option>)}
                  </Select>
                  <WorkTypeSelect value={a?.taskId} onChange={v=>setTask(w,v)} className="!py-2" disabled={absent}/>
                </div>

                {/* OT */}
                <div className="flex items-center gap-2 shrink-0">
                  <div className="flex items-center gap-1 bg-ink border border-line rounded-lg px-2 py-1" title="ชั่วโมง OT">
                    <Icon name="bolt" size={15} className="text-hazard"/>
                    <button onClick={()=>setOt(w,(a?.otHours||0)-1)} disabled={absent} className="tap w-6 h-6 rounded text-haze hover:text-chalk disabled:opacity-30">−</button>
                    <input value={a?.otHours||0} onChange={e=>setOt(w,+e.target.value||0)} onFocus={e=>e.target.select()} disabled={absent}
                      className="num w-9 text-center bg-transparent text-sm focus:outline-none disabled:opacity-40"/>
                    <button onClick={()=>setOt(w,(a?.otHours||0)+1)} disabled={absent} className="tap w-6 h-6 rounded text-haze hover:text-chalk disabled:opacity-30">+</button>
                    <span className="text-xs text-haze pr-1">ชม.</span>
                  </div>
                </div>

                {/* เบิกเงิน (กิน-ใช้) รายวัน */}
                <div className="flex items-center gap-1 bg-ink border border-line rounded-lg px-2 py-1 shrink-0" title="เบิกเงินระหว่างวัน (กิน-ใช้)">
                  <Icon name="money" size={15} className="text-brand"/>
                  <span className="text-xs text-haze">เบิก</span>
                  <input value={a?.advance||0} onChange={e=>setAdvance(w,+String(e.target.value).replace(/[^0-9.]/g,'')||0)} onFocus={e=>e.target.select()} disabled={absent}
                    className="num w-16 text-right bg-transparent text-sm focus:outline-none disabled:opacity-40"/>
                  <span className="text-xs text-haze pr-1">฿</span>
                </div>
              </div>

              {/* second row: note + saved indicator */}
              <div className="flex items-center gap-3 px-4 pb-3 -mt-1">
                <div className="relative flex-1">
                  <div className="absolute left-3 top-1/2 -translate-y-1/2 text-haze"><Icon name="edit" size={14}/></div>
                  <input value={a?.note||''} onChange={e=>setNote(w,e.target.value)} placeholder="หมายเหตุ / ข้อความถึงทีม (เช่น ลาช่วงบ่าย, ย้ายไปไซต์อื่น)" disabled={absent && false}
                    className={`${inputCls} pl-9 !py-2 text-sm`}/>
                </div>
                {logged
                  ? <span className="shrink-0 text-xs text-ok flex items-center gap-1 font-medium"><Icon name="check" size={14}/>บันทึกแล้ว</span>
                  : <span className="shrink-0 text-xs text-haze">ยังไม่ลงเวลา</span>}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

/* ====================== PAYROLL SUMMARY ====================== */
function AdjustModal({ open, onClose, worker, period }){
  const { addAdjustment } = useDB();
  const [kind,setKind] = uS('advance');
  const [label,setLabel] = uS('');
  const [amount,setAmount] = uS('');
  uE(()=>{ if(open){ setKind('advance'); setLabel(''); setAmount(''); } },[open]);
  const KINDS = [['advance','เบิกระหว่างงวด'],['social','ประกันสังคม'],['other','หักอื่นๆ']];
  const defLabel = { advance:'เบิกระหว่างงวด', social:'ประกันสังคม', other:'รายการหัก' };
  const save = ()=>{ if(!amount||+amount<=0) return; addAdjustment({ workerId:worker.id, period:period.id, kind, label: label || defLabel[kind], amount:+amount }); onClose(); };
  if(!worker) return null;
  return (
    <Modal open={open} onClose={onClose} title={`เพิ่มรายการหัก · ${worker.name}`}
      footer={<><Button variant="ghost" onClick={onClose}>ยกเลิก</Button><Button icon="check" onClick={save}>เพิ่มรายการ</Button></>}>
      <div className="space-y-4">
        <div className="text-xs text-haze">งวด: <span className="text-chalk">{period.label}</span> ({period.range})</div>
        <Field label="ประเภทรายการ">
          <div className="grid grid-cols-3 gap-2">
            {KINDS.map(([k,l])=>(
              <button key={k} onClick={()=>setKind(k)}
                className={`tap rounded-lg border px-3 py-3 text-sm font-medium ${kind===k?'border-brand bg-brand/12 text-brand':'border-line text-haze hover:border-haze/50'}`}>{l}</button>
            ))}
          </div>
        </Field>
        <Field label="คำอธิบายรายการ"><Input value={label} onChange={e=>setLabel(e.target.value)} placeholder={kind==='advance'?'เช่น เบิกค่าน้ำมัน':kind==='social'?'เช่น ประกันสังคม 5%':'เช่น หักค่าที่พัก'}/></Field>
        <Field label="จำนวนเงิน (บาท)"><NumberInput value={amount} onChange={v=>setAmount(v)} step={100} blankZero/></Field>
        <div className="text-xs text-haze bg-ink border border-line rounded-lg px-3 py-2 flex items-start gap-2">
          <Icon name="warn" size={15} className="text-hazard mt-0.5 shrink-0"/>
          รายการหักทั้งหมด (เบิกระหว่างงวด / ประกันสังคม / หักอื่นๆ) คนทำบัญชีเพิ่มเองตามงวด
        </div>
      </div>
    </Modal>
  );
}

function Payroll({ go, setSlip }){
  const { db, removeAdjustment } = useDB();
  const [period,setPeriod] = uS(currentPeriod());
  const [expanded,setExpanded] = uS(null);
  const [adjFor,setAdjFor] = uS(null);

  const rows = db.workers.map(w=>computePayroll(db,w.id,period));
  const totalGross = rows.reduce((s,p)=>s+p.gross,0);
  const totalDed = rows.reduce((s,p)=>s+p.deductions,0);
  const totalNet = rows.reduce((s,p)=>s+p.net,0);
  const totalOt = rows.reduce((s,p)=>s+p.otPay,0);

  return (
    <div data-screen>
      <PageHead title="สรุปเงินเดือน (รายงวด)" sub={`คำนวณค่าแรง + OT − รายการหัก · ${period.range}`}
        actions={<PeriodPicker value={period} onChange={setPeriod}/>} />

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <Stat strip label="ค่าแรงรวม (ก่อนหัก)" value={baht(totalGross,0)} icon="money" tone="chalk"/>
        <Stat label="ค่า OT รวม" value={baht(totalOt,0)} icon="bolt" tone="hazard"/>
        <Stat label="รายการหักรวม" value={baht(totalDed,0)} icon="arrow" tone="bad"/>
        <Stat label="ยอดจ่ายสุทธิ" value={baht(totalNet,0)} icon="payroll" tone="brand"/>
      </div>

      <Card pad={false}>
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[860px]">
            <thead>
              <tr className="text-left text-haze border-b border-line">
                <th className="font-medium px-4 py-3">คนงาน</th>
                <th className="font-medium px-4 py-3 text-center">วันทำงาน</th>
                <th className="font-medium px-4 py-3 text-right">ค่าแรงฐาน</th>
                <th className="font-medium px-4 py-3 text-right">OT</th>
                <th className="font-medium px-4 py-3 text-right">หัก</th>
                <th className="font-medium px-4 py-3 text-right">สุทธิ</th>
                <th className="font-medium px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(p=>{
                const open = expanded===p.worker.id;
                return (
                  <React.Fragment key={p.worker.id}>
                    <tr className="border-b border-line/60 hover:bg-white/[0.02] cursor-pointer" onClick={()=>setExpanded(open?null:p.worker.id)}>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          <Avatar name={p.worker.name} photo={p.worker.photo} size={36}/>
                          <div>
                            <div className="font-medium">{p.worker.name}</div>
                            <div className="text-xs text-haze flex items-center gap-1.5"><TypeBadge type={p.worker.type}/>{p.worker.group}</div>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-center num">{num(p.dayUnits,1)}{p.daysAbsent>0 && <span className="text-bad text-xs"> ·ขาด{p.daysAbsent}</span>}</td>
                      <td className="px-4 py-3 text-right num">{baht(p.base,0)}</td>
                      <td className="px-4 py-3 text-right num text-hazard">{p.otPay>0?baht(p.otPay,0):'—'}</td>
                      <td className="px-4 py-3 text-right num text-bad">{p.deductions>0?'−'+baht(p.deductions,0):'—'}</td>
                      <td className="px-4 py-3 text-right num font-display font-bold text-brand">{baht(p.net,0)}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-end gap-1">
                          <button onClick={(e)=>{e.stopPropagation(); setSlip({workerId:p.worker.id,period}); go('payslip');}} className="tap p-2 text-haze hover:text-brand rounded-md hover:bg-white/5" title="ออกสลิป"><Icon name="slip" size={17}/></button>
                          <Icon name="chevdown" size={16} className={`text-haze transition ${open?'rotate-180':''}`}/>
                        </div>
                      </td>
                    </tr>
                    {open && (
                      <tr className="bg-ink/60">
                        <td colSpan={7} className="px-4 py-4">
                          <div className="grid md:grid-cols-3 gap-5">
                            {/* breakdown */}
                            <div>
                              <div className="text-xs font-semibold text-haze uppercase tracking-wide mb-2">รายละเอียดการคำนวณ</div>
                              <dl className="space-y-1.5 text-sm">
                                <div className="flex justify-between"><dt className="text-haze">ค่าแรงฐาน</dt><dd className="num">{baht(p.base)}</dd></div>
                                <div className="flex justify-between"><dt className="text-haze">ค่า OT ({num(p.otHours)} ชม.)</dt><dd className="num text-hazard">+{baht(p.otPay)}</dd></div>
                                <div className="flex justify-between border-t border-line pt-1.5"><dt className="text-haze">รวมรายได้</dt><dd className="num font-semibold">{baht(p.gross)}</dd></div>
                              </dl>
                            </div>
                            {/* adjustments */}
                            <div>
                              <div className="flex items-center justify-between mb-2">
                                <div className="text-xs font-semibold text-haze uppercase tracking-wide">รายการหัก / เบิก</div>
                                <button onClick={()=>setAdjFor(p.worker)} className="tap text-xs text-brand font-semibold flex items-center gap-1"><Icon name="plus" size={13}/>เพิ่ม</button>
                              </div>
                              {p.dailyAdvance>0 && (
                                <div className="flex items-center justify-between text-sm mb-1.5">
                                  <span className="text-haze flex items-center gap-1.5"><Badge tone="warn">เบิกรายวัน</Badge>เบิกกิน-ใช้ระหว่างงวด ({p.dailyAdvanceDays.length} วัน)</span>
                                  <span className="num text-bad">−{baht(p.dailyAdvance)}</span>
                                </div>
                              )}
                              {p.adjs.length===0 && !(p.dailyAdvance>0) ? <div className="text-sm text-haze">ไม่มีรายการ</div> : (
                                <div className="space-y-1.5">
                                  {p.adjs.map(adj=>(
                                    <div key={adj.id} className="flex items-center justify-between text-sm group">
                                      <span className="text-haze flex items-center gap-1.5"><Badge tone={adj.kind==='advance'?'warn':adj.kind==='social'?'haze':'bad'}>{adj.kind==='advance'?'เบิก':adj.kind==='social'?'ปกส.':'หัก'}</Badge>{adj.label}</span>
                                      <span className="flex items-center gap-2">
                                        <span className="num text-bad">−{baht(adj.amount)}</span>
                                        <button onClick={()=>removeAdjustment(adj.id)} className="tap text-haze hover:text-bad opacity-0 group-hover:opacity-100"><Icon name="trash" size={14}/></button>
                                      </span>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                            {/* site allocation */}
                            <div>
                              <div className="text-xs font-semibold text-haze uppercase tracking-wide mb-2">ปันส่วนต้นทุนตามไซต์</div>
                              <div className="space-y-1.5 text-sm">
                                {Object.entries(p.bySite).map(([sid,v])=>{
                                  const s=db.sites.find(x=>x.id===sid);
                                  return <div key={sid} className="flex justify-between"><dt className="text-haze truncate flex items-center gap-1"><Icon name="pin" size={12}/>{s?.name||'—'}</dt><dd className="num">{baht(v.base+v.ot,0)}</dd></div>;
                                })}
                                {Object.keys(p.bySite).length===0 && <div className="text-haze">ไม่มีข้อมูล</div>}
                              </div>
                              <Button size="sm" icon="slip" className="mt-3 w-full" onClick={()=>{setSlip({workerId:p.worker.id,period}); go('payslip');}}>ออกสลิปเงินเดือน</Button>
                            </div>
                          </div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })}
            </tbody>
            <tfoot>
              <tr className="border-t-2 border-line font-display font-bold">
                <td className="px-4 py-3" colSpan={2}>รวมทั้งสิ้น ({rows.length} คน)</td>
                <td className="px-4 py-3 text-right num">{baht(rows.reduce((s,p)=>s+p.base,0),0)}</td>
                <td className="px-4 py-3 text-right num text-hazard">{baht(totalOt,0)}</td>
                <td className="px-4 py-3 text-right num text-bad">−{baht(totalDed,0)}</td>
                <td className="px-4 py-3 text-right num text-brand">{baht(totalNet,0)}</td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>

      <AdjustModal open={!!adjFor} onClose={()=>setAdjFor(null)} worker={adjFor} period={period}/>
    </div>
  );
}

Object.assign(window, { Attendance, Payroll });
