// ============================================================
// app.jsx — Login + App หลัก (multi-user, store, all modals)
// ============================================================
const { useState:uSApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "branch1": "ฟาร์ม่าวัน",
  "branch2": "น้ำริดเภสัช",
  "navTheme": "ทอง"
}/*EDITMODE-END*/;

const NAV_THEMES = {
  'ทอง':   'linear-gradient(100deg,#7a5d12,#a8821c 52%,#caa531)',
  'ม่วง':   'linear-gradient(100deg,#241f47,#322c63 60%,#3a3170)',
  'เขียว':  'linear-gradient(100deg,#103d39,#15605a 60%,#1c7a70)',
  'กรมท่า': 'linear-gradient(100deg,#16233c,#24365a 60%,#2d4470)',
};

const LOGIN_MAP = {
  'pha139':'pron', 'พร':'pron', 'pron':'pron',
  'แบม':'baem',   'baem':'baem',
  'ครีม':'cream', 'cream':'cream',
  'ฟิล์ม':'film', 'film':'film',
  'หยก':'yok',   'yok':'yok',
  'ฟอร์ม':'form', 'form':'form',
};
const ADMIN_IDS = ['pron','cream','yok','form'];

// ---- Login ----
function Login({ onLogin }){
  const [u,setU]=uSApp('พร'), [p,setP]=uSApp(''), [err,setErr]=uSApp('');
  const submit=e=>{
    e.preventDefault();
    const sid=LOGIN_MAP[u.trim()];
    if(!sid||p.trim()===''){setErr('ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง');return;}
    onLogin(sid);
  };
  const logins=[['พร','พร'],['แบม','แบม'],['ครีม','ครีม'],['ฟิล์ม','ฟิล์ม'],['หยก','หยก'],['ฟอร์ม','ฟอร์ม']];
  return (
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',
      background:'radial-gradient(1100px 600px at 70% -10%, #3c2f12 0%, #241c0a 55%, #151006 100%)',
      padding:20,fontFamily:'IBM Plex Sans Thai, sans-serif'}}>
      <div style={{width:'min(400px,94vw)'}}>
        <div style={{textAlign:'center',marginBottom:28,color:'#fff'}}>
          <img src="assets/icon.png" alt="หมื่นเจริญ"
            style={{width:100,height:100,borderRadius:24,display:'block',margin:'0 auto 18px',
              boxShadow:'0 8px 40px rgba(168,130,28,.55), 0 2px 12px rgba(0,0,0,.4)'}}/>
          <div style={{fontWeight:800,fontSize:26,fontFamily:'Anuphan',color:'#f0d98a',letterSpacing:.5,lineHeight:1.1}}>หมื่นเจริญ</div>
          <div style={{fontSize:10,letterSpacing:4,color:'rgba(202,191,160,.65)',marginTop:4,fontWeight:600}}>MUEN CHAROEN</div>
          <div style={{fontSize:12.5,color:'#cabfa0',marginTop:10}}>ตารางเวียนพนักงานร้านยา · 2 สาขา</div>
        </div>
        <form onSubmit={submit} style={{background:'#fff',borderRadius:20,padding:'26px 24px',boxShadow:'0 30px 60px -25px rgba(0,0,0,.5)'}}>
          <div style={{fontSize:17,fontWeight:700,marginBottom:18,color:'#2b2f3a'}}>เข้าสู่ระบบ</div>
          <Field label="ชื่อผู้ใช้"><input value={u} onChange={e=>{setU(e.target.value);setErr('');}} placeholder="pha139" style={inp}/></Field>
          <Field label="รหัสผ่าน"><input type="password" value={p} onChange={e=>{setP(e.target.value);setErr('');}} placeholder="••••" style={inp}/></Field>
          {err && <div style={{color:'#e0533a',fontSize:12.5,marginBottom:10}}>{err}</div>}
          <button type="submit" style={{width:'100%',padding:'12px',borderRadius:12,border:'none',cursor:'pointer',
            fontFamily:'inherit',fontSize:15,fontWeight:700,color:'#fff',background:'linear-gradient(100deg,#9a7616,#c19a2a)',marginTop:4}}>เข้าสู่ระบบ</button>
          <div style={{marginTop:14,padding:'10px 12px',background:'#f5f6fa',borderRadius:10,fontSize:12,color:'#8a91a0'}}>
            <b style={{display:'block',marginBottom:6,color:'#6b7282'}}>เข้าสู่ระบบด้วย:</b>
            <div style={{display:'flex',flexWrap:'wrap',gap:6}}>
              {logins.map(([k,label])=>(
                <button key={k} type="button" onClick={()=>setU(k)} style={{border:'1px solid #e3e6ee',borderRadius:8,padding:'4px 10px',
                  background:'#fff',color:'#a8821c',fontWeight:600,fontSize:12,cursor:'pointer',fontFamily:'inherit'}}>{label}</button>
              ))}
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
function Field({label,children}){return <label style={{display:'block',marginBottom:14}}><span style={{display:'block',fontSize:12.5,fontWeight:600,color:'#6b7282',marginBottom:6}}>{label}</span>{children}</label>;}
const inp={width:'100%',padding:'11px 13px',borderRadius:11,border:'1.5px solid #e3e6ee',fontSize:14.5,fontFamily:'inherit',outline:'none',boxSizing:'border-box',background:'#fafbfc'};

// ---- AppInner ----
function AppInner({ currentUserId, onLogout }){
  const [t,setTweak]=useTweaks(TWEAK_DEFAULTS);
  BRANCHES.b1.name=t.branch1||'ฟาร์ม่าวัน';
  BRANCHES.b2.name=t.branch2||'น้ำริดเภสัช';

  const { store, setOverride, clearOverride,
    requestLeave, requestAdvanceLeaves, updateLeave, cancelLeave,
    requestOT, updateOT, cancelOT,
    requestTransfer, updateTransfer, cancelTransfer,
    sendRequest, updateRequest, cancelRequest,
    pendingLeavesAdmin, pendingOTsAdmin, pendingTransfersAdmin, pendingRequestsFor } = useStore();

  const isAdmin = ADMIN_IDS.includes(currentUserId);
  const me = STAFF_BY_ID[currentUserId];

  const [scope,setScope]=uSApp('all');
  const [view,setView]=uSApp('calendar');
  const [month,setMonth]=uSApp(()=>{ const n=new Date(); return new Date(n.getFullYear(),n.getMonth(),1); });
  const moveMonth=d=>setMonth(new Date(month.getFullYear(),month.getMonth()+d,1));

  const [dayModal,setDayModal]=uSApp(null);
  const [editDay,setEditDay]=uSApp(null);
  const [adminPanel,setAdminPanel]=uSApp(false);
  const [notifPanel,setNotifPanel]=uSApp(false);
  const [sendReq,setSendReq]=uSApp(null);
  const [leaveDay,setLeaveDay]=uSApp(null);
  const [advLeave,setAdvLeave]=uSApp(false);
  const [otDay,setOtDay]=uSApp(null);
  const [profileStaff,setProfileStaff]=uSApp(null);
  const [transferDay,setTransferDay]=uSApp(null);

  const incomingReqs = pendingRequestsFor(currentUserId).length;
  const adminPending = isAdmin ? (pendingLeavesAdmin().length + pendingOTsAdmin().length + pendingTransfersAdmin().length) : 0;
  const badge = incomingReqs + adminPending;

  const y=month.getFullYear(), m=month.getMonth();
  const todayInMonth=TODAY.getMonth()===m&&TODAY.getFullYear()===y;
  const g=dayGroups(todayInMonth?TODAY:new Date(y,m,1), store.overrides, store.leaves);
  const title=scope==='mine'?'เวรของฉัน':scope==='report'?'รายงานประจำเดือน':(view==='calendar'?'ตารางเวียนสาขา':'ตารางเวียน (มุมมองตาราง)');

  return (
    <div style={{minHeight:'100vh',background:'#f4f5f8',fontFamily:'IBM Plex Sans Thai, sans-serif',color:'#2b2f3a'}}>
      <TopNav scope={scope} onScope={setScope} monthDate={month} onMonthMove={moveMonth}
        onLogout={onLogout} headerBg={NAV_THEMES[t.navTheme]||NAV_THEMES['ทอง']}
        badge={badge} onBell={()=>setNotifPanel(true)} isAdmin={isAdmin} onAdmin={()=>setAdminPanel(true)}
        currentStaff={me}/>

      <main style={{maxWidth:1280,margin:'0 auto',padding:'22px 22px 60px'}}>
        <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:16,flexWrap:'wrap',marginBottom:18}}>
          <div style={{minWidth:0}}>
            <h1 style={{fontSize:25,fontWeight:700,fontFamily:'Anuphan',margin:0,lineHeight:1.2,whiteSpace:'nowrap'}}>{title}</h1>
            <div style={{fontSize:13.5,color:'#8a91a0',marginTop:2}}>{MONTHS_TH[m]} {thaiYear(y)}</div>
          </div>
          {scope==='all' && <Segmented value={view} onChange={setView} accent="#b8901f" options={[{value:'calendar',label:'ปฏิทิน',icon:'🗓'},{value:'matrix',label:'ตาราง',icon:'▦'}]}/>}
        </div>

        {scope!=='report' && <div style={{display:'flex',gap:12,marginBottom:16,flexWrap:'wrap'}}>
          <StatCard theme="dark" value={STAFF.length} label="พนักงานทั้งหมด"/>
          <StatCard theme="b1" value={g.b1.length} label={`${BRANCHES.b1.name} · ${todayInMonth?'วันนี้':'วันที่ 1'}`}/>
          <StatCard theme="b2" value={g.b2.length} label={`${BRANCHES.b2.name} · ${todayInMonth?'วันนี้':'วันที่ 1'}`}/>
          <StatCard theme="off" value={g.off.length} label={`หยุด · ${todayInMonth?'วันนี้':'วันที่ 1'}`}/>
        </div>}

        {scope!=='report' && <div style={{marginBottom:16}}><Legend/></div>}

        {scope==='mine'
          ? <MineView monthDate={month} store={store} currentUserId={currentUserId}
              onLeaveDay={setLeaveDay} onOTDay={setOtDay} onAdvanceLeave={()=>setAdvLeave(true)} onTransferDay={setTransferDay}/>
          : scope==='report'
            ? <ReportView monthDate={month} store={store}/>
            : (view==='calendar'
                ? <CalendarAll monthDate={month} store={store} currentUserId={currentUserId} isAdmin={isAdmin}
                    onDayClick={setDayModal} onChipClick={(s,d)=>setSendReq({staff:s,date:d})} onEditDay={setEditDay}/>
                : <MatrixView monthDate={month} store={store} onProfileClick={setProfileStaff} isAdmin={isAdmin} onEditDay={setEditDay}/>)}
      </main>

      <TweaksPanel>
        <TweakSection label="ชื่อสาขา"/>
        <TweakText label="สาขา 1" value={t.branch1} onChange={v=>setTweak('branch1',v)}/>
        <TweakText label="สาขา 2" value={t.branch2} onChange={v=>setTweak('branch2',v)}/>
        <TweakSection label="ธีมหัวแอป"/>
        <TweakRadio label="สี" value={t.navTheme} options={['ทอง','ม่วง','เขียว','กรมท่า']} onChange={v=>setTweak('navTheme',v)}/>
      </TweaksPanel>

      {dayModal   && <DayModal date={dayModal} store={store} isAdmin={isAdmin} onEdit={d=>{setDayModal(null);setEditDay(d);}} onClose={()=>setDayModal(null)} onProfileClick={s=>{setDayModal(null);setProfileStaff(s);}}/>}
      {profileStaff && <StaffProfileModal staff={profileStaff} monthDate={month} store={store} onClose={()=>setProfileStaff(null)}/>}
      {editDay    && <EditDayModal date={editDay} store={store} setOverride={setOverride} clearOverride={clearOverride} onClose={()=>setEditDay(null)}/>}
      {adminPanel && <AdminPanel store={store} updateLeave={updateLeave} updateOT={updateOT} updateTransfer={updateTransfer} onEditDay={d=>{setAdminPanel(false);setEditDay(d);}} onClose={()=>setAdminPanel(false)}/>}
      {notifPanel && <NotificationPanel currentUserId={currentUserId} isAdmin={isAdmin} store={store}
        updateRequest={updateRequest} cancelRequest={cancelRequest} pendingRequestsFor={pendingRequestsFor}
        pendingLeavesAdmin={pendingLeavesAdmin} pendingOTsAdmin={pendingOTsAdmin}
        updateLeave={updateLeave} updateOT={updateOT} updateTransfer={updateTransfer}
        pendingTransfersAdmin={pendingTransfersAdmin} onClose={()=>setNotifPanel(false)}/>}
      {sendReq    && <SendRequestModal targetStaff={sendReq.staff} targetDate={sendReq.date} store={store}
        currentUserId={currentUserId} sendRequest={sendRequest} onClose={()=>setSendReq(null)}/>}
      {leaveDay   && <EmergencyLeaveModal date={leaveDay} staffId={currentUserId} store={store}
        requestLeave={requestLeave} cancelLeave={cancelLeave} onClose={()=>setLeaveDay(null)}/>}
      {advLeave   && <AdvanceLeaveModal staffId={currentUserId}
        targetMonth={new Date(month.getFullYear(), month.getMonth()+(TODAY.getDate()<=28?1:2), 1)}
        store={store} requestAdvanceLeaves={requestAdvanceLeaves} onClose={()=>setAdvLeave(false)}/>}
      {otDay      && <OTRequestModal date={otDay} staffId={currentUserId} store={store}
        requestOT={requestOT} cancelOT={cancelOT} onClose={()=>setOtDay(null)}/>}
      {transferDay && <TransferModal date={transferDay} staffId={currentUserId} store={store}
        requestTransfer={requestTransfer} cancelTransfer={cancelTransfer} onClose={()=>setTransferDay(null)}/>}
    </div>
  );
}

// ---- StaffProfileModal ----
function StaffProfileModal({ staff, monthDate, store, onClose }){
  const ov=store.overrides, lv=store.leaves;
  const y=monthDate.getFullYear(), m=monthDate.getMonth();
  const days=daysOfMonth(y,m);
  const cnt={b1:0,b2:0,off:0,m:0,a:0};
  days.forEach(d=>{
    const a=assignmentsForDate(d,ov,lv)[staff.id];
    if(a==='off')cnt.off++; else{cnt[a.b]++;cnt[a.s]++;}
  });
  return (
    <Overlay onClose={onClose}>
      <ModalBox title="โปรไฟล์พนักงาน" onClose={onClose}>
        <div style={{display:'flex',flexDirection:'column',alignItems:'center',gap:10,paddingBottom:16,borderBottom:'1px solid #eef0f4',marginBottom:16}}>
          <div style={{width:80,height:80,borderRadius:'50%',
            background:staffColor(staff,'tint'),color:staffColor(staff,'text'),
            display:'flex',alignItems:'center',justifyContent:'center',
            fontWeight:800,fontSize:36,fontFamily:'Anuphan',
            border:`3px solid ${staffColor(staff,'solid')}`,
            boxShadow:`0 6px 20px ${staffColor(staff,'solid')}44`}}>
            {staff.nick.slice(0,1)}
          </div>
          <div style={{textAlign:'center'}}>
            <div style={{fontSize:21,fontWeight:700,fontFamily:'Anuphan',marginBottom:6}}>{staff.full}</div>
            <span style={{
              background:staff.type==='full'?'#e6f5f2':'#ececfb',
              color:staff.type==='full'?'#0e6b60':'#46449e',
              borderRadius:999,padding:'4px 14px',fontSize:12.5,fontWeight:700}}>
              {TYPES[staff.type].label}
            </span>
          </div>
        </div>

        <div style={{marginBottom:14}}>
          <div style={{fontSize:12,fontWeight:700,color:'#9aa1b0',marginBottom:7}}>วันหยุดประจำสัปดาห์</div>
          <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
            {staff.offDays.map(d=>(
              <span key={d} style={{background:DOW_COLORS[d]+'22',color:DOW_COLORS[d],
                borderRadius:999,padding:'5px 13px',fontSize:12.5,fontWeight:700}}>
                วัน{WEEKDAYS_TH[d]}
              </span>
            ))}
          </div>
        </div>

        <div style={{fontSize:12,fontWeight:700,color:'#9aa1b0',marginBottom:8}}>
          สรุปเดือน {MONTHS_TH[m]} {thaiYear(y)}
        </div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8,marginBottom:8}}>
          {['b1','b2','off'].map(k=>{
            const b=BRANCHES[k];
            return (
              <div key={k} style={{background:b.tint,borderRadius:10,padding:'10px 8px',textAlign:'center'}}>
                <div style={{fontSize:26,fontWeight:800,fontFamily:'Anuphan',color:b.solid,lineHeight:1}}>{cnt[k]}</div>
                <div style={{fontSize:11,color:b.text,marginTop:4,fontWeight:600}}>{b.name}</div>
              </div>
            );
          })}
        </div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:8}}>
          {['m','a'].map(k=>{
            const s=SHIFTS[k];
            return (
              <div key={k} style={{background:s.tint,borderRadius:10,padding:'9px 8px',textAlign:'center'}}>
                <div style={{fontSize:22,fontWeight:800,fontFamily:'Anuphan',color:s.solid,lineHeight:1}}>{cnt[k]}</div>
                <div style={{fontSize:11,color:s.text,marginTop:3,fontWeight:600}}>{s.label} · {s.time}</div>
              </div>
            );
          })}
        </div>
      </ModalBox>
    </Overlay>
  );
}

class ErrorBoundary extends React.Component {
  constructor(props){ super(props); this.state={err:null}; }
  static getDerivedStateFromError(e){ return {err:e}; }
  componentDidCatch(e){ console.error('App error:',e); }
  render(){
    if(this.state.err) return (
      <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',
        background:'#f4f5f8',fontFamily:'IBM Plex Sans Thai,sans-serif',padding:24}}>
        <div style={{background:'#fff',borderRadius:16,padding:'28px 24px',maxWidth:360,textAlign:'center',boxShadow:'0 8px 32px rgba(0,0,0,.1)'}}>
          <div style={{fontSize:36,marginBottom:12}}>⚠️</div>
          <div style={{fontWeight:700,fontSize:16,marginBottom:8,color:'#2b2f3a'}}>เกิดข้อผิดพลาด</div>
          <div style={{fontSize:13,color:'#9aa1b0',marginBottom:18}}>กรุณาลองใหม่อีกครั้ง</div>
          <button onClick={()=>this.setState({err:null})}
            style={{border:'none',borderRadius:10,padding:'10px 24px',background:'linear-gradient(100deg,#9a7616,#c19a2a)',
              color:'#fff',fontWeight:700,fontSize:14,cursor:'pointer',fontFamily:'inherit'}}>ลองใหม่</button>
        </div>
      </div>
    );
    return this.props.children;
  }
}

function App(){
  const [userId,setUserId]=uSApp(null);
  if(!userId) return <Login onLogin={setUserId}/>;
  return (
    <ErrorBoundary>
      <StoreProvider currentUserId={userId}>
        <AppInner currentUserId={userId} onLogout={()=>setUserId(null)}/>
      </StoreProvider>
    </ErrorBoundary>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
