// ============================================================
// WASIED · Router - hash-based, simple, fast
// ============================================================

const RouterContext = React.createContext({ path: '/', params: {}, query: {} });

function parseHash() {
  const raw = (window.location.hash || '#/').slice(1);
  const [pathRaw, queryRaw] = raw.split('?');
  const path = pathRaw || '/';
  const query = {};
  (queryRaw || '').split('&').filter(Boolean).forEach(p => {
    const [k, v] = p.split('=');
    query[decodeURIComponent(k)] = decodeURIComponent(v || '');
  });
  return { path, query };
}

function useRouter() {
  return React.useContext(RouterContext);
}

function RouterProvider({ children }) {
  const [route, setRoute] = React.useState(parseHash());
  React.useEffect(() => {
    const onChange = () => {
      const next = parseHash();
      setRoute(next);
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  return <RouterContext.Provider value={route}>{children}</RouterContext.Provider>;
}

function navigate(to, opts = {}) {
  if (typeof to !== 'string') return;
  const href = to.startsWith('#') ? to : '#' + (to.startsWith('/') ? to : '/' + to);
  if (opts.replace) {
    window.location.replace(href);
  } else {
    window.location.hash = href.slice(1);
  }
}

function Link({ to, children, style, className, onClick, activeStyle, exactActive, ...rest }) {
  const { path } = useRouter();
  const href = to.startsWith('#') ? to : '#' + (to.startsWith('/') ? to : '/' + to);
  const targetPath = href.slice(1).split('?')[0];
  const isActive = exactActive ? path === targetPath : (targetPath !== '/' && path.startsWith(targetPath));
  return (
    <a href={href} onClick={onClick} className={className}
      style={{ color: 'inherit', textDecoration: 'none', cursor: 'pointer', ...style, ...(isActive ? activeStyle : {}) }}
      {...rest}>
      {children}
    </a>
  );
}

// Pattern matcher: '/u/:handle' against '/u/zapz' → { handle: 'zapz' }
function matchRoute(pattern, path) {
  const pParts = pattern.split('/').filter(Boolean);
  const aParts = path.split('/').filter(Boolean);
  if (pParts.length !== aParts.length) return null;
  const params = {};
  for (let i = 0; i < pParts.length; i++) {
    if (pParts[i].startsWith(':')) {
      params[pParts[i].slice(1)] = decodeURIComponent(aParts[i]);
    } else if (pParts[i] !== aParts[i]) {
      return null;
    }
  }
  return params;
}

Object.assign(window, { RouterContext, RouterProvider, useRouter, navigate, Link, matchRoute });
