// ===== app.jsx =====
// Hash-based router. URLs:
//   #/                          → home
//   #/upload                    → upload
//   #/order/:id?token=xxx       → order （token 用于持久化凭证）
//   #/report/:id?token=xxx      → report
//   #/mgmt-7k2q9w8m             → admin (内部入口，勿外传)
const { useState: useSApp, useEffect: useEApp, useMemo: useMApp } = React;

function parseHash() {
  const raw = window.location.hash.replace(/^#\/?/, '');
  // 拆出 query 部分（?token=xxx&...），剩余按 / 切路径
  const qIdx = raw.indexOf('?');
  const pathPart = qIdx === -1 ? raw : raw.slice(0, qIdx);
  const queryPart = qIdx === -1 ? '' : raw.slice(qIdx + 1);
  const query = {};
  if (queryPart) {
    for (const pair of queryPart.split('&')) {
      if (!pair) continue;
      const [k, v = ''] = pair.split('=');
      try { query[decodeURIComponent(k)] = decodeURIComponent(v); } catch (_) { query[k] = v; }
    }
  }
  const [path, ...rest] = pathPart.split('/');
  if (!path)              return { route: 'home',   params: { ...query } };
  if (path === 'upload')  return { route: 'upload', params: { ...query } };
  if (path === 'mgmt-7k2q9w8m') return { route: 'admin', params: { ...query } };
  if (path === 'order')   return { route: 'order',  params: { id: rest[0] || '20260524-1085', ...query } };
  if (path === 'report')  return { route: 'report', params: { id: rest[0] || 'r-1085',        ...query } };
  if (path === 'trial-report' || path === 'trial') return { route: 'trial', params: { ...query } };
  if (path === 'lookup')  return { route: 'lookup', params: { ...query } };
  return { route: 'home', params: { ...query } };
}

function App() {
  const [state, setState] = useSApp(parseHash());

  useEApp(() => {
    const onHash = () => setState(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const navigate = (route, params = {}) => {
    let hash = '#/';
    const q = params.token ? `?token=${encodeURIComponent(params.token)}` : '';
    if (route === 'home')   hash = '#/' + (params.hash ? '#' + params.hash : '');
    if (route === 'upload') hash = '#/upload';
    if (route === 'admin')  hash = '#/mgmt-7k2q9w8m';
    if (route === 'order')  hash = `#/order/${params.id || ''}${q}`;
    if (route === 'report') hash = `#/report/${params.id || ''}${q}`;
    if (route === 'trial')  hash = '#/trial-report';
    if (route === 'lookup') hash = '#/lookup';
    window.location.hash = hash;
    // hashchange will fire; but in case of identical hash, force:
    setState({ route, params });
    setTimeout(() => {
      if (params.hash) {
        const el = document.getElementById(params.hash);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      } else {
        window.scrollTo({ top: 0, behavior: 'instant' });
      }
    }, 20);
  };

  // Render
  const showChrome = state.route !== 'admin';
  return (
    <div data-screen-label={`${state.route}`}>
      {showChrome && <Navbar route={state.route} navigate={navigate} />}
      <main>
        {state.route === 'home'   && <HomePage   navigate={navigate} />}
        {state.route === 'upload' && <UploadPage navigate={navigate} />}
        {state.route === 'order'  && <OrderPage  navigate={navigate} params={state.params} />}
        {state.route === 'report' && <ReportPage navigate={navigate} params={state.params} />}
        {state.route === 'trial'  && <TrialReportPage navigate={navigate} />}
        {state.route === 'lookup' && <LookupPage navigate={navigate} />}
        {state.route === 'admin'  && <AdminPage  navigate={navigate} />}
      </main>
      {showChrome && state.route === 'home' && <Footer navigate={navigate} />}
      {showChrome && state.route !== 'home' && <SlimFooter navigate={navigate} />}
      <LiveFeed />
      {showChrome && <MobileStickyCTA navigate={navigate} route={state.route} />}
    </div>
  );
}

function SlimFooter({ navigate }) {
  return (
    <div className="border-t border-ink-200 bg-white">
      <div className="max-w-[1200px] mx-auto px-6 lg:px-8 h-14 flex items-center justify-between text-[12px] text-ink-500 flex-wrap gap-2">
        <div className="flex items-center gap-4 flex-wrap">
          <span className="flex items-center gap-1.5"><I.ShieldCheck size={13} className="text-ok-600" />文件 24h 内自动删除</span>
          <span className="flex items-center gap-1.5 text-ok-600 font-medium"><I.Check size={12} />30 分钟内出报告，超时全额退款</span>
        </div>
        <div className="flex items-center gap-4">
          <a onClick={() => navigate('lookup')} className="hover:text-navy-900 cursor-pointer">找回订单</a>
          <a onClick={() => navigate('home', { hash: 'faq' })} className="hover:text-navy-900 cursor-pointer">常见问题</a>
          <a href="mailto:support@mojian.ai" className="hover:text-navy-900">support@mojian.ai</a>
        </div>
      </div>
    </div>
  );
}

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