// ============================================================
// admin.jsx — AdminPanel + EditDayModal (สำหรับ ผจก/admin)
// ============================================================
const { useState:uSA, useMemo:uMA } = React;

// ---- แก้ไขตารางรายวัน ----
function EditDayModal({ date, store, setOverride, clearOverride, onClose }){
  if(!date) return null;
  const origMap = assignmentsForDate(date, store.overrides, store.leaves);
  const [map, setMap] = uSA(()=>({ ...origMap }));
  const changed = (sid)=> JSON.stringify(map[sid]) !== JSON.stringify(origMap[sid]);

  const setB = (sid,val)=> setMap(m=>({...m,[sid]:{...m[sid],b:val}}));
  const setShift = (sid,val)=> setMap(m=>{ const next={...m[sid],s:val}; if(val!=='c') delete next.customTime; return {...m,[sid]:next}; });
  const setCustomTime = (sid,val)=> setMap(m=>({...m,[sid]:{...m[sid],customTime:val}}));
  const toggleOff = (sid)=> setMap(m=>({ ...m, [sid]: m[sid]==='off' ? SLOTS[(STAFF.findIndex(s=>s.id===sid)+weekIndex(date))%SLOTS.length] : 'off' }));

  const save = ()=>{
    STAFF.forEach(s=>{
      if(!changed(s.id)) return;
      const baseAsgn = assignmentsForDate(date)[s.id];
      if(JSON.stringify(map[s.id]) === JSON.stringify(baseAsgn)){
        clearOverride(date, s.id);
      } else {
        setOverride(date, s.id, map[s.id]);
      }
    });
    onClose();
  };
  const reset = ()=>{ STAFF.forEach(s=>clearOverride(date,s.id)); onClose(); };

  return (
    <Overlay onClose={onClose}>
      <ModalBox title={`แก้ไขตาราง · ${date.getDate()} ${MONTHS_TH[date.getMonth()]}`} onClose={onClose} wide>
        <div style={{display:'flex',flexDirection:'column',gap:10,padding:'4px 0'}}>
          {STAFF.map(s=>{
            const a = map[s.id]; const off = a==='off';
            return (
              <div key={s.id} style={{display:'flex',alignItems:'center',gap:10,background:off?'#f5f6fa':'#fafbfc',
                border:'1px solid #ebedf2',borderRadius:12,padding:'10px 14px'}}>
                <Avatar staff={s} size={28}/>
                <span style={{fontWeight:600,fontSize:13.5,minWidth:60}}>{s.nick}</span>
                <span style={{fontSize:11,color:'#9aa1b0',flex:1}}>{TYPES[s.type].short}</span>
                <button onClick={()=>toggleOff(s.id)} style={{...pill,background:off?'#e9ebf0':'#f0f1f5',color:off?'#69707e':'#9aa1b0'}}>
                  {off ? 'หยุด ✓' : 'หยุด'}
                </button>
                {!off && <>
                  <select value={a.b} onChange={e=>setB(s.id,e.target.value)} style={selStyle}>
                    {Object.values(BRANCHES).filter(b=>b.id!=='off').map(b=><option key={b.id} value={b.id}>{b.name}</option>)}
                  </select>
                  <select value={a.s} onChange={e=>setShift(s.id,e.target.value)} style={selStyle}>
                    {Object.values(SHIFTS).map(sh=><option key={sh.id} value={sh.id}>{sh.label}{sh.id!=='c'?` ${sh.time}`:''}</option>)}
                  </select>
                  {a.s==='c' && (
                    <input value={a.customTime||''} onChange={e=>setCustomTime(s.id,e.target.value)}
                      placeholder="เช่น 09:00–15:00"
                      style={{border:'1px solid #e3e6ee',borderRadius:8,padding:'4px 8px',fontSize:12,fontFamily:'inherit',width:118}}/>
                  )}
                </>}
                {changed(s.id) && <span style={{width:8,height:8,borderRadius:'50%',background:'#e8745a'}}></span>}
              </div>
            );
          })}
        </div>
        <div style={{display:'flex',gap:10,marginTop:16,paddingTop:14,borderTop:'1px solid #eef0f4'}}>
          <button onClick={reset} style={{...btnStyle,background:'#f5f6fa',color:'#9aa1b0',flex:1}}>รีเซ็ต</button>
          <button onClick={save} style={{...btnStyle,background:'linear-gradient(100deg,#9a7616,#c19a2a)',color:'#fff',flex:2}}>บันทึก</button>
        </div>
      </ModalBox>
    </Overlay>
  );
}
const pill={border:'none',cursor:'pointer',borderRadius:999,padding:'4px 10px',fontSize:12,fontWeight:600,fontFamily:'inherit'};
const selStyle={border:'1px solid #e3e6ee',borderRadius:8,padding:'4px 8px',fontSize:12.5,fontFamily:'inherit',background:'#fff'};
const btnStyle={border:'none',cursor:'pointer',borderRadius:12,padding:'11px',fontSize:14,fontWeight:600,fontFamily:'inherit'};

// ---- AdminPanel ----
function AdminPanel({ store, updateLeave, updateOT, updateTransfer, onEditDay, onClose }){
  const [tab, setTab] = uSA('edit');
  const leaves = uMA(()=>Object.entries(store.leaves).map(([k,v])=>({k,date:new Date(v.ds+'T00:00:00'),...v}))
    .sort((a,b)=>a.date-b.date),[store.leaves]);
  const advLeaves = leaves.filter(l=>l.ltype==='advance');
  const emgLeaves = leaves.filter(l=>l.ltype!=='advance');
  const ots = uMA(()=>Object.entries(store.ots).map(([k,v])=>({k,date:new Date(v.ds+'T00:00:00'),...v}))
    .sort((a,b)=>a.date-b.date),[store.ots]);
  const transfers = uMA(()=>Object.entries(store.transfers||{}).map(([k,v])=>({k,date:new Date(v.ds+'T00:00:00'),...v}))
    .sort((a,b)=>a.date-b.date),[store.transfers]);

  const pending = (arr)=>arr.filter(x=>x.status==='pending');
  const tabs=[{id:'advance',  label:'ล่วงหน้า',  count:pending(advLeaves).length},
              {id:'emg',      label:'ฉุกเฉิน',    count:pending(emgLeaves).length},
              {id:'ot',       label:'OT',          count:pending(ots).length},
              {id:'transfer', label:'สลับสาขา',  count:pending(transfers).length},
              {id:'edit',     label:'แก้ตาราง',   count:0},
              {id:'log',      label:'บันทึก',     count:0}];

  return (
    <Overlay onClose={onClose}>
      <ModalBox title="แผงจัดการ (ผจก.)" onClose={onClose} wide>
        <div style={{display:'flex',gap:6,marginBottom:16}}>
          {tabs.map(t=>(
            <button key={t.id} onClick={()=>setTab(t.id)} style={{flex:1,border:'none',cursor:'pointer',fontFamily:'inherit',
              borderRadius:10,padding:'8px 6px',fontSize:13,fontWeight:600,position:'relative',
              background:tab===t.id?'linear-gradient(100deg,#9a7616,#c19a2a)':'#f3f4f8',
              color:tab===t.id?'#fff':'#6b7282'}}>
              {t.label}
              {t.count>0 && <span style={{position:'absolute',top:4,right:4,width:16,height:16,borderRadius:'50%',
                background:'#e8745a',color:'#fff',fontSize:9,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center'}}>{t.count}</span>}
            </button>
          ))}
        </div>
        {tab==='advance'  && <RequestList items={advLeaves} onAction={(item,status)=>updateLeave(item.date,item.staffId,status)} label="วันหยุดล่วงหน้า"/>}
        {tab==='emg'      && <RequestList items={emgLeaves} onAction={(item,status)=>updateLeave(item.date,item.staffId,status)} label="ลาฉุกเฉิน"/>}
        {tab==='ot'       && <RequestList items={ots}       onAction={(item,status)=>updateOT(item.date,item.staffId,status)} label="OT" showHours/>}
        {tab==='transfer' && <TransferAdminList items={transfers} onAction={(item,status)=>updateTransfer(item.date,item.staffId,status)} store={store}/>}
        {tab==='edit'     && <EditDatePicker onSelect={onEditDay} onClose={onClose}/>}
        {tab==='log'      && <AuditLogView audit={store.audit}/>}
      </ModalBox>
    </Overlay>
  );
}

function RequestList({ items, onAction, label, showHours }){
  if(items.length===0) return <div style={{textAlign:'center',padding:'32px 0',color:'#aeb4c2',fontSize:14}}>ไม่มีคำขอ{label}</div>;
  return (
    <div style={{display:'flex',flexDirection:'column',gap:8,maxHeight:420,overflowY:'auto'}}>
      {items.map(item=>{
        const s=STAFF_BY_ID[item.staffId]; const st=STATUS_STYLE[item.status];
        return (
          <div key={item.k} style={{display:'flex',alignItems:'center',gap:10,background:'#fafbfc',border:'1px solid #ebedf2',borderRadius:12,padding:'11px 14px'}}>
            <Avatar staff={s} size={28}/>
            <div style={{flex:1}}>
              <div style={{fontWeight:600,fontSize:13.5}}>{s.nick} <span style={{fontWeight:400,color:'#9aa1b0',fontSize:12}}>· {item.date.getDate()} {MONTHS_TH[item.date.getMonth()]}</span></div>
              {item.note && <div style={{fontSize:12,color:'#7b8194',marginTop:2}}>"{item.note}"</div>}
              {showHours && item.hours>0 && <div style={{fontSize:12,color:'#9aa1b0',marginTop:2}}>⏰ {item.hours} ชั่วโมง</div>}
            </div>
            <span style={{background:st.bg,color:st.col,borderRadius:999,padding:'3px 10px',fontSize:11.5,fontWeight:700}}>{st.label}</span>
            {item.status==='pending' && <>
              <button onClick={()=>onAction(item,'approved')} style={{...pill,background:'#e6f5f2',color:'#0e6b60'}}>อนุมัติ</button>
              <button onClick={()=>onAction(item,'denied')}   style={{...pill,background:'#fde8e8',color:'#b94040'}}>ปฏิเสธ</button>
            </>}
          </div>
        );
      })}
    </div>
  );
}

function TransferAdminList({ items, onAction, store }){
  if(items.length===0) return <div style={{textAlign:'center',padding:'32px 0',color:'#aeb4c2',fontSize:14}}>ไม่มีคำขอสลับสาขา</div>;
  return (
    <div style={{display:'flex',flexDirection:'column',gap:8,maxHeight:420,overflowY:'auto'}}>
      {items.map(item=>{
        const s=STAFF_BY_ID[item.staffId]; const st=STATUS_STYLE[item.status];
        const myA=assignmentsForDate(item.date,store.overrides,store.leaves)[item.staffId];
        const fromB=myA&&myA!=='off'?BRANCHES[myA.b]:null;
        const toB=BRANCHES[item.toBranch];
        return (
          <div key={item.k} style={{display:'flex',alignItems:'center',gap:10,background:'#fafbfc',border:'1px solid #ebedf2',borderRadius:12,padding:'11px 14px',flexWrap:'wrap'}}>
            <Avatar staff={s} size={28}/>
            <div style={{flex:1,minWidth:120}}>
              <div style={{fontWeight:600,fontSize:13.5}}>{s.nick}
                <span style={{fontWeight:400,color:'#9aa1b0',fontSize:12}}> · {item.date.getDate()} {MONTHS_TH[item.date.getMonth()]}</span>
              </div>
              <div style={{fontSize:12,color:'#7b8194',marginTop:3,display:'flex',alignItems:'center',gap:4,flexWrap:'wrap'}}>
                {fromB && <span style={{background:fromB.tint,color:fromB.text,borderRadius:5,padding:'1px 7px',fontWeight:600}}>{fromB.name}</span>}
                <span>→</span>
                {toB && <span style={{background:toB.tint,color:toB.text,borderRadius:5,padding:'1px 7px',fontWeight:600}}>{toB.name}</span>}
                <span style={{color:'#9aa1b0'}}>· {item.time} · ⛽ {item.fuel} บาท</span>
              </div>
            </div>
            <span style={{background:st.bg,color:st.col,borderRadius:999,padding:'3px 10px',fontSize:11.5,fontWeight:700}}>{st.label}</span>
            {item.status==='pending' && <>
              <button onClick={()=>onAction(item,'approved')} style={{...pill,background:'#e6f5f2',color:'#0e6b60'}}>อนุมัติ</button>
              <button onClick={()=>onAction(item,'denied')}   style={{...pill,background:'#fde8e8',color:'#b94040'}}>ปฏิเสธ</button>
            </>}
          </div>
        );
      })}
    </div>
  );
}

function EditDatePicker({ onSelect, onClose }){
  const [viewDate, setViewDate] = uSA(()=>new Date(TODAY.getFullYear(), TODAY.getMonth(), 1));
  const [sel, setSel] = uSA(null);
  const cells = monthGrid(viewDate.getFullYear(), viewDate.getMonth());
  const nb = {border:'none',background:'#f3f4f8',borderRadius:8,width:32,height:32,cursor:'pointer',fontSize:18,
    color:'#6b7282',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'inherit'};
  return (
    <div>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
        <button onClick={()=>setViewDate(d=>new Date(d.getFullYear(),d.getMonth()-1,1))} style={nb}>‹</button>
        <span style={{flex:1,textAlign:'center',fontWeight:700,fontSize:14,fontFamily:'Anuphan'}}>
          {MONTHS_TH[viewDate.getMonth()]} {thaiYear(viewDate.getFullYear())}
        </span>
        <button onClick={()=>setViewDate(d=>new Date(d.getFullYear(),d.getMonth()+1,1))} style={nb}>›</button>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:4,marginBottom:4}}>
        {WEEKDAYS_SHORT.map((d,i)=>(
          <div key={i} style={{textAlign:'center',fontSize:10,fontWeight:700,color:DOW_COLORS[i]}}>{d}</div>
        ))}
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:4}}>
        {cells.map((c,idx)=>!c.inMonth
          ? <div key={idx}/>
          : <button key={idx} onClick={()=>setSel(c.date)} style={{
              aspectRatio:'1',borderRadius:10,padding:0,
              border:`1px solid ${sel&&isSameDay(c.date,sel)?'#b8901f':'#ebedf2'}`,
              background:sel&&isSameDay(c.date,sel)?'#fef5e0':'#fff',
              fontFamily:'Anuphan',fontSize:13.5,
              fontWeight:isSameDay(c.date,TODAY)?700:400,
              color:isSameDay(c.date,TODAY)?'#b8901f':'#2b2f3a',cursor:'pointer',
            }}>{c.date.getDate()}</button>
        )}
      </div>
      {sel && <button onClick={()=>{onSelect(sel);onClose();}} style={{...btnStyle,background:'linear-gradient(100deg,#9a7616,#c19a2a)',color:'#fff',width:'100%',marginTop:14}}>
        แก้ไขวันที่ {sel.getDate()} {MONTHS_TH[sel.getMonth()]}
      </button>}
    </div>
  );
}

function fmtAsgn(a){
  if(!a) return 'ค่าเริ่มต้น';
  if(a==='off') return 'หยุด';
  const b=BRANCHES[a.b]; const sh=SHIFTS[a.s];
  const extra = a.s==='c' && a.customTime ? ` (${a.customTime})` : '';
  return `${b?.name||a.b} · ${sh?.label||a.s}${extra}`;
}
function fmtAuditTime(ts){
  const d=new Date(ts);
  return `${d.getDate()} ${MONTHS_TH[d.getMonth()]} ${thaiYear(d.getFullYear())} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')} น.`;
}

function AuditLogView({ audit }){
  const entries=[...(audit||[])].sort((a,b)=>b.at-a.at);
  if(entries.length===0) return <div style={{textAlign:'center',padding:'32px 0',color:'#aeb4c2',fontSize:14}}>ยังไม่มีประวัติการแก้ไขตาราง</div>;
  return (
    <div style={{display:'flex',flexDirection:'column',gap:8,maxHeight:420,overflowY:'auto'}}>
      {entries.map((e,i)=>{
        const who=STAFF_BY_ID[e.who]; const whom=STAFF_BY_ID[e.staffId];
        const dd=new Date(e.ds+'T00:00:00');
        return (
          <div key={i} style={{background:'#fafbfc',border:'1px solid #ebedf2',borderRadius:12,padding:'11px 14px'}}>
            <div style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap',marginBottom:5}}>
              {who && <Avatar staff={who} size={22}/>}
              <span style={{fontWeight:700,fontSize:13}}>{who?.nick||e.who}</span>
              <span style={{color:'#9aa1b0',fontSize:12}}>แก้เวร</span>
              <span style={{fontWeight:600,color:'#2b2f3a',fontSize:13}}>{whom?.nick||e.staffId}</span>
              <span style={{color:'#9aa1b0',fontSize:12}}>วันที่ {dd.getDate()} {MONTHS_TH[dd.getMonth()]} {thaiYear(dd.getFullYear())}</span>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:8,fontSize:12,paddingLeft:28}}>
              <span style={{background:'#fde8e8',color:'#b94040',borderRadius:6,padding:'2px 9px',fontWeight:600}}>{fmtAsgn(e.before)}</span>
              <span style={{color:'#9aa1b0'}}>→</span>
              <span style={{background:'#e6f5f2',color:'#0e6b60',borderRadius:6,padding:'2px 9px',fontWeight:600}}>{fmtAsgn(e.after)}</span>
            </div>
            <div style={{fontSize:11,color:'#bec3cf',marginTop:4,paddingLeft:28}}>{fmtAuditTime(e.at)}</div>
          </div>
        );
      })}
    </div>
  );
}

const STATUS_STYLE={
  pending:  {bg:'#fff4d6',col:'#9a6a12',label:'รอดำเนินการ'},
  approved: {bg:'#e6f5f2',col:'#0e6b60',label:'อนุมัติ'},
  denied:   {bg:'#fde8e8',col:'#b94040',label:'ปฏิเสธ'},
  accepted: {bg:'#e6f5f2',col:'#0e6b60',label:'สำเร็จ'},
  rejected: {bg:'#fde8e8',col:'#b94040',label:'ไม่รับ'},
};

// ---- shared modal shell ----
function Overlay({children,onClose}){
  return <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(20,15,5,.48)',display:'flex',alignItems:'center',justifyContent:'center',zIndex:60,backdropFilter:'blur(2px)'}}>
    <div onClick={e=>e.stopPropagation()}>{children}</div>
  </div>;
}
function ModalBox({title,onClose,children,wide}){
  return <div style={{background:'#fff',borderRadius:20,width:wide?'min(560px,95vw)':'min(420px,95vw)',maxHeight:'90vh',overflow:'auto',boxShadow:'0 32px 72px -20px rgba(0,0,0,.5)'}}>
    <div style={{padding:'18px 22px',borderBottom:'1px solid #eef0f4',display:'flex',alignItems:'center',justifyContent:'space-between',position:'sticky',top:0,background:'#fff'}}>
      <span style={{fontWeight:700,fontSize:17,fontFamily:'Anuphan'}}>{title}</span>
      <button onClick={onClose} style={{border:'none',background:'#f0f1f5',width:32,height:32,borderRadius:'50%',cursor:'pointer',fontSize:16,color:'#6b7282'}}>✕</button>
    </div>
    <div style={{padding:'18px 22px'}}>{children}</div>
  </div>;
}

Object.assign(window,{EditDayModal,AdminPanel,TransferAdminList,Overlay,ModalBox,STATUS_STYLE,btnStyle});
