

const TPSRouteContext = React.createContext({ path: '/', navigate: () => {} });

function TPSRouterProvider({ children }) {
  const [path, setPath] = React.useState(() => window.location.pathname || '/');

  React.useEffect(() => {
    const onPop = () => setPath(window.location.pathname || '/');
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const navigate = React.useCallback((to) => {
    const cur = window.location.pathname + window.location.hash;
    if (to === cur || to === window.location.pathname) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    window.history.pushState({}, '', to);
    setPath(window.location.pathname);
    if (window.location.hash) {
      requestAnimationFrame(() => {
        setTimeout(() => {
          const el = document.querySelector(window.location.hash);
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 60);
      });
    } else {
      window.scrollTo(0, 0);
    }
  }, []);

  React.useEffect(() => {
    const handler = (e) => {
      const a = e.target.closest('a[href]');
      if (!a) return;
      if (a.target === '_blank' || e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;
      const href = a.getAttribute('href');
      if (!href || !href.startsWith('#')) return;
      if (window.location.pathname !== '/') {
        e.preventDefault();
        navigate('/' + href);
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [navigate]);

  return (
    <TPSRouteContext.Provider value={{ path, navigate }}>
      {children}
    </TPSRouteContext.Provider>
  );
}

const useRoute = () => React.useContext(TPSRouteContext);

function TPSLink({ to, children, onClick, ...rest }) {
  const { navigate } = useRoute();
  return (
    <a
      href={to}
      onClick={(e) => {
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;
        e.preventDefault();
        onClick?.(e);
        navigate(to);
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

window.TPSRouterProvider = TPSRouterProvider;
window.useRoute = useRoute;
window.TPSLink = TPSLink;
