/* ===== app.jsx — Router + App ===== */
(function () {
  const {
    StoreProvider, useStore, useRoute, navigate, matchRoute,
    Sidebar, TopBar, CmdK, MobileFrame, MobileBottomNav, MobileTopBar, ToastHost,
    cls, Icon,
  } = window;

  /* ---------- Route resolver ---------- */
  function resolveRoute(path) {
    if (path === '/' || path === '') return { name: 'dashboard' };
    if (path === '/login') return { name: 'login' };
    if (path === '/alerts' || path.startsWith('/alerts?')) return { name: 'alerts' };
    if (path === '/suppliers') return { name: 'suppliers' };
    if (path === '/suppliers/new') return { name: 'supplier_new' };
    let m = matchRoute(path.split('?')[0], '/suppliers/:id'); if (m) return { name: 'supplier_detail', params: m };
    if (path === '/customers') return { name: 'customers' };
    if (path === '/customers/new') return { name: 'customer_new' };
    m = matchRoute(path.split('?')[0], '/customers/:id'); if (m) return { name: 'customer_detail', params: m };
    if (path === '/reagents/products') return { name: 'reagent_products' };
    if (path.startsWith('/reagents/batches/new')) return { name: 'reagent_batch_new' };
    if (path === '/reagents/batches' || path.startsWith('/reagents/batches?')) return { name: 'reagent_batches' };
    m = matchRoute(path.split('?')[0], '/reagents/batches/:id'); if (m) return { name: 'reagent_batch_detail', params: m };
    if (path.startsWith('/reagents/outflow/new')) return { name: 'reagent_outflow_new' };
    if (path === '/devices/products') return { name: 'device_products' };
    if (path === '/devices/units/new') return { name: 'device_unit_new' };
    if (path === '/devices/units' || path.startsWith('/devices/units?')) return { name: 'device_units' };
    m = matchRoute(path.split('?')[0], '/devices/units/:id'); if (m) return { name: 'device_unit_detail', params: m };
    if (path.startsWith('/devices/transfer/new')) return { name: 'device_transfer_new' };
    if (path === '/settings/users') return { name: 'settings_users' };
    if (path === '/settings/thresholds') return { name: 'settings_thr' };
    return { name: 'notfound' };
  }

  /* ---------- Renders page body for a route ---------- */
  function Page({ name, params, mobile }) {
    switch (name) {
      case 'dashboard':        return <window.Dashboard mobile={mobile} />;
      case 'alerts':           return <window.AlertsPage mobile={mobile} />;
      case 'suppliers':        return <window.SuppliersPage mobile={mobile} />;
      case 'supplier_new':     return <window.SupplierNew mobile={mobile} />;
      case 'supplier_detail':  return <window.SupplierDetail id={params.id} mobile={mobile} />;
      case 'customers':        return <window.CustomersPage mobile={mobile} />;
      case 'customer_new':     return <window.CustomerNew mobile={mobile} />;
      case 'customer_detail':  return <window.CustomerDetail id={params.id} mobile={mobile} />;
      case 'reagent_products': return <window.ReagentProducts mobile={mobile} />;
      case 'reagent_batches':  return <window.ReagentBatches mobile={mobile} />;
      case 'reagent_batch_detail': return <window.ReagentBatchDetail id={params.id} mobile={mobile} />;
      case 'reagent_batch_new':return <window.ReagentBatchNew mobile={mobile} />;
      case 'reagent_outflow_new': return <window.ReagentOutflowNew mobile={mobile} />;
      case 'device_products':  return <window.DeviceProducts mobile={mobile} />;
      case 'device_units':     return <window.DeviceUnits mobile={mobile} />;
      case 'device_unit_detail': return <window.DeviceUnitDetail id={params.id} mobile={mobile} />;
      case 'device_unit_new':  return <window.DeviceUnitNew mobile={mobile} />;
      case 'device_transfer_new': return <window.DeviceTransferNew mobile={mobile} />;
      case 'settings_users':   return <window.SettingsUsers mobile={mobile} />;
      case 'settings_thr':     return <window.SettingsThresholds mobile={mobile} />;
      default:
        return (
          <div className="p-12 text-center">
            <window.EmptyState title="页面未找到" hint={`路由 ${window.location.hash} 未匹配`}
              action={<window.Button size="sm" onClick={() => navigate('#/')}>回到仪表盘</window.Button>} />
          </div>
        );
    }
  }

  /* ---------- Get title for route ---------- */
  function getCrumbs(name, params) {
    const store = useStore();
    switch (name) {
      case 'dashboard': return [{ label: '仪表盘' }];
      case 'alerts': return [{ label: '全部报警' }];
      case 'suppliers': return [{ label: '供货商' }];
      case 'supplier_new': return [{ label: '供货商', to: '#/suppliers' }, { label: '新建' }];
      case 'supplier_detail': {
        const r = store.suppliers.find(x => x.id === params.id);
        return [{ label: '供货商', to: '#/suppliers' }, { label: r?.short || '?' }];
      }
      case 'customers': return [{ label: '客户' }];
      case 'customer_new': return [{ label: '客户', to: '#/customers' }, { label: '新建' }];
      case 'customer_detail': {
        const r = store.customers.find(x => x.id === params.id);
        return [{ label: '客户', to: '#/customers' }, { label: r?.short || '?' }];
      }
      case 'reagent_products': return [{ label: '试剂', to: '#/reagents/batches' }, { label: '产品目录' }];
      case 'reagent_batches':  return [{ label: '试剂' }, { label: '批次' }];
      case 'reagent_batch_detail': {
        const b = store.reagent_batches.find(x => x.id === params.id);
        return [{ label: '试剂', to: '#/reagents/batches' }, { label: '批次', to: '#/reagents/batches' }, { label: b?.lot || '?' }];
      }
      case 'reagent_batch_new':   return [{ label: '试剂', to: '#/reagents/batches' }, { label: '新建批次' }];
      case 'reagent_outflow_new': return [{ label: '试剂', to: '#/reagents/batches' }, { label: '取货' }];
      case 'device_products':     return [{ label: '设备' }, { label: '型号目录' }];
      case 'device_units':        return [{ label: '设备' }, { label: '列表' }];
      case 'device_unit_detail': {
        const u = store.device_units.find(x => x.id === params.id);
        return [{ label: '设备', to: '#/devices/units' }, { label: u?.sn || '(SN 缺失)' }];
      }
      case 'device_unit_new':     return [{ label: '设备', to: '#/devices/units' }, { label: '登记新设备' }];
      case 'device_transfer_new': return [{ label: '设备', to: '#/devices/units' }, { label: '新转移' }];
      case 'settings_users':      return [{ label: '系统' }, { label: '用户管理' }];
      case 'settings_thr':        return [{ label: '系统' }, { label: '低库存阈值' }];
      default: return [{ label: '页面未找到' }];
    }
  }

  /* ---------- Desktop shell ---------- */
  function DesktopShell({ children, route }) {
    const { sidebarCollapsed, set } = useStore();
    const crumbs = getCrumbs(route.name, route.params);
    return (
      <div className="flex h-full bg-ink-50">
        <Sidebar collapsed={sidebarCollapsed} onCollapse={(v) => set({ sidebarCollapsed: v })} />
        <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
          <TopBar breadcrumbs={crumbs} />
          <main className="flex-1 overflow-y-auto">
            {children}
          </main>
        </div>
      </div>
    );
  }

  /* ---------- Mobile shell ---------- */
  function MobileShellInner({ children, route }) {
    const crumbs = getCrumbs(route.name, route.params);
    const title = crumbs[crumbs.length - 1]?.label || '';
    const back = crumbs.length > 1;
    const isFullBleed = route.name === 'login';

    if (isFullBleed) return children;

    return (
      <>
        <MobileTopBar title={title} back={back} />
        <div className="flex-1 overflow-y-auto pb-16">{children}</div>
        <MobileBottomNav />
      </>
    );
  }

  /* ---------- Floating device toggle (always visible) ---------- */
  function FloatingDeviceToggle() {
    const { device, set } = useStore();
    return (
      <div className="fixed top-3 right-3 z-[80] flex items-center gap-1 bg-white/90 backdrop-blur ring-1 ring-ink-200 rounded-lg shadow-card p-0.5">
        {[
          { id: 'desktop', label: 'Desktop' },
          { id: 'mobile',  label: 'Mobile' },
          { id: 'split',   label: 'Both' },
        ].map((opt) => (
          <button key={opt.id} onClick={() => set({ device: opt.id })}
            className={cls(
              'h-7 px-2.5 text-xs rounded-md transition-colors',
              device === opt.id ? 'bg-ink-900 text-white' : 'text-ink-600 hover:bg-ink-100'
            )}>{opt.label}</button>
        ))}
      </div>
    );
  }

  /* ---------- App ---------- */
  function App() {
    const route = useRoute();
    const r = resolveRoute(route.path);
    const { device } = useStore();

    // /login always full-bleed, no shell
    if (r.name === 'login') {
      return (
        <div className="h-full">
          <window.LoginPage mobile={device === 'mobile'} />
        </div>
      );
    }

    if (device === 'mobile') {
      return (
        <div className="h-full flex items-center justify-center dot-bg overflow-auto relative">
          <FloatingDeviceToggle />
          <div className="py-6">
            <MobileFrame>
              <MobileShellInner route={r}>
                <Page name={r.name} params={r.params} mobile={true} />
              </MobileShellInner>
            </MobileFrame>
            <div className="text-center mt-4 text-[11px] text-ink-500 font-mono">375 × 812 · iPhone 13 mini · 移动端预览</div>
          </div>
        </div>
      );
    }

    if (device === 'split') {
      return (
        <div className="h-full grid grid-cols-[1fr_400px] gap-0 relative">
          <FloatingDeviceToggle />
          <div className="border-r border-ink-200 overflow-hidden h-full">
            <DesktopShell route={r}>
              <Page name={r.name} params={r.params} mobile={false} />
            </DesktopShell>
          </div>
          <div className="bg-ink-100 flex items-center justify-center overflow-auto py-4">
            <div>
              <MobileFrame>
                <MobileShellInner route={r}>
                  <Page name={r.name} params={r.params} mobile={true} />
                </MobileShellInner>
              </MobileFrame>
              <div className="text-center mt-3 text-[11px] text-ink-500 font-mono">375 · mobile</div>
            </div>
          </div>
        </div>
      );
    }

    return (
      <DesktopShell route={r}>
        <Page name={r.name} params={r.params} mobile={false} />
      </DesktopShell>
    );
  }

  /* ---------- Root ---------- */
  function Root() {
    return (
      <StoreProvider>
        <App />
        <CmdK />
        <ToastHost />
      </StoreProvider>
    );
  }

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