// ============================================================
// views.jsx — ปฏิทิน / เมตริกซ์ / ของฉัน / modal  (with store)
// ============================================================
const { useMemo:uMV, useState:uSV } = React;

function ShiftBadge({ shift, customTime, withTime }){
  const sh = SHIFTS[shift];
  const timeLabel = (shift==='c' && customTime) ? customTime : sh.time;
  return <span style={{background:sh.tint,color:sh.text,borderRadius:6,padding:'1px 7px',fontSize:10.5,fontWeight:700,whiteSpace:'nowrap'}}>
    {sh.label}{withTime?` · ${timeLabel}`:''}
  </span>;
}

function WeekHeader(){
  return <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:8,marginBottom:8}}>
    {WEEKDAYS_TH.map((d,i)=>(
      <div key={i} style={{background:DOW_COLORS[i],color:'#fff',fontWeight:700,fontSize:14,textAlign:'center',padding:'9px 0',borderRadius:10}}>{d}</div>
    ))}
  </div>;
}

// ---------- แถบสาขา (chips คลิกได้ส่งคำขอ) ----------
function BranchBand({ branch, items, currentUserId, onChipClick }){
  const b = BRANCHES[branch];
  return <div style={{background:b.tint,borderRadius:8,padding:'5px 7px'}}>
    <div style={{fontSize:10,fontWeight:700,color:b.text,marginBottom:4}}>{b.name}</div>
    <div style={{display:'flex',flexDirection:'column',gap:4}}>
      {items.length===0
        ? <span style={{fontSize:10.5,color:'#bcc2cd'}}>— ปิด</span>
        : items.map(({staff,shift,customTime})=>{
          const isMe = staff.id===currentUserId;
          return <div key={staff.id} onClick={!isMe&&onChipClick ? ()=>onChipClick(staff) : undefined}
            style={{display:'flex',alignItems:'center',gap:5,borderRadius:6,padding:'2px 4px',
              cursor:isMe?'default':'pointer',
              background:isMe?'rgba(255,255,255,.6)':'rgba(255,255,255,.9)',
              transition:'opacity .12s'}}>
            <span style={{width:11,height:11,borderRadius:'50%',background:staffColor(staff,'solid'),flex:'0 0 auto'}}></span>
            <span style={{fontSize:11.5,fontWeight:isMe?700:600,color:'#2b2f3a'}}>{staff.nick}</span>
            {isMe && <span style={{fontSize:9,color:b.text,fontWeight:700,marginLeft:1}}>★</span>}
            <span style={{marginLeft:'auto'}}><ShiftBadge shift={shift} customTime={customTime}/></span>
          </div>;
        })}
    </div>
  </div>;
}

// ---------- ปฏิทิน ทุกคน ----------
function CalendarAll({ monthDate, store, currentUserId, isAdmin, onDayClick, onChipClick, onEditDay }){
  const ov=store.overrides, lv=store.leaves;
  const mob=useMobile();
  const cells = uMV(()=>monthGrid(monthDate.getFullYear(), monthDate.getMonth()),
    [monthDate.getFullYear(), monthDate.getMonth()]);

  // มือถือ: เซลล์กะทัดรัด กดทั้งเซลล์เปิด DayModal
  if(mob) return <div>
    <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:2,marginBottom:4}}>
      {WEEKDAYS_SHORT.map((d,i)=>(
        <div key={i} style={{textAlign:'center',fontSize:10.5,fontWeight:700,color:DOW_COLORS[i],padding:'6px 0'}}>{d}</div>
      ))}
    </div>
    <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:2}}>
      {cells.map((c,i)=>{
        const g=dayGroups(c.date,ov,lv);
        const dow=c.date.getDay(); const today=isSameDay(c.date,TODAY);
        return (
          <div key={i} onClick={()=>c.inMonth&&onDayClick(c.date)}
            style={{background:c.inMonth?'#fff':'#f7f8fb',border:today?'2px solid #b8901f':'1px solid #ebedf2',
              borderRadius:8,padding:'5px 3px',minHeight:62,display:'flex',flexDirection:'column',
              alignItems:'center',gap:2,opacity:c.inMonth?1:.35,cursor:c.inMonth?'pointer':'default'}}>
            <span style={{fontSize:12,fontWeight:700,fontFamily:'Anuphan',width:20,height:20,borderRadius:'50%',
              display:'flex',alignItems:'center',justifyContent:'center',
              background:today?'#b8901f':'transparent',color:today?'#fff':DOW_COLORS[dow]}}>
              {c.date.getDate()}
            </span>
            {c.inMonth && g.b1.length>0 && <div style={{display:'flex',alignItems:'center',gap:2}}>
              <span style={{width:6,height:6,borderRadius:'50%',background:BRANCHES.b1.solid,flex:'0 0 auto'}}/>
              <span style={{fontSize:9.5,color:BRANCHES.b1.text,fontWeight:700}}>{g.b1.length}</span>
            </div>}
            {c.inMonth && g.b2.length>0 && <div style={{display:'flex',alignItems:'center',gap:2}}>
              <span style={{width:6,height:6,borderRadius:'50%',background:BRANCHES.b2.solid,flex:'0 0 auto'}}/>
              <span style={{fontSize:9.5,color:BRANCHES.b2.text,fontWeight:700}}>{g.b2.length}</span>
            </div>}
            {c.inMonth && g.b1.length===0&&g.b2.length===0 && g.off.length>0 &&
              <span style={{fontSize:8.5,color:'#bcc2cd',marginTop:1}}>หยุด</span>}
          </div>
        );
      })}
    </div>
  </div>;

  // Desktop: เดิม
  return <div>
    <WeekHeader/>
    <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:8}}>
      {cells.map((c,i)=>{
        const g = dayGroups(c.date,ov,lv);
        const dow=c.date.getDay(); const today=isSameDay(c.date,TODAY); const working=g.b1.length+g.b2.length;
        return (
          <div key={i} style={{
            background:c.inMonth?'#fff':'#f7f8fb', border:today?'2px solid #b8901f':'1px solid #ebedf2',
            borderRadius:12, padding:8, minHeight:148, display:'flex', flexDirection:'column', gap:6,
            opacity:c.inMonth?1:.55, position:'relative',
          }}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
              <span onClick={()=>c.inMonth&&onDayClick(c.date)} style={{fontSize:14,fontWeight:700,fontFamily:'Anuphan',width:24,height:24,borderRadius:'50%',
                display:'flex',alignItems:'center',justifyContent:'center',cursor:c.inMonth?'pointer':'default',
                background:today?'#b8901f':'transparent',color:today?'#fff':DOW_COLORS[dow]}}>{c.date.getDate()}</span>
              {c.inMonth && <div style={{display:'flex',alignItems:'center',gap:4}}>
                {working>0 && <span style={{fontSize:10.5,color:'#aeb4c2',fontWeight:600}}>{working}</span>}
                {isAdmin && c.inMonth && <button onClick={()=>onEditDay(c.date)} title="แก้ไขตาราง"
                  style={{width:20,height:20,borderRadius:5,border:'none',background:'rgba(184,144,31,.12)',cursor:'pointer',
                  fontSize:11,display:'flex',alignItems:'center',justifyContent:'center',color:'#9a7616'}}>✎</button>}
              </div>}
            </div>
            {c.inMonth && <BranchBand branch="b1" items={g.b1} currentUserId={currentUserId} onChipClick={s=>c.inMonth&&onChipClick(s,c.date)}/>}
            {c.inMonth && <BranchBand branch="b2" items={g.b2} currentUserId={currentUserId} onChipClick={s=>c.inMonth&&onChipClick(s,c.date)}/>}
            {c.inMonth && g.off.length>0 && <div style={{fontSize:10.5,color:'#9aa1b0',marginTop:'auto'}}>หยุด: {g.off.map(s=>s.nick).join(', ')}</div>}
          </div>
        );
      })}
    </div>
  </div>;
}

// ---------- เมตริกซ์ ----------
function MatrixView({ monthDate, store, onProfileClick, isAdmin, onEditDay }){
  const ov=store.overrides, lv=store.leaves;
  const days = uMV(()=>daysOfMonth(monthDate.getFullYear(), monthDate.getMonth()),
    [monthDate.getFullYear(), monthDate.getMonth()]);
  const groups=[{type:'full',rows:STAFF.filter(s=>s.type==='full')},{type:'part',rows:STAFF.filter(s=>s.type==='part')}];
  const cols = days.map(d=>({d, map:assignmentsForDate(d,ov,lv)}));
  const nameW=132;
  return <div style={{background:'#fff',border:'1px solid #ebedf2',borderRadius:14,overflow:'hidden'}}>
    <div style={{overflowX:'auto'}}>
      <table style={{borderCollapse:'separate',borderSpacing:0,width:'100%',minWidth:nameW+days.length*40}}>
        <thead>
          <tr>
            <th style={{...mxH,position:'sticky',left:0,zIndex:3,width:nameW,minWidth:nameW,background:'#fff',textAlign:'left',paddingLeft:16}}>พนักงาน</th>
            {cols.map(({d})=>{
              const tod=isSameDay(d,TODAY);
              return <th key={d.getDate()} style={{...mxH,background:tod?'#fbf4e2':'#fafbfc'}}>
                <div style={{fontSize:9,color:DOW_COLORS[d.getDay()],fontWeight:700}}>{WEEKDAYS_SHORT[d.getDay()]}</div>
                <div style={{fontSize:12,fontWeight:700,color:tod?'#b8901f':'#5b6170',fontFamily:'Anuphan'}}>{d.getDate()}</div>
                {isAdmin && onEditDay && <button onClick={()=>onEditDay(d)} title="แก้ไข"
                  style={{border:'none',background:'transparent',cursor:'pointer',padding:'1px 2px',fontSize:10,color:'#b8901f',lineHeight:1,display:'block',margin:'0 auto'}}>✎</button>}
              </th>;
            })}
          </tr>
        </thead>
        <tbody>
          {groups.map(grp=>(
            <React.Fragment key={grp.type}>
              <tr><td colSpan={days.length+1} style={{position:'sticky',left:0,background:'#f3f4f8',padding:'5px 16px',fontSize:11.5,fontWeight:700,color:'#7b8194',borderTop:'1px solid #ebedf2'}}>{TYPES[grp.type].label}</td></tr>
              {grp.rows.map(s=>(
                <tr key={s.id}>
                  <td onClick={()=>onProfileClick&&onProfileClick(s)}
                    style={{position:'sticky',left:0,zIndex:1,background:'#fff',width:nameW,minWidth:nameW,padding:'6px 12px',borderTop:'1px solid #f1f2f6',cursor:onProfileClick?'pointer':'default'}}>
                    <span style={{display:'inline-flex',alignItems:'center',gap:8}}><Avatar staff={s} size={24}/><span style={{fontSize:13,fontWeight:600}}>{s.nick}</span></span>
                  </td>
                  {cols.map(({d,map})=>{
                    const a=map[s.id]; const tod=isSameDay(d,TODAY); const off=a==='off';
                    const b=off?null:BRANCHES[a.b];
                    // check if override
                    const dkStr=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}_${s.id}`;
                    const isOvr = ov[dkStr]!==undefined;
                    return <td key={d.getDate()} style={{borderTop:'1px solid #f1f2f6',textAlign:'center',padding:3,background:tod?'#fdfaf2':'#fff'}}>
                      <span style={{display:'inline-flex',alignItems:'center',justifyContent:'center',width:32,height:26,borderRadius:6,fontSize:11.5,fontWeight:800,fontFamily:'Anuphan',
                        background:off?'#f0f1f5':b.tint, color:off?'#c2c7d0':b.text,
                        borderBottom:off?'2px solid transparent':`2px solid ${SHIFTS[a.s].solid}`,
                        outline:isOvr?'2px solid #b8901f':'none', outlineOffset:1}}>
                        {off?'—':`${b.num}${SHIFTS[a.s].char}`}</span>
                    </td>;
                  })}
                </tr>
              ))}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
    <div style={{padding:'7px 14px',borderTop:'1px solid #f1f2f6',fontSize:11,color:'#9aa1b0',display:'flex',gap:16,flexWrap:'wrap'}}>
      <span>{BRANCHES.b1.num}={BRANCHES.b1.name} · {BRANCHES.b2.num}={BRANCHES.b2.name} &nbsp;|&nbsp; ช=เช้า · บ=บ่าย</span>
      <span style={{color:'#b8901f'}}>กรอบทอง = แก้ไขแล้ว</span>
    </div>
  </div>;
}
const mxH={padding:'8px 4px',textAlign:'center',borderBottom:'1px solid #ebedf2',position:'sticky',top:0,zIndex:2};

// ---------- ของฉัน ----------
function MineView({ monthDate, store, currentUserId, onLeaveDay, onOTDay, onAdvanceLeave, onTransferDay }){
  const ov=store.overrides, lv=store.leaves, ots=store.ots, trs=store.transfers||{};
  const me=STAFF_BY_ID[currentUserId];
  const cells=uMV(()=>monthGrid(monthDate.getFullYear(),monthDate.getMonth()),[monthDate.getFullYear(),monthDate.getMonth()]);
  const days=daysOfMonth(monthDate.getFullYear(),monthDate.getMonth());
  const inRotation=STAFF.some(s=>s.id===currentUserId);
  const mob=useMobile();
  const [selDate,setSelDate]=uSV(null);

  const cnt={b1:0,b2:0,off:0,m:0,a:0};
  if(inRotation) days.forEach(d=>{ const a=assignmentsForDate(d,ov,lv)[me.id]; if(a==='off')cnt.off++; else{cnt[a.b]++;cnt[a.s]++;} });

  if(!inRotation) return (
    <div style={{textAlign:'center',padding:'60px 20px',color:'#9aa1b0'}}>
      <div style={{fontSize:52,marginBottom:12}}>👤</div>
      <div style={{fontSize:18,fontWeight:700,fontFamily:'Anuphan',marginBottom:8,color:'#4a5060'}}>ไม่มีตารางเวร</div>
      <div style={{fontSize:13}}>บัญชีนี้ไม่ได้อยู่ในระบบเวร</div>
    </div>
  );

  // ---- Mobile ----
  if(mob){
    const mk=n=>String(n).padStart(2,'0');
    const selDk=selDate?`${selDate.getFullYear()}-${mk(selDate.getMonth()+1)}-${mk(selDate.getDate())}_${me.id}`:null;
    const selA=selDate?assignmentsForDate(selDate,ov,lv)[me.id]:null;
    const selOff=!selA||selA==='off'; const selWorking=selDate&&!selOff;
    const selB=selWorking&&selA&&selA!=='off'?BRANCHES[selA.b]:null;
    const selLeave=selDk?lv[selDk]:null; const selOT=selDk?ots[selDk]:null; const selTransfer=selDk?trs[selDk]:null;

    return <div>
      <div style={{display:'flex',gap:6,marginBottom:8,flexWrap:'wrap'}}>
        <SummaryPill branch="b1" n={cnt.b1}/><SummaryPill branch="b2" n={cnt.b2}/><SummaryPill branch="off" n={cnt.off}/>
      </div>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10}}>
        <span style={{fontSize:12,color:'#9aa1b0'}}>เช้า {cnt.m} · บ่าย {cnt.a} · รวม {cnt.b1+cnt.b2} วัน</span>
        <button onClick={onAdvanceLeave} style={{border:'1.5px solid #b8901f',borderRadius:999,
          padding:'5px 11px',background:'#fef5e0',color:'#9a6a12',fontWeight:700,fontSize:12,cursor:'pointer',fontFamily:'inherit'}}>
          🗓 ยื่นล่วงหน้า
        </button>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:2,marginBottom:3}}>
        {WEEKDAYS_SHORT.map((d,i)=>(
          <div key={i} style={{textAlign:'center',fontSize:10,fontWeight:700,color:DOW_COLORS[i],padding:'5px 0'}}>{d}</div>
        ))}
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:2}}>
        {cells.map((cell,i)=>{
          const a=cell.inMonth?assignmentsForDate(cell.date,ov,lv)[me.id]:null;
          const off=a==='off'; const working=cell.inMonth&&!off;
          const b=working?BRANCHES[a.b]:null;
          const today=isSameDay(cell.date,TODAY); const dow=cell.date.getDay();
          const dkStr=cell.inMonth?`${cell.date.getFullYear()}-${mk(cell.date.getMonth()+1)}-${mk(cell.date.getDate())}_${me.id}`:null;
          const leaveRec=dkStr?lv[dkStr]:null; const otRec=dkStr?ots[dkStr]:null; const transferRec=dkStr?trs[dkStr]:null;
          const sel=selDate&&cell.inMonth&&isSameDay(cell.date,selDate);
          return (
            <div key={i} onClick={()=>cell.inMonth&&setSelDate(sel?null:cell.date)}
              style={{background:sel?'#fef5e0':cell.inMonth?'#fff':'#f7f8fb',
                border:sel?'2px solid #b8901f':today?'2px solid #e8c97055':'1px solid #ebedf2',
                borderRadius:8,padding:'5px 2px',minHeight:62,display:'flex',flexDirection:'column',
                alignItems:'center',gap:2,opacity:cell.inMonth?1:.3,cursor:cell.inMonth?'pointer':'default'}}>
              <span style={{fontSize:11,fontWeight:700,fontFamily:'Anuphan',width:18,height:18,borderRadius:'50%',
                display:'flex',alignItems:'center',justifyContent:'center',
                background:today?'#b8901f':'transparent',color:today?'#fff':DOW_COLORS[dow]}}>
                {cell.date.getDate()}
              </span>
              {cell.inMonth && working && !leaveRec && (
                <span style={{background:b.solid,color:'#fff',borderRadius:4,padding:'1px 4px',fontSize:9,fontWeight:800}}>
                  {b.num}{SHIFTS[a.s].char}
                </span>
              )}
              {cell.inMonth && leaveRec && (
                <span style={{background:'#fde8e8',color:'#b94040',borderRadius:3,fontSize:8,fontWeight:700,padding:'1px 3px'}}>ลา</span>
              )}
              {cell.inMonth && otRec && (
                <span style={{background:'#ececfb',color:'#46449e',borderRadius:3,fontSize:8,fontWeight:700,padding:'1px 3px'}}>OT</span>
              )}
              {cell.inMonth && transferRec && (
                <span style={{background:'#ecf5e8',color:'#3a6128',borderRadius:3,fontSize:8,fontWeight:700,padding:'1px 3px'}}>🚗</span>
              )}
              {cell.inMonth && off && !leaveRec && (
                <span style={{fontSize:8,color:'#c2c7d0'}}>หยุด</span>
              )}
            </div>
          );
        })}
      </div>

      {selDate && (
        <div style={{marginTop:12,background:'#fff',borderRadius:14,padding:'14px 16px',border:'1px solid #e8e2d4',boxShadow:'0 4px 16px -8px rgba(0,0,0,.12)'}}>
          <div style={{fontSize:14,fontWeight:700,marginBottom:10,fontFamily:'Anuphan',color:'#2b2f3a'}}>
            {selDate.getDate()} {MONTHS_TH[selDate.getMonth()]} · วัน{WEEKDAYS_TH[selDate.getDay()]}
          </div>
          {selWorking && !selLeave && (
            <div style={{background:selB.tint,borderRadius:10,padding:'10px 12px',marginBottom:10,borderLeft:`3px solid ${selB.solid}`}}>
              <div style={{fontSize:13,fontWeight:700,color:selB.text}}>{selB.name}</div>
              <div style={{fontSize:11,color:SHIFTS[selA.s].text,marginTop:2}}>{SHIFTS[selA.s].label} · {(selA.s==='c'&&selA.customTime)||SHIFTS[selA.s].time}</div>
            </div>
          )}
          {selLeave && <div style={{marginBottom:10}}><StatusChip status={selLeave.status} label="วันหยุด"/></div>}
          {selOT && <div style={{marginBottom:10}}><StatusChip status={selOT.status} label={`OT ${selOT.hours}ชม.`}/></div>}
          {selTransfer && <div style={{marginBottom:10}}><StatusChip status={selTransfer.status} label={`🚗 →${BRANCHES[selTransfer.toBranch]?.name||'?'} ${selTransfer.time} ⛽${selTransfer.fuel}฿`}/></div>}
          {selOff && !selLeave && <div style={{fontSize:12.5,color:'#b6bcc8',marginBottom:10}}>วันหยุดประจำสัปดาห์</div>}
          {selWorking && (
            <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
              {!selLeave && <MiniBtn label="ลาฉุกเฉิน" color="#b94040" onClick={()=>{onLeaveDay(selDate);setSelDate(null);}}/>}
              {!selOT && <MiniBtn label="OT" color="#6664c4" onClick={()=>{onOTDay(selDate);setSelDate(null);}}/>}
              {!selLeave && !selTransfer && <MiniBtn label="🚗 สลับสาขา" color="#3a6128" onClick={()=>{onTransferDay(selDate);setSelDate(null);}}/>}
            </div>
          )}
        </div>
      )}
    </div>;
  }

  // ---- Desktop ----
  return <div>
    <div style={{display:'flex',gap:10,marginBottom:14,flexWrap:'wrap',alignItems:'center'}}>
      <SummaryPill branch="b1" n={cnt.b1}/><SummaryPill branch="b2" n={cnt.b2}/><SummaryPill branch="off" n={cnt.off}/>
      <span style={{width:1,height:24,background:'#e3e6ee'}}></span>
      <span style={{...mPill,background:SHIFTS.m.tint,color:SHIFTS.m.text}}>เช้า {cnt.m}</span>
      <span style={{...mPill,background:SHIFTS.a.tint,color:SHIFTS.a.text}}>บ่าย {cnt.a}</span>
      <span style={{fontSize:12.5,color:'#9aa1b0'}}>รวม {cnt.b1+cnt.b2} วัน</span>
      <button onClick={onAdvanceLeave} style={{marginLeft:'auto',border:'1.5px solid #b8901f',borderRadius:999,
        padding:'7px 16px',background:'#fef5e0',color:'#9a6a12',fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit',display:'flex',alignItems:'center',gap:6}}>
        🗓 ยื่นล่วงหน้า
        <span style={{fontSize:11,fontWeight:500,color:'#b8901f'}}>(ก่อน 28 ของเดือน)</span>
      </button>
    </div>
    <WeekHeader/>
    <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:8}}>
      {cells.map((cell,i)=>{
        const a=cell.inMonth?assignmentsForDate(cell.date,ov,lv)[me.id]:null;
        const off=!a||a==='off'; const working=cell.inMonth&&!off;
        const b=working&&a&&a!=='off'?BRANCHES[a.b]:null;
        const today=isSameDay(cell.date,TODAY); const dow=cell.date.getDay();
        const dkStr=cell.inMonth?`${cell.date.getFullYear()}-${String(cell.date.getMonth()+1).padStart(2,'0')}-${String(cell.date.getDate()).padStart(2,'0')}_${me.id}`:null;
        const leaveRec=dkStr?lv[dkStr]:null;
        const otRec=dkStr?ots[dkStr]:null;
        const transferRec=dkStr?trs[dkStr]:null;

        return <div key={i} style={{background:cell.inMonth?'#fff':'#f7f8fb',border:today?'2px solid #b8901f':'1px solid #ebedf2',
          borderRadius:12,padding:9,minHeight:110,opacity:cell.inMonth?1:.5,display:'flex',flexDirection:'column',gap:6}}>
          <span style={{fontSize:14,fontWeight:700,fontFamily:'Anuphan',alignSelf:'flex-start',width:24,height:24,borderRadius:'50%',
            display:'flex',alignItems:'center',justifyContent:'center',
            background:today?'#b8901f':'transparent',color:today?'#fff':DOW_COLORS[dow]}}>{cell.date.getDate()}</span>

          {cell.inMonth && working && !leaveRec && (
            <div style={{background:b.tint,borderRadius:8,padding:'6px 8px',borderLeft:`3px solid ${b.solid}`}}>
              <div style={{fontSize:12.5,fontWeight:700,color:b.text}}>{b.name}</div>
              <div style={{fontSize:10.5,fontWeight:600,color:SHIFTS[a.s].text,marginTop:2}}>{SHIFTS[a.s].label} · {(a.s==='c'&&a.customTime)||SHIFTS[a.s].time}</div>
            </div>
          )}
          {cell.inMonth && working && leaveRec && (
            <StatusChip status={leaveRec.status} label="วันหยุด"/>
          )}
          {cell.inMonth && off && !leaveRec && (
            <div style={{color:'#b6bcc8',fontSize:12,fontWeight:600,textAlign:'center',margin:'auto'}}>หยุด</div>
          )}
          {cell.inMonth && otRec && (
            <StatusChip status={otRec.status} label={`OT ${otRec.hours}ชม.`}/>
          )}
          {cell.inMonth && transferRec && (
            <StatusChip status={transferRec.status} label={`🚗 →${BRANCHES[transferRec.toBranch]?.name||'?'} ${transferRec.time}`}/>
          )}

          {cell.inMonth && working && (
            <div style={{display:'flex',gap:4,marginTop:'auto',flexWrap:'wrap'}}>
              {!leaveRec && <MiniBtn label="ลาฉุกเฉิน" color="#b94040" onClick={()=>onLeaveDay(cell.date)}/>}
              {!otRec && <MiniBtn label="OT" color="#6664c4" onClick={()=>onOTDay(cell.date)}/>}
              {!leaveRec && !transferRec && <MiniBtn label="🚗 สลับ" color="#3a6128" onClick={()=>onTransferDay(cell.date)}/>}
            </div>
          )}
        </div>;
      })}
    </div>
  </div>;
}

function MiniBtn({label,color,onClick}){
  return <button onClick={onClick} style={{border:`1px solid ${color}33`,background:`${color}11`,color,borderRadius:6,padding:'2px 7px',fontSize:10.5,fontWeight:700,cursor:'pointer',fontFamily:'inherit'}}>{label}</button>;
}
function StatusChip({ status, label }){
  const st=STATUS_STYLE?STATUS_STYLE[status]:{bg:'#fff4d6',col:'#9a6a12',label:'รอ'};
  return <div style={{background:st.bg,color:st.col,borderRadius:7,padding:'4px 8px',fontSize:11,fontWeight:700}}>{st.label} · {label}</div>;
}
const mPill={display:'inline-flex',alignItems:'center',borderRadius:999,padding:'7px 13px',fontWeight:700,fontSize:13};
function SummaryPill({ branch, n }){
  const b=BRANCHES[branch];
  return <span style={{display:'inline-flex',alignItems:'center',gap:8,background:b.tint,borderRadius:999,padding:'8px 16px',color:b.text,fontWeight:700,fontSize:14}}>
    <span style={{width:12,height:12,borderRadius:4,background:b.solid}}></span>
    {b.name} <span style={{fontFamily:'Anuphan',fontSize:16}}>{n}</span>
  </span>;
}

// ---------- DayModal ----------
function DayModal({ date, store, isAdmin, onEdit, onClose, onProfileClick }){
  if(!date) return null;
  const g=dayGroups(date, store.overrides, store.leaves);
  return (
    <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(30,24,10,.45)',display:'flex',alignItems:'center',justifyContent:'center',zIndex:50,backdropFilter:'blur(2px)'}}>
      <div onClick={e=>e.stopPropagation()} style={{background:'#fff',borderRadius:18,width:'min(560px,92vw)',maxHeight:'86vh',overflow:'auto',boxShadow:'0 30px 70px -20px rgba(40,30,10,.5)'}}>
        <div style={{padding:'18px 22px',borderBottom:'1px solid #eef0f4',display:'flex',alignItems:'center',justifyContent:'space-between',position:'sticky',top:0,background:'#fff'}}>
          <div>
            <div style={{fontSize:11,color:DOW_COLORS[date.getDay()],fontWeight:700}}>วัน{WEEKDAYS_TH[date.getDay()]}</div>
            <div style={{fontSize:19,fontWeight:700,fontFamily:'Anuphan'}}>{date.getDate()} {MONTHS_TH[date.getMonth()]} {thaiYear(date.getFullYear())}</div>
          </div>
          <div style={{display:'flex',gap:8,alignItems:'center'}}>
            {isAdmin && <button onClick={()=>onEdit(date)} style={{border:'none',background:'#fef5e0',color:'#9a7616',borderRadius:8,padding:'6px 12px',cursor:'pointer',fontWeight:600,fontSize:12,fontFamily:'inherit'}}>✎ แก้ไข</button>}
            <button onClick={onClose} style={{border:'none',background:'#f0f1f5',width:34,height:34,borderRadius:'50%',cursor:'pointer',fontSize:18,color:'#6b7282'}}>✕</button>
          </div>
        </div>
        <div style={{padding:22,display:'flex',flexDirection:'column',gap:16}}>
          {['b1','b2'].map(k=>(
            <div key={k}>
              <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
                <span style={{width:14,height:14,borderRadius:5,background:BRANCHES[k].solid}}></span>
                <span style={{fontWeight:700,fontSize:15}}>{BRANCHES[k].name}</span>
                <span style={{fontSize:12,color:'#9aa1b0'}}>{g[k].length} คน</span>
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:7}}>
                {g[k].length===0&&<div style={{fontSize:12.5,color:'#b6bcc8',paddingLeft:2}}>ไม่มีพนักงาน</div>}
                {g[k].map(({staff,shift,customTime})=>(
                  <div key={staff.id} onClick={()=>onProfileClick&&onProfileClick(staff)}
                    style={{display:'flex',alignItems:'center',gap:10,background:BRANCHES[k].tint,borderRadius:10,padding:'8px 12px',
                      cursor:onProfileClick?'pointer':'default',transition:'opacity .12s'}}>
                    <Avatar staff={staff} size={30}/>
                    <span style={{fontWeight:600,fontSize:14}}>{staff.full}</span>
                    <span style={{fontSize:10.5,color:'#8a91a0',background:'#fff',borderRadius:999,padding:'2px 9px'}}>{TYPES[staff.type].short}</span>
                    <span style={{marginLeft:'auto'}}><ShiftBadge shift={shift} customTime={customTime} withTime/></span>
                  </div>
                ))}
              </div>
            </div>
          ))}
          {g.off.length>0&&<div style={{fontSize:13,color:'#9aa1b0'}}><b style={{color:'#79808f'}}>หยุด:</b> {g.off.map(s=>s.nick).join(', ')}</div>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window,{CalendarAll,MatrixView,MineView,DayModal,ShiftBadge,BranchBand});
