/**
 * DemoDriver — a tap-free, deterministic walkthrough of the core journey,
 * for client-demo recordings and kiosk playback.
 *
 * Gated on `EXPO_PUBLIC_MAPMAP_DEMO=1`; a no-op otherwise. It drives the
 * SAME state-machine actions the real UI dispatches (nothing is faked at a
 * layer below the app) and, in mock mode, the SDK's mock provider auto-plays
 * the guidance session through to arrival. Mounted as a sibling of AppShell,
 * so it can see both the territory and app-mode contexts.
 */
import { useEffect, useRef } from "react";
import { useAppMode } from "../state/appMode";
import { useTerritory } from "../state/territory";
import type { SelectedPlace } from "../state/types";

const ENABLED = process.env.EXPO_PUBLIC_MAPMAP_DEMO === "1";

/** Demo destination — Manchester, because the hosted engine currently pins
 * every origin to Slade Lane, Manchester (FINDINGS F1): with a Manchester
 * destination the returned route is real and road-following end-to-end. */
const DESTINATION: SelectedPlace = {
  name: "Manchester Town Hall",
  address: "Albert Square, Manchester M2 5DB",
  position: { latitude: 53.4794, longitude: -2.2453 },
  distanceMeters: 4200,
};

// Cinematic dwell times (ms) so each screen is legible on the recording.
const DWELL_EXPLORE = 2600;
const DWELL_PLACE = 2600;
const DWELL_PREVIEW = 5200;
const REPLAY_AFTER_ARRIVED = 4000;

export function DemoDriver(): null {
  const { state, dispatch } = useAppMode();
  const { ready, hasMap } = useTerritory();
  const stage = useRef(0);

  // The app enters on online maps by default (no territory download), so
  // the driver never touches the territory context — flipping to offline
  // would blank the map while the mock has no installed territory.

  // Walk explore → place → preview → guidance, reacting to mode.
  useEffect(() => {
    if (!ENABLED || !ready || !hasMap) return;
    let t: ReturnType<typeof setTimeout> | undefined;

    if (state.mode === "EXPLORE" && stage.current <= 1) {
      stage.current = 2;
      t = setTimeout(
        () => dispatch({ type: "SELECT_PLACE", place: DESTINATION }),
        DWELL_EXPLORE
      );
    } else if (state.mode === "PLACE" && stage.current === 2) {
      stage.current = 3;
      t = setTimeout(() => dispatch({ type: "REQUEST_DIRECTIONS" }), DWELL_PLACE);
    } else if (
      state.mode === "PREVIEW" &&
      stage.current === 3 &&
      state.routeResult &&
      !state.isComputing
    ) {
      stage.current = 4;
      t = setTimeout(() => dispatch({ type: "START" }), DWELL_PREVIEW);
    } else if (state.mode === "ARRIVED" && stage.current === 4) {
      // Loop the journey so the recording/kiosk runs continuously.
      stage.current = 5;
      t = setTimeout(() => {
        stage.current = 1;
        dispatch({ type: "EXIT" });
      }, REPLAY_AFTER_ARRIVED);
    }

    return () => {
      if (t) clearTimeout(t);
    };
  }, [state, ready, hasMap, dispatch]);

  return null;
}
