/* =========================================================================
   app.jsx — Login (real API auth), App shell, router
   ========================================================================= */
const { useState:aS, useEffect:aE } = React;

const ROLE_LABEL = { admin:'ผู้ดูแลระบบ', accountant:'ฝ่ายบัญชี', manager:'ผู้จัดการ', staff:'เจ้าหน้าที่' };
const roleLabel = (r)=> ROLE_LABEL[r] || 'ผู้ใช้งาน';

/* ====================== LOGIN ====================== */
function Login({ onLogin }){
  const [user,setUser] = aS('');
  const [pass,setPass] = aS('');
  const [err,setErr] = aS('');
  const [busy,setBusy] = aS(false);
  const submit = async (e)=>{
    e.preventDefault();
    setBusy(true); setErr('');
    const r = await API.post('auth/login', { username:user.trim(), password:pass });
    if(r.ok && r.data.ok){ API.setToken(r.data.token); onLogin(r.data.user); }
    else { setErr((r.data && r.data.msg) || 'เข้าสู่ระบบไม่สำเร็จ'); setBusy(false); }
  };
  return (
    <div className="min-h-screen flex items-stretch">
      {/* left visual */}
      <div className="hidden lg:flex flex-col justify-between w-[44%] relative overflow-hidden bg-panel grain p-12">
        <div className="absolute -right-20 -top-20 w-80 h-80 rounded-full bg-brand/10 blur-3xl"></div>
        <div className="absolute bottom-0 left-0 right-0 h-3 hazard-strip opacity-60"></div>
        <div className="flex items-center gap-3 relative">
          <div className="w-12 h-12 rounded-xl bg-brand text-ink flex items-center justify-center"><Icon name="helmet" size={26}/></div>
          <div>
            <div className="font-display font-extrabold text-xl leading-none">ค่าแรง</div>
            <div className="text-xs text-haze">Workforce & Payroll</div>
          </div>
        </div>
        <div className="relative">
          <h1 className="font-display font-extrabold text-4xl leading-tight">ระบบบริหาร<br/>แรงงานก่อสร้าง<br/><span className="text-brand">และเงินเดือน</span></h1>
          <p className="text-haze mt-4 max-w-sm">ลงเวลาเข้างานรายไซต์ คำนวณค่าแรง OT ปันส่วนต้นทุนตามหน้างาน และออกสลิปเงินเดือนพร้อมพิมพ์</p>
          <div className="flex gap-2 mt-6">
            {['ลงเวลารายไซต์','คำนวณ OT','ออกสลิป A5'].map(t=>(
              <span key={t} className="text-xs font-semibold px-3 py-1.5 rounded-md bg-white/5 border border-line text-haze">{t}</span>
            ))}
          </div>
        </div>
        <div className="text-xs text-haze relative">© 2569 หจก.เจริญธุรกิจการก่อสร้าง</div>
      </div>

      {/* right form */}
      <div className="flex-1 flex items-center justify-center p-6">
        <div className="w-full max-w-sm">
          <div className="lg:hidden flex items-center gap-3 mb-8">
            <div className="w-11 h-11 rounded-xl bg-brand text-ink flex items-center justify-center"><Icon name="helmet" size={24}/></div>
            <div className="font-display font-extrabold text-xl">ค่าแรง</div>
          </div>
          <h2 className="font-display font-extrabold text-2xl">เข้าสู่ระบบ</h2>
          <p className="text-haze text-sm mt-1 mb-7">กรอกข้อมูลเพื่อเข้าใช้งานระบบจัดการ</p>
          <form onSubmit={submit} className="space-y-4">
            <Field label="ชื่อผู้ใช้">
              <div className="relative">
                <div className="absolute left-3 top-1/2 -translate-y-1/2 text-haze"><Icon name="user" size={18}/></div>
                <input value={user} onChange={e=>{setUser(e.target.value);setErr('');}} className={`${inputCls} pl-10`} placeholder="ชื่อผู้ใช้" autoFocus/>
              </div>
            </Field>
            <Field label="รหัสผ่าน">
              <div className="relative">
                <div className="absolute left-3 top-1/2 -translate-y-1/2 text-haze"><Icon name="lock" size={18}/></div>
                <input type="password" value={pass} onChange={e=>{setPass(e.target.value);setErr('');}} className={`${inputCls} pl-10`} placeholder="••••"/>
              </div>
            </Field>
            {err && <div className="text-sm text-bad flex items-center gap-2"><Icon name="warn" size={15}/>{err}</div>}
            <Button type="submit" size="lg" className="w-full" iconR={busy?undefined:"arrow"} disabled={!user || !pass || busy}>
              {busy ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ'}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
}

/* ====================== SHELL ====================== */
const NAV = [
  { key:'dashboard',  label:'ภาพรวม',       icon:'dashboard' },
  { key:'attendance', label:'ลงเวลาเข้างาน', icon:'check' },
  { key:'payroll',    label:'สรุปเงินเดือน', icon:'payroll' },
  { key:'payslip',    label:'ออกสลิป',      icon:'slip' },
  { key:'workstats',  label:'สถิติงาน',      icon:'chart' },
  { key:'workers',    label:'คนงาน',        icon:'workers' },
  { key:'sites',      label:'ไซต์งาน',      icon:'site' },
  { key:'settings',   label:'ตั้งค่า',       icon:'settings' },
];

function Sidebar({ route, go, user, onLogout, mobileOpen, setMobileOpen }){
  return (
    <>
      {mobileOpen && <div className="fixed inset-0 bg-black/60 z-30 lg:hidden" onClick={()=>setMobileOpen(false)}></div>}
      <aside className={`fixed lg:sticky top-0 z-40 h-screen w-[248px] shrink-0 bg-panel border-r border-line flex flex-col transition-transform lg:translate-x-0 ${mobileOpen?'translate-x-0':'-translate-x-full'}`}>
        <div className="flex items-center gap-3 px-5 h-16 border-b border-line">
          <div className="w-10 h-10 rounded-xl bg-brand text-ink flex items-center justify-center"><Icon name="helmet" size={22}/></div>
          <div>
            <div className="font-display font-extrabold text-lg leading-none">ค่าแรง</div>
            <div className="text-[10px] text-haze tracking-wide">PAYROLL SYSTEM</div>
          </div>
        </div>
        <nav className="flex-1 overflow-y-auto p-3 space-y-1">
          {NAV.map(n=>(
            <button key={n.key} onClick={()=>{ go(n.key); setMobileOpen(false); }}
              className={`tap w-full flex items-center gap-3 px-3.5 py-2.5 rounded-lg text-[15px] font-medium ${route===n.key?'bg-brand text-ink font-semibold':'text-haze hover:text-chalk hover:bg-white/5'}`}>
              <Icon name={n.icon} size={20}/>{n.label}
            </button>
          ))}
        </nav>
        <div className="p-3 border-t border-line">
          <div className="flex items-center gap-3 px-2 py-2">
            <div className="w-9 h-9 rounded-lg bg-raised border border-line flex items-center justify-center text-brand"><Icon name="user" size={18}/></div>
            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium truncate">{user.name}</div>
              <div className="text-xs text-haze">{roleLabel(user.role)}</div>
            </div>
            <button onClick={onLogout} className="tap p-2 text-haze hover:text-bad rounded-md hover:bg-white/5" title="ออกจากระบบ"><Icon name="logout" size={18}/></button>
          </div>
        </div>
      </aside>
    </>
  );
}

/* ====================== SHELL (authenticated) ====================== */
function Shell({ user, onLogout }){
  const [route,setRoute] = aS('dashboard');
  const [mobileOpen,setMobileOpen] = aS(false);
  const [slip,setSlip] = aS(null);
  const [profileId,setProfileId] = aS(null);
  const [detailSiteId,setDetailSiteId] = aS(null);
  const [editWorker,setEditWorker] = aS(null);

  const go = (r)=> setRoute(r);
  const openProfile = (id)=>{ setProfileId(id); setRoute('profile'); };
  const openSite = (id)=>{ setDetailSiteId(id); setRoute('sitedetail'); };
  const openSlipFor = (workerId, period)=>{ setSlip({workerId, period}); setRoute('payslip'); };

  const titles = { ...Object.fromEntries(NAV.map(n=>[n.key,n.label])), profile:'ประวัติคนงาน', sitedetail:'รายละเอียดไซต์' };
  const activeNav = route==='profile'?'workers':route==='sitedetail'?'sites':route;

  return (
    <div className="flex min-h-screen">
      <Sidebar route={activeNav} go={go} user={user} onLogout={onLogout} mobileOpen={mobileOpen} setMobileOpen={setMobileOpen}/>
      <div className="flex-1 min-w-0 flex flex-col">
        {/* mobile topbar */}
        <header className="lg:hidden sticky top-0 z-20 h-14 bg-panel/95 backdrop-blur border-b border-line flex items-center gap-3 px-4">
          <button onClick={()=>setMobileOpen(true)} className="tap p-2 -ml-2 text-haze"><Icon name="menu"/></button>
          <div className="font-display font-bold">{titles[route]}</div>
        </header>
        <main className="flex-1 p-4 sm:p-6 lg:p-8 max-w-[1280px] w-full mx-auto">
          {route==='dashboard'  && <Dashboard go={go}/>}
          {route==='attendance' && <Attendance/>}
          {route==='payroll'    && <Payroll go={go} setSlip={setSlip}/>}
          {route==='payslip'    && <Payslip slip={slip} setSlip={setSlip}/>}
          {route==='workstats'  && <WorkStats/>}
          {route==='workers'    && <Workers openProfile={openProfile}/>}
          {route==='sites'      && <Sites openSite={openSite}/>}
          {route==='settings'   && <Settings/>}
          {route==='profile'    && <WorkerProfile workerId={profileId} back={()=>setRoute('workers')} onEdit={(w)=>{ setEditWorker(w); }} openSlip={openSlipFor}/>}
          {route==='sitedetail' && <SiteDetail siteId={detailSiteId} back={()=>setRoute('sites')}/>}
        </main>
      </div>
      <WorkerModal open={!!editWorker} onClose={()=>setEditWorker(null)} initial={editWorker}/>
    </div>
  );
}

/* ====================== ROOT (auth gate) ====================== */
function App(){
  const [user,setUser] = aS(null);
  const [authReady,setAuthReady] = aS(false);

  aE(()=>{
    let alive = true;
    (async ()=>{
      if(API.token){
        const r = await API.get('auth/me');
        if(alive){ if(r.ok && r.data.user) setUser(r.data.user); else API.setToken(null); }
      }
      if(alive) setAuthReady(true);
    })();
    return ()=>{ alive=false; };
  }, []);

  const login = (u)=> setUser(u);
  const logout = async ()=>{ try{ await API.post('auth/logout'); }catch(e){} API.setToken(null); setUser(null); };

  if(!authReady) return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="w-6 h-6 border-2 border-brand border-t-transparent rounded-full animate-spin"></div>
    </div>
  );
  if(!user) return <Login onLogin={login}/>;

  return (
    <StoreProvider onAuthExpired={logout}>
      <Shell user={user} onLogout={logout}/>
    </StoreProvider>
  );
}

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