/**
 * The app-mode state machine (UI-SPEC: EXPLORE→SEARCH→PREVIEW→GUIDANCE→
 * ARRIVED, with PLACE between SEARCH and PREVIEW for the place card).
 * Plain discriminated unions + a pure reducer — see reducer.ts. No xstate.
 */
import type {
  BridgeError,
  GuidanceEvent,
  JourneyStats,
  Route,
  RouteProfile,
  RouteResult,
  SelectedPlace,
} from "../types";

export type AppMode =
  | "EXPLORE"
  | "SEARCH"
  | "PLACE"
  | "PREVIEW"
  | "GUIDANCE"
  | "ARRIVED";

export type ExploreModeState = { mode: "EXPLORE" };

export type SearchModeState = { mode: "SEARCH"; query: string };

export type PlaceModeState = { mode: "PLACE"; place: SelectedPlace };

export type PreviewModeState = {
  mode: "PREVIEW";
  place: SelectedPlace;
  profile: RouteProfile;
  routeResult?: RouteResult;
  activeRouteIndex: number;
  isComputing: boolean;
  error?: BridgeError;
};

export type GuidanceModeState = {
  mode: "GUIDANCE";
  place: SelectedPlace;
  profile: RouteProfile;
  routeIndex: number;
  /** The route selected on S6 (Preview), carried through so S7 can draw
   * the full route line + true consumed-route dimming against real
   * geometry instead of a breadcrumb-only fallback. Absent only if S6's
   * routeResult somehow didn't contain the selected index (shouldn't
   * happen — START only fires with a resolved routeResult). */
  route?: Route;
  guidance?: GuidanceEvent;
  isRerouting: boolean;
  isFollowingCamera: boolean;
  isOverview: boolean;
};

export type ArrivedModeState = {
  mode: "ARRIVED";
  place: SelectedPlace;
  journey: JourneyStats;
};

export type AppModeState =
  | ExploreModeState
  | SearchModeState
  | PlaceModeState
  | PreviewModeState
  | GuidanceModeState
  | ArrivedModeState;

export const initialAppModeState: AppModeState = { mode: "EXPLORE" };

/* ---------- events ---------- */

export type AppModeEvent =
  | { type: "OPEN_SEARCH" }
  | { type: "UPDATE_SEARCH_QUERY"; query: string }
  | { type: "CANCEL_SEARCH" }
  | { type: "SELECT_PLACE"; place: SelectedPlace }
  /** Context-sensitive back: PLACE→EXPLORE, PREVIEW→PLACE. */
  | { type: "BACK" }
  | { type: "REQUEST_DIRECTIONS"; profile?: RouteProfile }
  | { type: "CHANGE_PROFILE"; profile: RouteProfile }
  | { type: "ROUTE_COMPUTING" }
  | { type: "ROUTE_COMPUTED"; result: RouteResult; activeRouteIndex?: number }
  | { type: "ROUTE_FAILED"; error: BridgeError }
  | { type: "SELECT_ROUTE"; routeIndex: number }
  | { type: "START" }
  | { type: "GUIDANCE_UPDATE"; event: GuidanceEvent }
  /** A mid-drive reroute finished: swap in the freshly computed route. */
  | { type: "REROUTE_COMPLETE"; route: Route }
  | { type: "SET_FOLLOWING_CAMERA"; following: boolean }
  | { type: "TOGGLE_OVERVIEW" }
  | { type: "ARRIVE"; journey: JourneyStats }
  | { type: "EXIT" }
  | { type: "DONE" }
  | { type: "RESET" };
