// Top-level router using the History API so URLs are clean:
//   /            → home
//   /claim       → claim form
//   /track       → tracking lookup
//   /track/S3D-X → tracking result for that ref
//
// Server serves index.html for unknown paths, so any of these reload cleanly.

function parsePath() {
  // Back-compat: if someone lands on /#/claim (old hash-style), redirect them.
  const h = window.location.hash || '';
  if (h.startsWith('#/')) {
    const clean = '/' + h.slice(2).replace(/^\/+/, '');
    window.history.replaceState({}, '', clean || '/');
  }

  const parts = window.location.pathname.split('/').filter(Boolean);
  if (!parts.length) return { screen: 'home', ref: null };
  if (parts[0] === 'claim') return { screen: 'claim', ref: null };
  if (parts[0] === 'track') return { screen: 'track', ref: parts[1] ? decodeURIComponent(parts[1]) : null };
  return { screen: 'home', ref: null };
}

function setPath(screen, ref) {
  let url = '/';
  if (screen === 'claim') url = '/claim';
  else if (screen === 'track') url = ref ? `/track/${encodeURIComponent(ref)}` : '/track';
  if (window.location.pathname !== url) {
    window.history.pushState({}, '', url);
  }
}

function App() {
  const [route, setRoute] = React.useState(parsePath());

  React.useEffect(() => {
    const onChange = () => setRoute(parsePath());
    window.addEventListener('popstate', onChange);
    return () => window.removeEventListener('popstate', onChange);
  }, []);

  const go = (screen, ref) => {
    setPath(screen, ref);
    setRoute({ screen, ref: ref || null });
    window.scrollTo(0, 0);
  };

  if (route.screen === 'home') {
    return <HomeScreen
      onClaim={() => go('claim')}
      onTrack={() => go('track')}
    />;
  }
  if (route.screen === 'track') {
    return <TrackingScreen
      initialRef={route.ref}
      onBack={() => go('home')}
    />;
  }
  return <ClaimScreen
    onBack={() => go('home')}
    onSubmitted={(_ref) => { /* success card stays; user taps Track */ }}
    onNavigateTrack={(ref) => go('track', ref)}
  />;
}

Object.assign(window, { App });
