// ============ Payroll Calculator ============
// db.staff  = [{id, name, role, dailyRate, note}]
// db.payrollEvents = [{id, monthKey, createdAt, totalWage, rows:[{staffId,staffName,dailyRate,daysWorked,wage}]}]

const PAYROLL_ROLES = ['บาริสต้า','แคชเชียร์','เบเกอรี่','ครัว','ทำความสะอาด','ผู้จัดการ','Part-time','อื่นๆ'];

function newStaffId(){ return 'STF'+Date.now().toString(36).toUpperCase(); }

// ---------- Staff Form Modal ----------
function StaffModal({ item, onSave, onClose }){
  const [f,setF]=React.useState(item || {id:newStaffId(),name:'',role:'บาริสต้า',dailyRate:350,note:''});
  const ok=f.name.trim() && Number(f.dailyRate)>0;
  return <Modal open title={item?'แก้ไขข้อมูลพนักงาน':'เพิ่มพนักงาน'} onClose={onClose} width={420}
    footer={<><Button variant="secondary" onClick={onClose}>ยกเลิก</Button>
      <Button icon="check" onClick={()=>ok&&onSave({...f,dailyRate:Number(f.dailyRate)})} disabled={!ok}>บันทึก</Button></>}>
    <div style={{display:'flex',flexDirection:'column',gap:14}}>
      <Field label="ชื่อ-นามสกุล"><Input value={f.name} onChange={e=>setF({...f,name:e.target.value})} placeholder="สมชาย ใจดี"/></Field>
      <Field label="ตำแหน่ง">
        <select value={f.role} onChange={e=>setF({...f,role:e.target.value})}
          style={{width:'100%',padding:'9px 12px',borderRadius:10,border:'1.5px solid var(--line)',background:'var(--surface)',color:'var(--ink)',fontSize:14}}>
          {PAYROLL_ROLES.map(r=><option key={r} value={r}>{r}</option>)}
        </select>
      </Field>
      <Field label="อัตราค่าจ้าง (฿/วัน)"><Input type="number" value={f.dailyRate} onChange={e=>setF({...f,dailyRate:e.target.value})}/></Field>
      <Field label="หมายเหตุ (ไม่บังคับ)"><Input value={f.note} onChange={e=>setF({...f,note:e.target.value})} placeholder="เช่น สัญญาจ้าง, ประกันสังคม"/></Field>
    </div>
  </Modal>;
}

// ---------- Payroll Calculator Tab ----------
function PayrollCalc({ db, setDb, flash, THAI_MONTHS }){
  const months = aggregateByMonth(db);
  const [selKey,setSelKey] = React.useState(()=>months.length?months[months.length-1].key:'');
  const staff = db.staff || [];
  const { settings } = useData();

  // days worked state per staff for selected month — seed from saved payroll if exists
  const savedPayroll = React.useMemo(()=>
    (db.payrollEvents||[]).find(p=>p.monthKey===selKey), [selKey, db.payrollEvents]);

  const initDays = React.useCallback(()=>{
    if(savedPayroll){
      return Object.fromEntries(savedPayroll.rows.map(r=>[r.staffId, String(r.daysWorked)]));
    }
    return Object.fromEntries(staff.map(s=>[s.id,'26'])); // default 26 วัน
  },[selKey, savedPayroll, staff]);

  const [days,setDays]=React.useState(initDays);
  React.useEffect(()=>{ setDays(initDays()); },[selKey]);

  // HR integration
  const [hrLoading,setHrLoading]=React.useState(false);
  const [hrResult,setHrResult]=React.useState(null);
  const hrEnabled=!!(settings.hrEnabled && settings.hrSupabaseUrl && settings.hrAnonKey);

  const fetchFromHR = async () => {
    if(!hrEnabled||!selKey) return;
    setHrLoading(true); setHrResult(null);
    try {
      const [yr,mo]=selKey.split('-').map(Number);
      const base=(settings.hrSupabaseUrl||'').replace(/\/+$/,'');
      const res=await fetch(`${base}/rest/v1/rpc/get_payroll_month_summary`,{
        method:'POST',
        headers:{'Content-Type':'application/json','apikey':settings.hrAnonKey,'Authorization':`Bearer ${settings.hrAnonKey}`},
        body:JSON.stringify({p_year:yr,p_month:mo}),
      });
      if(!res.ok){ const t=await res.text(); throw new Error(`HR ${res.status}: ${t.slice(0,120)}`); }
      const hrData=await res.json();
      const newDays={...days};
      let matched=0; const unmatched=[];
      (hrData||[]).forEach(hr=>{
        const n=String(hr.emp_name||'').trim().toLowerCase();
        const s=staff.find(x=>String(x.name||'').trim().toLowerCase()===n);
        if(s){ newDays[s.id]=String(hr.days_worked??0); matched++; }
        else unmatched.push(hr.emp_name);
      });
      setDays(newDays);
      setHrResult({total:(hrData||[]).length,matched,unmatched});
      flash(`ดึงข้อมูล HR: จับคู่ ${matched}/${(hrData||[]).length} คน`);
    } catch(e){ flash('เชื่อม HR ไม่สำเร็จ: '+e.message,'err'); }
    finally{ setHrLoading(false); }
  };

  const rows = staff.map(s=>({
    ...s,
    daysWorked: Math.max(0, Number(days[s.id])||0),
    wage: s.dailyRate * Math.max(0, Number(days[s.id])||0),
  }));
  const totalWage = rows.reduce((s,r)=>s+r.wage,0);

  const selMonthObj = months.find(m=>m.key===selKey);
  const monthLabel = selMonthObj ? `${THAI_MONTHS[selMonthObj.monthIdx]} ${parseInt(selMonthObj.year)+543}` : selKey;

  const existingExpense = selKey && (db.expenseEvents||[]).find(e=>
    e.category==='labor' && e.source==='payroll' && String(e.paidAt||'').startsWith(selKey));

  const savePayroll = () => {
    if(!totalWage) return;
    const payRecord = {
      id:'PAY'+Date.now().toString(36).toUpperCase(),
      monthKey:selKey, createdAt:new Date().toISOString(), totalWage,
      rows:rows.map(r=>({staffId:r.id,staffName:r.name,dailyRate:r.dailyRate,daysWorked:r.daysWorked,wage:r.wage})),
    };
    // expense entry
    const expEntry = {
      id:'EXP'+Date.now().toString(36)+Math.random().toString(36).slice(2,5),
      category:'labor', source:'payroll', amount:totalWage,
      note:`เงินเดือนพนักงาน ${monthLabel} · ${rows.filter(r=>r.daysWorked>0).length} คน`,
      paidAt:selKey+'-28', createdAt:new Date().toISOString(),
    };
    setDb(prev=>{
      const prevPayroll=(prev.payrollEvents||[]).filter(p=>p.monthKey!==selKey);
      const prevExp=(prev.expenseEvents||[]).filter(e=>!(e.category==='labor'&&e.source==='payroll'&&String(e.paidAt||'').startsWith(selKey)));
      return {...prev, payrollEvents:[payRecord,...prevPayroll], expenseEvents:[expEntry,...prevExp]};
    });
    flash(`บันทึกเงินเดือน ${fmtB(totalWage)} สำหรับ ${monthLabel} แล้ว`);
  };

  if(!staff.length) return (
    <Empty icon="user" title="ยังไม่มีรายชื่อพนักงาน"
      sub="เพิ่มพนักงานในแท็บ 'พนักงาน' ก่อนคิดเงินเดือน"/>
  );

  return <div style={{display:'flex',flexDirection:'column',gap:18}}>
    {/* month selector + summary */}
    <div style={{display:'flex',gap:12,flexWrap:'wrap',alignItems:'center'}}>
      <Select value={selKey} onChange={e=>setSelKey(e.target.value)}
        options={months.length
          ? [...months].reverse().map(m=>({value:m.key,label:`${THAI_MONTHS[m.monthIdx]} ${parseInt(m.year)+543}`}))
          : [{value:'',label:'ยังไม่มีข้อมูลเดือน'}]}/>
      <div style={{flex:1}}/>
      {savedPayroll && <Badge tone="green">บันทึกแล้ว {fmtB(savedPayroll.totalWage)}</Badge>}
    </div>

    {hrEnabled && <div style={{display:'flex',gap:10,alignItems:'center',flexWrap:'wrap',padding:'10px 14px',background:'var(--surface-2)',borderRadius:12,border:'1px solid var(--line)'}}>
      <Button variant="soft" onClick={fetchFromHR} disabled={hrLoading||!selKey}>
        {hrLoading ? '⏳ กำลังดึง HR...' : '🔗 ดึงวันทำงานจาก HR'}
      </Button>
      {hrResult && <span style={{fontSize:13,color:hrResult.matched===hrResult.total?'var(--green)':'var(--orange)',fontWeight:500}}>
        จับคู่ {hrResult.matched}/{hrResult.total} คน
        {hrResult.unmatched.length>0&&<span style={{fontWeight:400,color:'var(--ink-3)'}}> · ไม่พบ: {hrResult.unmatched.join(', ')}</span>}
      </span>}
      {!hrResult && <span style={{fontSize:12.5,color:'var(--ink-3)'}}>ดึงจำนวนวันทำงานจริงจากระบบ HR แล้วเติมอัตโนมัติ</span>}
    </div>}

    {existingExpense && <div style={{padding:'10px 14px',background:'var(--green-soft)',borderRadius:10,fontSize:13,color:'var(--green)'}}>
      ✅ สร้างรายการค่าใช้จ่ายแรงงาน {fmtB(existingExpense.amount)} สำหรับ{monthLabel}แล้ว
      — KPI และ Dashboard จะใช้ข้อมูลนี้โดยอัตโนมัติ
    </div>}

    {/* payroll table */}
    <Card pad={0}>
      <table style={{width:'100%',borderCollapse:'collapse',fontSize:13.5}}>
        <thead><tr style={{color:'var(--ink-2)',fontSize:12,borderBottom:'1.5px solid var(--line)'}}>
          <th style={{textAlign:'left',padding:'11px 18px',fontWeight:600}}>พนักงาน</th>
          <th style={{textAlign:'left',padding:'11px 10px',fontWeight:600}}>ตำแหน่ง</th>
          <th style={{textAlign:'right',padding:'11px 10px',fontWeight:600}}>อัตรา/วัน</th>
          <th style={{textAlign:'center',padding:'11px 10px',fontWeight:600}}>วันทำงาน</th>
          <th style={{textAlign:'right',padding:'11px 18px',fontWeight:600}}>ค่าจ้าง</th>
        </tr></thead>
        <tbody>
          {rows.map(r=>(
            <tr key={r.id} style={{borderTop:'1px solid var(--line-2)'}}>
              <td style={{padding:'10px 18px',fontWeight:600}}>{r.name}</td>
              <td style={{padding:'10px 10px'}}><Badge tone="gray">{r.role}</Badge></td>
              <td className="tnum" style={{textAlign:'right',padding:'10px 10px',color:'var(--ink-2)'}}>{fmtB(r.dailyRate,0)}</td>
              <td style={{textAlign:'center',padding:'8px 10px'}}>
                <input type="number" min="0" max="31" value={days[r.id]||''} onChange={e=>setDays(prev=>({...prev,[r.id]:e.target.value}))}
                  style={{width:64,textAlign:'center',padding:'6px 8px',borderRadius:9,border:'1.5px solid var(--line)',
                    background:'var(--surface)',color:'var(--ink)',fontSize:14,fontFamily:'inherit'}}/>
              </td>
              <td className="tnum" style={{textAlign:'right',padding:'10px 18px',fontWeight:700,color:r.wage>0?'var(--green)':'var(--ink-3)'}}>
                {r.wage>0?fmtB(r.wage,0):'—'}
              </td>
            </tr>
          ))}
          <tr style={{borderTop:'2px solid var(--ink)',background:'var(--surface-2)'}}>
            <td colSpan={3} style={{padding:'12px 18px',fontWeight:700,fontSize:14}}>รวมทั้งหมด ({rows.filter(r=>r.daysWorked>0).length} คน)</td>
            <td className="tnum" style={{textAlign:'center',padding:'12px 10px',fontWeight:700}}>
              {rows.reduce((s,r)=>s+r.daysWorked,0)} วัน
            </td>
            <td className="tnum" style={{textAlign:'right',padding:'12px 18px',fontWeight:700,fontSize:16,color:'var(--green)'}}>
              {fmtB(totalWage,0)}
            </td>
          </tr>
        </tbody>
      </table>
    </Card>

    <div style={{display:'flex',gap:10,justifyContent:'flex-end',alignItems:'center',flexWrap:'wrap'}}>
      <div style={{fontSize:13,color:'var(--ink-2)'}}>
        บันทึกจะสร้างรายการค่าใช้จ่าย "แรงงาน" ให้อัตโนมัติ — ใช้ใน Dashboard, KPI, P&L
      </div>
      <Button icon="check" onClick={savePayroll} disabled={!totalWage}>
        {existingExpense ? 'อัปเดตเงินเดือน' : 'บันทึกเงินเดือน'} {totalWage>0?fmtB(totalWage,0):''}
      </Button>
    </div>
  </div>;
}

// ---------- Payroll History Tab ----------
function PayrollHistory({ db, setDb, flash, THAI_MONTHS }){
  const history = [...(db.payrollEvents||[])].sort((a,b)=>String(b.monthKey||'').localeCompare(String(a.monthKey||'')));
  if(!history.length) return <Empty icon="wallet" title="ยังไม่มีประวัติเงินเดือน" sub="คิดเงินเดือนในแท็บ 'คิดเงินเดือน' แล้วบันทึก"/>;
  return <div style={{display:'flex',flexDirection:'column',gap:14}}>
    {history.map(p=>{
      const months = aggregateByMonth(db);
      const m = months.find(mo=>mo.key===p.monthKey);
      const label = m ? `${THAI_MONTHS[m.monthIdx]} ${parseInt(m.year)+543}` : p.monthKey;
      return <Card key={p.id}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
          <div>
            <div style={{fontWeight:700,fontSize:14}}>{label}</div>
            <div style={{fontSize:12,color:'var(--ink-3)'}}>{p.rows?.length||0} คน · {new Date(p.createdAt).toLocaleDateString('th-TH',{dateStyle:'medium'})}</div>
          </div>
          <div style={{display:'flex',gap:8,alignItems:'center'}}>
            <span className="tnum" style={{fontSize:18,fontWeight:700,color:'var(--green)'}}>{fmtB(p.totalWage,0)}</span>
            <Button variant="ghost" size="sm" icon="trash" onClick={()=>{
              if(confirm(`ลบประวัติเงินเดือน ${label}?`)){
                setDb(prev=>({...prev, payrollEvents:(prev.payrollEvents||[]).filter(x=>x.id!==p.id)}));
                flash('ลบแล้ว');
              }
            }}/>
          </div>
        </div>
        <div style={{overflowX:'auto'}}>
          <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
            <thead><tr style={{color:'var(--ink-2)',fontSize:11.5}}>
              <th style={{textAlign:'left',padding:'5px 0',fontWeight:600}}>พนักงาน</th>
              <th style={{textAlign:'right',padding:'5px 0',fontWeight:600}}>วันทำงาน</th>
              <th style={{textAlign:'right',padding:'5px 0',fontWeight:600}}>อัตรา/วัน</th>
              <th style={{textAlign:'right',padding:'5px 0',fontWeight:600}}>ค่าจ้าง</th>
            </tr></thead>
            <tbody>{(p.rows||[]).filter(r=>r.daysWorked>0).map((r,i)=>(
              <tr key={i} style={{borderTop:'1px solid var(--line-2)'}}>
                <td style={{padding:'5px 0',fontWeight:500}}>{r.staffName}</td>
                <td className="tnum" style={{textAlign:'right',padding:'5px 0'}}>{r.daysWorked}</td>
                <td className="tnum" style={{textAlign:'right',padding:'5px 0',color:'var(--ink-2)'}}>{fmtB(r.dailyRate,0)}</td>
                <td className="tnum" style={{textAlign:'right',padding:'5px 0',fontWeight:600}}>{fmtB(r.wage,0)}</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      </Card>;
    })}
  </div>;
}

// ---------- Main Page ----------
function PayrollPage({ go }){
  const { db, setDb, flash, THAI_MONTHS } = useData();
  const [tab,setTab]=React.useState('calc');
  const [editStaff,setEditStaff]=React.useState(null);
  const [addOpen,setAddOpen]=React.useState(false);
  const staff = db.staff || [];

  const saveStaff = (s) => {
    setDb(prev=>{
      const list = prev.staff||[];
      const idx = list.findIndex(x=>x.id===s.id);
      return {...prev, staff: idx>=0 ? list.map(x=>x.id===s.id?s:x) : [...list,s]};
    });
    setEditStaff(null); setAddOpen(false);
    flash('บันทึกข้อมูลพนักงานแล้ว');
  };

  const deleteStaff = (id) => {
    if(!confirm('ลบพนักงานคนนี้?')) return;
    setDb(prev=>({...prev, staff:(prev.staff||[]).filter(s=>s.id!==id)}));
    flash('ลบพนักงานแล้ว');
  };

  return <div className="view-enter" style={{display:'flex',flexDirection:'column',gap:18}}>
    {/* Summary KPIs */}
    <div className="r-2col" style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:16}}>
      <Stat label="จำนวนพนักงาน" value={fmt(staff.length)} icon="user" tone="var(--accent)"
        sub={`บาริสต้า ${staff.filter(s=>s.role==='บาริสต้า').length} · อื่นๆ ${staff.filter(s=>s.role!=='บาริสต้า').length}`}/>
      <Stat label="ค่าจ้างเฉลี่ย/วัน" value={staff.length?fmtB(staff.reduce((s,x)=>s+x.dailyRate,0)/staff.length,0):'—'} icon="wallet" tone="var(--green)"/>
      <Stat label="ประมาณค่าแรง/เดือน (26 วัน)" value={fmtB(staff.reduce((s,x)=>s+x.dailyRate*26,0),0)} icon="sales" tone="var(--orange)"
        sub="อ้างอิง 26 วัน/คน"/>
    </div>

    {/* Tabs */}
    <div style={{display:'flex',gap:8,flexWrap:'wrap',alignItems:'center'}}>
      <Segmented value={tab} onChange={setTab} options={[
        {value:'calc',label:'คิดเงินเดือน'},
        {value:'staff',label:`พนักงาน (${staff.length})`},
        {value:'history',label:'ประวัติ'},
      ]}/>
      {tab==='staff' && <Button size="sm" icon="plus" onClick={()=>setAddOpen(true)}>เพิ่มพนักงาน</Button>}
    </div>

    {/* Tab: staff list */}
    {tab==='staff' && <>
      {!staff.length
        ? <Empty icon="user" title="ยังไม่มีพนักงาน" sub="เพิ่มพนักงานเพื่อเริ่มคิดเงินเดือน"
            action={<Button icon="plus" onClick={()=>setAddOpen(true)}>เพิ่มพนักงาน</Button>}/>
        : <Card pad={0}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:13.5}}>
              <thead><tr style={{color:'var(--ink-2)',fontSize:12,borderBottom:'1.5px solid var(--line)'}}>
                <th style={{textAlign:'left',padding:'11px 18px',fontWeight:600}}>ชื่อ</th>
                <th style={{textAlign:'left',padding:'11px 10px',fontWeight:600}}>ตำแหน่ง</th>
                <th style={{textAlign:'right',padding:'11px 10px',fontWeight:600}}>อัตรา/วัน</th>
                <th style={{textAlign:'right',padding:'11px 10px',fontWeight:600}}>ประมาณ/เดือน</th>
                <th style={{padding:'11px 18px'}}/>
              </tr></thead>
              <tbody>{staff.map(s=>(
                <tr key={s.id} style={{borderTop:'1px solid var(--line-2)'}}>
                  <td style={{padding:'10px 18px'}}>
                    <div style={{fontWeight:600}}>{s.name}</div>
                    {s.note&&<div style={{fontSize:11.5,color:'var(--ink-3)'}}>{s.note}</div>}
                  </td>
                  <td style={{padding:'10px 10px'}}><Badge tone="gray">{s.role}</Badge></td>
                  <td className="tnum" style={{textAlign:'right',padding:'10px 10px',fontWeight:600}}>{fmtB(s.dailyRate,0)}</td>
                  <td className="tnum" style={{textAlign:'right',padding:'10px 10px',color:'var(--ink-2)'}}>{fmtB(s.dailyRate*26,0)}</td>
                  <td style={{padding:'10px 18px',display:'flex',gap:6,justifyContent:'flex-end'}}>
                    <Button variant="ghost" size="sm" icon="edit" onClick={()=>setEditStaff(s)}/>
                    <Button variant="ghost" size="sm" icon="trash" onClick={()=>deleteStaff(s.id)}/>
                  </td>
                </tr>
              ))}</tbody>
            </table>
          </Card>}
    </>}

    {/* Tab: payroll calculator */}
    {tab==='calc' && <PayrollCalc db={db} setDb={setDb} flash={flash} THAI_MONTHS={THAI_MONTHS}/>}

    {/* Tab: history */}
    {tab==='history' && <PayrollHistory db={db} setDb={setDb} flash={flash} THAI_MONTHS={THAI_MONTHS}/>}

    {(addOpen || editStaff) && <StaffModal
      item={editStaff||null}
      onSave={saveStaff}
      onClose={()=>{ setAddOpen(false); setEditStaff(null); }}/>}
  </div>;
}

Object.assign(window, { PayrollPage });
