// router.jsx — minimal hash router for the production site.
// Hash routes (e.g. #/about) keep static hosting trivial: no nginx rewrites needed.

const ROUTES = [
  ['/',                                      'Главная'],
  ['/services',                              'Услуги'],
  ['/services/crypto-recovery',              'Возврат криптоактивов'],
  ['/services/forex-disputes',               'Споры с Forex-брокерами'],
  ['/services/investment-fraud',             'Инвестиционное мошенничество'],
  ['/services/broker-withdrawal-disputes',   'Споры по выводу средств'],
  ['/services/b2b-disputes',                 'B2B финансовые споры'],
  ['/services/chargeback',                   'Chargeback / платёжные споры'],
  ['/crypto',                                'Крипто'],
  ['/forex',                                 'Forex'],
  ['/business',                              'Бизнес'],
  ['/about',                                 'О компании'],
  ['/specialists',                           'Специалисты'],
  ['/specialists/how-recovery-works',        'Как работает возврат'],
  ['/specialists/evidence',                  'Какие доказательства нужны'],
  ['/specialists/broker-scam-signs',         'Признаки брокерского мошенничества'],
  ['/faq',                                   'FAQ'],
  ['/contact',                               'Контакты'],
  ['/privacy',                               'Конфиденциальность'],
  ['/terms',                                 'Условия'],
  ['/security',                              'Безопасность данных'],
  ['/docs',                                  'Документация'],
  ['/docs/company',                          'Информация о компании'],
  ['/docs/kvk',                              'KVK регистрация'],
  ['/docs/complaints',                       'Процедура жалоб'],
  ['/docs/case-review-policy',               'Политика разбора дела'],
  ['/docs/risk-disclosure',                  'Раскрытие рисков'],
  ['/docs/client-checklist',                 'Чеклист документов'],
];

const ROUTE_LABELS = Object.fromEntries(ROUTES);

function parseHash() {
  const raw = (window.location.hash || '').replace(/^#/, '');
  const path = raw.split('?')[0] || '/';
  return path === '' ? '/' : path;
}

function navigate(to, opts = {}) {
  if (!to) return;
  const next = to.startsWith('#') ? to : '#' + to;
  if (window.location.hash === next) return;
  if (opts.replace) window.history.replaceState(null, '', next);
  else window.location.hash = next;
  // Scroll to top on navigation; production pages assume this.
  window.scrollTo({ top: 0, behavior: 'auto' });
}

// Disable browser scroll restoration so back/forward and intra-site
// navigation never resurrect a stale scrollY from a different page.
if (typeof window !== 'undefined' && 'scrollRestoration' in window.history) {
  window.history.scrollRestoration = 'manual';
}

function useRoute() {
  const [path, setPath] = React.useState(parseHash());
  React.useEffect(() => {
    const onChange = () => {
      setPath(parseHash());
      // Always realign to the top on route changes. navigate() already
      // does this, but plain <a href="#/..."> links (mobile nav sheet,
      // footer, related-section cards) bypass navigate() — without this
      // the new page would inherit the previous page's scroll position
      // and appear to land mid-section.
      window.scrollTo({ top: 0, behavior: 'auto' });
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  // document.title is set by site/seo.js (per-route + per-language).
  return path;
}

function Link({ to, children, style, onClick, className, ariaLabel, ...rest }) {
  const handle = (e) => {
    e.preventDefault();
    if (onClick) onClick(e);
    navigate(to);
  };
  return (
    <a href={'#' + to} onClick={handle} style={style} className={className} aria-label={ariaLabel} {...rest}>
      {children}
    </a>
  );
}

Object.assign(window, { ROUTES, ROUTE_LABELS, parseHash, navigate, useRoute, Link });
