/* app.jsx — top-level router + state */

function App() {
  const [authed, setAuthed] = React.useState(false);
  const [user, setUser] = React.useState({ name: 'Linh Tran', email: 'linh.tran@boxme.tech' });
  const [route, setRoute] = React.useState('/');
  const [country, setCountry] = React.useState('VN');
  const [warehouseId, setWarehouseId] = React.useState('wh-vn-hn-01');
  const [role, setRole] = React.useState('PLANNER');
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);
  const [sidebarDrawerOpen, setSidebarDrawerOpen] = React.useState(false);
  const [cmdkOpen, setCmdkOpen] = React.useState(false);
  const [toasts, setToasts] = React.useState([]);
  const { isMobile, isTablet, isCompact } = useViewport();

  function navigate(r) { setRoute(r); setSidebarDrawerOpen(false); }
  function addToast(t) {
    const id = Math.random().toString(36).slice(2, 8);
    setToasts(prev => [...prev, { ...t, id }]);
    setTimeout(() => setToasts(prev => prev.filter(x => x.id !== id)), 4500);
  }
  function dismissToast(id) { setToasts(prev => prev.filter(x => x.id !== id)); }

  // Auto-collapse sidebar on tablet
  React.useEffect(() => {
    if (isTablet && !sidebarCollapsed) setSidebarCollapsed(true);
  }, [isTablet]);

  // Cmd+K
  React.useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault(); setCmdkOpen(o => !o);
      } else if (e.key === 'Escape' && cmdkOpen) {
        setCmdkOpen(false);
      }
    }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [cmdkOpen]);

  // sync warehouse selection when country changes
  React.useEffect(() => {
    const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId);
    if (wh && wh.countryCode !== country) {
      const first = WFP.WAREHOUSES.find(w => w.countryCode === country);
      if (first) setWarehouseId(first.id);
    }
  }, [country]);

  if (!authed) {
    return <LoginScreen onLogin={(u) => { setUser(u); setAuthed(true); setRoute('/'); }}/>;
  }

  let screenEl, screenLabel;
  if (route === '/')                           { screenEl = <HomeScreen role={role} country={country} warehouseId={warehouseId} navigate={navigate}/>; screenLabel = 'Trang chủ'; }
  else if (route === '/admin/warehouses')      { screenEl = <WarehousesScreen country={country}/>; screenLabel = 'Quản trị · Kho'; }
  else if (route === '/admin/staff')           { screenEl = <StaffScreen warehouseId={warehouseId}/>; screenLabel = 'Quản trị · Nhân sự'; }
  else if (route === '/admin/config')          { screenEl = <ConfigScreen/>; screenLabel = 'Quản trị · Tham số'; }
  else if (route === '/admin/config/dinhmuc')  { screenEl = <NormsScreen warehouseId={warehouseId}/>; screenLabel = 'Cấu hình · Định mức'; }
  else if (route === '/admin/config/thamso')   { screenEl = <ParamsScreen/>; screenLabel = 'Cấu hình · Tham số'; }
  else if (route === '/admin/history-import')  { screenEl = <HistoryImportScreen addToast={addToast} navigate={navigate}/>; screenLabel = 'Quản trị · Dữ liệu lịch sử'; }
  else if (route === '/planner/forecast')              { screenEl = <ForecastOverviewScreen  country={country} warehouseId={warehouseId} navigate={navigate}/>; screenLabel = 'Dự báo · Tổng quan'; }
  else if (route === '/planner/forecast/customer')     { screenEl = <ForecastCustomerScreen  warehouseId={warehouseId} navigate={navigate}/>; screenLabel = 'Dự báo · Khách hàng'; }
  else if (route === '/planner/forecast/warehouse')    { screenEl = <ForecastWarehouseScreen warehouseId={warehouseId} navigate={navigate}/>; screenLabel = 'Dự báo · Kho'; }
  else if (route === '/planner/forecast/review' || route === '/planner/forecast-input') { screenEl = <ForecastInputScreen warehouseId={warehouseId} navigate={navigate}/>; screenLabel = 'Dự báo · Phê duyệt'; }
  else if (route === '/planner/shift-plan')    { screenEl = <ShiftPlanScreen warehouseId={warehouseId} navigate={navigate} addToast={addToast}/>; screenLabel = 'Kế hoạch ca'; }
  else if (route === '/planner/hiring')        { screenEl = <HiringScreen warehouseId={warehouseId} addToast={addToast}/>; screenLabel = 'Tuyển dụng'; }
  else if (route === '/planner/override-import'){ screenEl = <OverrideImportScreen addToast={addToast} navigate={navigate}/>; screenLabel = 'Gửi điều chỉnh'; }
  else { screenEl = <Empty icon="info" title="Không tìm thấy trang" subtitle={'Không có màn hình cho ' + route} action={<Button variant="primary" onClick={() => setRoute('/')}>Về trang chủ</Button>}/>; screenLabel = '404'; }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', minHeight: 0 }}
         data-screen-label={screenLabel}>
      <TopNav
        country={country} setCountry={setCountry}
        warehouseId={warehouseId} setWarehouseId={setWarehouseId}
        role={role} setRole={setRole}
        openCmdK={() => setCmdkOpen(true)}
        openSidebar={() => setSidebarDrawerOpen(true)}
        user={user} onLogout={() => { setAuthed(false); setRoute('/'); }}
      />
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {!isMobile && (
          <Sidebar route={route} navigate={navigate}
            collapsed={sidebarCollapsed}
            onToggle={() => setSidebarCollapsed(v => !v)}
            role={role}/>
        )}
        {isMobile && (
          <Sidebar route={route} navigate={navigate}
            collapsed={false} onToggle={() => {}}
            role={role} drawerOpen={sidebarDrawerOpen}
            onCloseDrawer={() => setSidebarDrawerOpen(false)} isMobile/>
        )}
        <main style={{ flex: 1, minWidth: 0, background: 'var(--bx-page-bg)', display: 'flex', flexDirection: 'column' }}>
          {screenEl}
        </main>
      </div>
      <CmdK open={cmdkOpen} onClose={() => setCmdkOpen(false)} navigate={navigate}/>
      <Toaster toasts={toasts} dismiss={dismissToast}/>
    </div>
  );
}

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