/**
 * H5 路由配置
 * 所有 /pms/* 路径的 H5 端路由
 */
import { Route } from 'react-router-dom';
import H5Layout from './layout';
import H5Login from './pages/login';
import H5Home from './pages/home';
import H5Devices from './pages/devices';
import H5DeviceDetail from './pages/device-detail';
import H5CompartmentDetail from './pages/compartment-detail';
import H5Me from './pages/me';

/**
 * H5 路由片段，需挂载到 /pms 路径下：
 *
 * /pms/login              - 登录
 * /pms                    - 首页（需认证，底部导航）
 * /pms/devices            - 设备列表（需认证，底部导航）
 * /pms/devices/:id        - 设备详情（需认证，底部导航）
 * /pms/compartments/:id   - 通道详情（需认证，全屏）
 * /pms/me                 - 我的（需认证，底部导航）
 */
export const h5Routes = (
  <>
    {/* 登录页 - 无底部导航 */}
    <Route path="/pms/login" element={<H5Login />} />

    {/* H5 主布局（含底部导航 + 认证守卫） */}
    <Route path="/pms" element={<H5Layout />}>
      <Route index element={<H5Home />} />
      <Route path="devices" element={<H5Devices />} />
      <Route path="devices/:id" element={<H5DeviceDetail />} />
      <Route path="me" element={<H5Me />} />
    </Route>

    {/* 通道详情 - 全屏页面，直接挂载 */}
    <Route path="/pms/compartments/:id" element={<H5CompartmentDetail />} />

    {/* 扫码入口: /pms/{abstract_id} 重定向到设备详情
       ponytail: 扫码进入后需先查 abstract_id 对应的 cabinet id */}
    <Route path="/pms/:abstractId" element={<ScanRedirect />} />
  </>
);

/** 扫码入口处理：通过 abstract_id 查设备详情 */
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { h5Api } from './api';
import { Loading } from './components';

function ScanRedirect() {
  const { abstractId } = useParams<{ abstractId: string }>();
  const navigate = useNavigate();
  const [error, setError] = useState('');

  useEffect(() => {
    // 排除已知路径
    if (!abstractId ||
      ['login', 'devices', 'me', 'compartments'].includes(abstractId)) {
      return;
    }

    h5Api.getCabinetByAbstractId(abstractId)
      .then((res) => navigate(`/pms/devices/${res.data.id}`, { replace: true }))
      .catch(() => setError('未找到该设备'));
  }, [abstractId, navigate]);

  if (error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-3 bg-white">
        <span className="text-4xl">🔍</span>
        <p className="text-sm text-gray-500">{error}</p>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-white">
      <Loading />
    </div>
  );
}
