// Main App

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "blue",
  "density": "comfortable"
}/*EDITMODE-END*/;

const THEMES = {
  blue: {
    name: 'น้ำเงิน',
    palette: ['#eff6ff','#dbeafe','#bfdbfe','#93c5fd','#60a5fa','#3b82f6','#2563eb','#1d4ed8','#1e40af','#1e3a8a']
  },
  teal: {
    name: 'เขียวมรกต',
    palette: ['#f0fdfa','#ccfbf1','#99f6e4','#5eead4','#2dd4bf','#14b8a6','#0d9488','#0f766e','#115e59','#134e4a']
  },
  indigo: {
    name: 'อินดิโก้',
    palette: ['#eef2ff','#e0e7ff','#c7d2fe','#a5b4fc','#818cf8','#6366f1','#4f46e5','#4338ca','#3730a3','#312e81']
  },
  slate: {
    name: 'เทาเข้ม',
    palette: ['#f8fafc','#f1f5f9','#e2e8f0','#cbd5e1','#94a3b8','#64748b','#475569','#334155','#1e293b','#0f172a']
  },
};

const ThemeStyles = ({ theme }) => {
  const p = THEMES[theme]?.palette || THEMES.blue.palette;
  return (
    <style>{`
      :root {
        --brand-50:  ${p[0]};
        --brand-100: ${p[1]};
        --brand-200: ${p[2]};
        --brand-300: ${p[3]};
        --brand-400: ${p[4]};
        --brand-500: ${p[5]};
        --brand-600: ${p[6]};
        --brand-700: ${p[7]};
        --brand-800: ${p[8]};
        --brand-900: ${p[9]};
        --vac:    ${p[6]};
        --vac-bg: ${p[0]};
      }
    `}</style>
  );
};

const TitleMap = {
  dashboard: { title: 'แดชบอร์ด', sub: 'ภาพรวมการเข้างานและคำขอ' },
  leaves:    { title: 'การลา',     sub: 'พักร้อน / ลากิจ / ลาป่วย' },
  'swap-ot': { title: 'OT & สลับวันหยุด', sub: 'จัดการ OT และสลับวันหยุด' },
  employees: { title: 'พนักงาน',   sub: 'ข้อมูลพนักงานและโควต้า' },
  settings:  { title: 'ตั้งค่า',    sub: 'ตั้งค่าระบบและกฎ' },
  reports:   { title: 'รายงาน',     sub: 'สรุปและ Export' },
  'my-leaves': { title: 'การลาของฉัน', sub: 'ประวัติและขอลาใหม่' },
  'my-swap':   { title: 'OT & สลับวันหยุด', sub: 'ขอ OT หรือสลับวันหยุดของคุณ' },
  'my-quota':  { title: 'โควต้าของฉัน', sub: 'วันลาคงเหลือและประวัติ' },
};

const BootSplash = ({ msg }) => (
  <div style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'100vh', flexDirection:'column', gap:14, color:'#64748b' }}>
    <div style={{ width:36, height:36, borderRadius:8, background:'#1d4ed8', color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700 }}>WC</div>
    <div style={{ fontSize:13 }}>{msg || 'กำลังโหลดข้อมูล…'}</div>
  </div>
);

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const today = new Date(2026, 4, 22);

  const [booting, setBooting] = React.useState(true);
  const [bootError, setBootError] = React.useState(null);
  const [currentUser, setCurrentUser] = React.useState(null);
  const [liveData, setLiveData] = React.useState(window.APP_DATA);
  const [role, setRole] = React.useState('admin');
  const [page, setPage] = React.useState('dashboard');
  const [view, setView] = React.useState({ year: today.getFullYear(), month: today.getMonth() });
  const [selected, setSelected] = React.useState(today);
  const [modal, setModal] = React.useState(null);

  const applyBootstrap = (b) => {
    const data = {
      employees: b.employees || [],
      holidays: b.holidays || [],
      leaves: b.leaves || [],
      swapRequests: b.swapRequests || [],
      otRequests: b.otRequests || [],
      specialOffs: b.specialOffs || [],
      settings: { ...window.APP_DATA.settings, ...(b.settings || {}) },
      otPlans: b.otPlans || {},
      notifications: [],
    };
    data.notifications = window.deriveNotifications(data);
    window.APP_DATA = data;
    setLiveData(data);
    if (b.currentUser) setCurrentUser(b.currentUser);
  };

  const refresh = React.useCallback(async () => {
    const b = await window.API.bootstrap();
    applyBootstrap(b);
  }, []);

  React.useEffect(() => {
    (async () => {
      try {
        const b = await window.API.bootstrap();
        applyBootstrap(b);
        if (b.currentUser) setRole(b.currentUser.appRole);
      } catch (e) {
        if (e.status !== 401) setBootError(e.message);
      } finally {
        setBooting(false);
      }
    })();
  }, []);

  const handleLoggedIn = async (user) => {
    setCurrentUser(user);
    setRole(user.appRole);
    setPage('dashboard');
    await refresh();
  };

  const handleLogout = async () => {
    try { await window.API.logout(); } catch {}
    setCurrentUser(null);
  };

  const openModal = (m) => setModal(m);
  const closeModal = () => setModal(null);
  const onAction = (action, date) => {
    if (action === 'leave') openModal({ type: 'leave-form', date });
    if (action === 'ot') openModal({ type: 'ot-form', date });
    if (action === 'swap') openModal({ type: 'swap-form', date });
    if (action === 'special') openModal({ type: 'special-form', date });
    if (action === 'ot-plan') openModal({ type: 'ot-plan', date });
  };

  React.useEffect(() => {
    if (role === 'admin' && !['dashboard','leaves','swap-ot','employees','reports','settings'].includes(page)) {
      setPage('dashboard');
    }
    if (role === 'employee' && !['dashboard','my-leaves','my-swap','my-quota'].includes(page)) {
      setPage('dashboard');
    }
  }, [role]);

  const setSettings = async (next) => {
    const value = typeof next === 'function' ? next(liveData.settings) : next;
    setLiveData(d => ({ ...d, settings: value }));
    try { await window.API.putSettings(value); }
    catch (e) { console.warn('settings save failed:', e.message); }
  };

  if (booting) return (<><ThemeStyles theme={tweaks.theme}/><BootSplash msg="กำลังเชื่อมต่อระบบ…"/></>);
  if (bootError) return (<><ThemeStyles theme={tweaks.theme}/><BootSplash msg={`เชื่อมต่อไม่สำเร็จ: ${bootError}`}/></>);

  if (!currentUser) {
    return (
      <>
        <ThemeStyles theme={tweaks.theme}/>
        <Login onLogin={handleLoggedIn} data={liveData}/>
        <TweaksUI tweaks={tweaks} setTweak={setTweak}/>
      </>
    );
  }

  const t = TitleMap[page] || TitleMap.dashboard;
  const effectiveRole = currentUser.appRole === 'admin' ? role : 'employee';

  return (
    <>
      <ThemeStyles theme={tweaks.theme}/>
      <div className="app" data-density={tweaks.density}>
        <Sidebar role={effectiveRole} setRole={currentUser.appRole === 'admin' ? setRole : null} page={page} setPage={setPage} currentUser={currentUser} onLogout={handleLogout} onChangePassword={() => openModal({ type: 'change-password' })}/>
        <div className="main">
          <Topbar title={t.title} subtitle={t.sub}/>
          <div className="page">
            {page === 'dashboard' && (
              <Dashboard data={liveData} today={today} view={view} setView={setView}
                selected={selected} setSelected={setSelected} onAction={onAction}
                role={effectiveRole} currentUser={currentUser}/>
            )}
            {page === 'leaves' && <LeavesPage data={liveData} openModal={openModal} role={effectiveRole} currentUser={currentUser} refresh={refresh}/>}
            {page === 'my-leaves' && <LeavesPage data={liveData} openModal={openModal} role="employee" currentUser={currentUser} refresh={refresh}/>}
            {page === 'swap-ot' && <SwapOtPage data={liveData} openModal={openModal} role={effectiveRole} currentUser={currentUser} refresh={refresh}/>}
            {page === 'my-swap' && <SwapOtPage data={liveData} openModal={openModal} role="employee" currentUser={currentUser} refresh={refresh}/>}
            {page === 'employees' && <EmployeesPage data={liveData} refresh={refresh}/>}
            {page === 'reports' && <ReportsPage data={liveData}/>}
            {page === 'settings' && <SettingsPage data={liveData} settings={liveData.settings} setSettings={setSettings}/>}
            {page === 'my-quota' && <MyQuotaPage data={liveData} currentUser={currentUser} openModal={openModal}/>}
          </div>
        </div>
      </div>

      {modal?.type === 'leave-form' && <LeaveModal onClose={closeModal} currentUser={currentUser} data={liveData} refresh={refresh}/>}
      {modal?.type === 'swap-form' && <SwapModal onClose={closeModal} currentUser={currentUser} data={liveData} refresh={refresh}/>}
      {modal?.type === 'ot-form' && <OtModal onClose={closeModal} currentUser={currentUser} data={liveData} refresh={refresh}/>}
      {modal?.type === 'special-form' && <SpecialOffModal onClose={closeModal} currentUser={currentUser} data={liveData} refresh={refresh}/>}
      {modal?.type === 'ot-plan' && <OtPlanModal onClose={closeModal} date={modal.date} data={liveData} settings={liveData.settings} setSettings={setSettings} refresh={refresh}/>}
      {modal?.type === 'change-password' && <ChangePasswordModal onClose={closeModal}/>}
      {modal?.type === 'reset-password' && <ResetPasswordModal emp={modal.emp} onClose={closeModal}/>}

      <TweaksUI tweaks={tweaks} setTweak={setTweak}/>
    </>
  );
};

const TweaksUI = ({ tweaks, setTweak }) => {
  return (
    <TweaksPanel>
      <TweakSection label="ธีมและสี" />
      <TweakSelect
        label="ธีมสีหลัก"
        value={tweaks.theme}
        onChange={v => setTweak('theme', v)}
        options={[
          { value: 'blue', label: '🔵 น้ำเงิน (Blue)' },
          { value: 'teal', label: '🟢 เขียวมรกต (Teal)' },
          { value: 'indigo', label: '🟣 อินดิโก้ (Indigo)' },
          { value: 'slate', label: '⚫ เทาเข้ม (Slate)' },
        ]}
      />
    </TweaksPanel>
  );
};

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