/* kata-spa.jsx — hash router that hosts all pages in one document.
   Page components register themselves on window.__KATA_PAGES.
   Routes: "#base" or "#base/param" (param drives detail pages).
   entry.active may be a string or a fn(param) → nav key to highlight. */

/* 兼容旧 .html 链接 + 新 #hash 链接 */
const FILE2KEY = Object.assign(
  Object.fromEntries(KSITE.nav.map((n) => [n.href, n.key])),
  {
    '咔哒Lab 首页.html': 'home',
    '社区活动.html': 'community',
    '企业活动.html': 'enterprise',
    'Demo广场.html': 'demo',
    '社区发帖.html': 'post',
    '#home': 'home',
    '#community': 'community',
    '#enterprise': 'enterprise',
    '#demo': 'demo',
    '#post': 'post',
  }
);

function KataSPA() {
  const parse = () => {
    const raw = decodeURIComponent(location.hash.replace(/^#\/?/, ''));
    const [base, ...rest] = raw.split('/');
    const known = window.__KATA_PAGES && window.__KATA_PAGES[base];
    return { base: known ? base : 'home', param: rest.join('/') || null };
  };
  const [route, setRoute] = React.useState(parse);
  const [t, setTweak] = useKataTheme();

  React.useEffect(() => {
    const onHash = () => { setRoute(parse()); window.scrollTo({ top: 0, left: 0 }); };
    window.addEventListener('hashchange', onHash);
    const onClick = (e) => {
      const a = e.target.closest && e.target.closest('a');
      if (!a) return;
      const href = a.getAttribute('href');
      if (!href) return;
      if (href === '#') { e.preventDefault(); return; }

      // 统一拦截 SPA 路由：#xxx 或旧 .html 文件名
      let key = FILE2KEY[href];
      if (!key && href.startsWith('#')) {
        const base = href.slice(1).split('/')[0];
        if (window.__KATA_PAGES && window.__KATA_PAGES[base]) key = href.slice(1);
      }
      if (key != null) {
        e.preventDefault();
        const next = key.startsWith('#') ? key : ('#' + key);
        const cur = '#' + location.hash.replace(/^#\/?/, '');
        if (cur === next || location.hash === next) window.scrollTo({ top: 0, left: 0 });
        else location.hash = next.startsWith('#') ? next : ('#' + next);
      }
    };
    document.addEventListener('click', onClick);
    return () => { window.removeEventListener('hashchange', onHash); document.removeEventListener('click', onClick); };
  }, []);

  const entry = window.__KATA_PAGES[route.base] || window.__KATA_PAGES.home;
  const Comp = entry.Comp;
  const active = typeof entry.active === 'function' ? entry.active(route.param) : entry.active;

  /* 全站共享极光 + 星座连线：路由切换不卸载，保证所有子页面都有科技感连线 */
  return (
    <KataCtx.Provider value={{ t, setTweak }}>
      <div className="ka" data-page={active || 'none'}>
        <AuroraBG />
        <TechNetBG />
        <KataNav active={active} dark={t.dark} onToggle={() => setTweak('dark', !t.dark)} />
        <div className="ka-content" key={route.base + (route.param || '')}>
          <Comp routeParam={route.param} kt={t} />
        </div>
        <KataFooter />
        <KataTweaks t={t} setTweak={setTweak} />
      </div>
    </KataCtx.Provider>
  );
}

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