"use client";

import Image from "next/image";
import type { CSSProperties, DragEvent as ReactDragEvent, KeyboardEvent as ReactKeyboardEvent } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { HaloEyebrow } from "@/components/brand/HaloEyebrow";
import {
  HaloMobileButton,
  HaloMobileCaptureLaunchSheet,
  HaloMobileDetailCompletion,
  HaloMobileScannerViewport,
  HaloMobileShell,
  HaloMobileVinVerificationControl,
  HaloMobileVehicleHandoffSummary
} from "@/components/mobile/HaloMobile";
import { HaloIcon } from "@/components/ui/HaloIcon";
import type { HaloIconName } from "@/components/ui/HaloIcon";
import { HaloPhoneFrame } from "@/components/ui/HaloPhoneFrame";
import { PrismSelect } from "@/components/prism/PrismSelect";
import type { PrismSelectOption } from "@/components/prism/PrismSelect";
import styles from "./halo-flows-section.module.css";

type FlowStageId = "arrival" | "mechanical" | "detail" | "imagery" | "listed";
type NotificationState = "not-required" | "pending" | "sent" | "opened";
type SlaState = "On track" | "At risk" | "Met";

type FlowVehicle = {
  stockNumber: string;
  vin: string;
  year: number;
  make: string;
  model: string;
  trim?: string;
  currentStage: FlowStageId;
  responsibleTeam: string;
  timeInStage: string;
  notificationState: NotificationState;
  needsAttention?: boolean;
  status: string;
  slaState: SlaState;
  event?: string;
  assignedTo?: string;
  contactState?: string;
  unreadReply?: boolean;
  blockerTitle?: string;
  observations?: string[];
};

const workflowStages: Array<{ id: FlowStageId; label: string; team: string }> = [
  {
    id: "arrival",
    label: "New Arrival",
    team: "Lot team"
  },
  {
    id: "mechanical",
    label: "Mechanical",
    team: "Service"
  },
  {
    id: "detail",
    label: "Detail",
    team: "Detail"
  },
  {
    id: "imagery",
    label: "Final Imagery",
    team: "Merchandising"
  },
  {
    id: "listed",
    label: "Listed",
    team: "Manager"
  }
] as const;

type TimelineEventType = "automation" | "stage" | "sms-out" | "sms-in" | "blocker" | "note";

type TimelineEvent = {
  id: string;
  stockNumber: string;
  type: TimelineEventType;
  title: string;
  body: string;
  meta: string;
  source: "Halo" | "Manual" | "SMS";
  unread?: boolean;
  actionable?: "blocker";
};

type StageOverride = {
  stage: FlowStageId;
  previousStage?: FlowStageId;
  status: string;
  responsibleTeam: string;
  timeInStage: string;
  notificationState: NotificationState;
  slaState: SlaState;
  event: string;
  assignedTo?: string;
  needsAttention?: boolean;
  contactState?: string;
  unreadReply?: boolean;
  blockerTitle?: string;
};

type ConfirmationMode = "next" | "change" | null;
type BoardWorkflowPhase = "resting" | "active" | "moving" | "settled";
type FlowScreen =
  | "scanVin"
  | "detailComplete"
  | "operationsUpdate"
  | "smsReceived"
  | "browserOpens"
  | "guidedCapture"
  | "boardUpdates";
type StepActivationSource = "click" | "keyboard" | "scroll";

type PendingDragMove = {
  destinationStage: FlowStageId;
  sourceStage: FlowStageId;
  vehicle: FlowVehicle;
};

const PHONE_DESIGN_WIDTH = 393;
const PHONE_DESIGN_HEIGHT = 852;
const managerName = "Stephen";

const assigneesByTeam: Record<
  string,
  {
    name: string;
    role: string;
    mobile: string;
  }
> = {
  "Lot team": { name: "Alex Park", role: "Lot team", mobile: "1403" },
  Service: { name: "Jordan Lee", role: "Service", mobile: "2841" },
  Detail: { name: "Maya Chen", role: "Detail", mobile: "6118" },
  Merchandising: { name: "Riley Patel", role: "Merchandising", mobile: "4472" },
  Manager: { name: "Stephen", role: "Manager", mobile: "0000" }
};

const stageStatusDefaults: Record<
  FlowStageId,
  Pick<StageOverride, "status" | "timeInStage" | "notificationState" | "slaState" | "event">
> = {
  arrival: {
    status: "Queued",
    timeInStage: "Just now",
    notificationState: "not-required",
    slaState: "On track",
    event: "Vehicle returned to New Arrival"
  },
  mechanical: {
    status: "In progress",
    timeInStage: "Just now",
    notificationState: "pending",
    slaState: "On track",
    event: "Service was assigned"
  },
  detail: {
    status: "In progress",
    timeInStage: "Just now",
    notificationState: "pending",
    slaState: "On track",
    event: "Detail was assigned"
  },
  imagery: {
    status: "Capture requested",
    timeInStage: "Just now",
    notificationState: "sent",
    slaState: "On track",
    event: "Secure SMS capture link sent"
  },
  listed: {
    status: "Published",
    timeInStage: "Complete",
    notificationState: "not-required",
    slaState: "Met",
    event: "Standardized views published to listing"
  }
};

const values = [
  [
    "Replace the whiteboard",
    "See the current stage, owner and next action without chasing updates across departments."
  ],
  [
    "Finish the handoff at the vehicle",
    "Each person scans the VIN and marks their work complete on the phone already in their hand."
  ],
  [
    "Give the next person the exact job",
    "Halo advances the stage, notifies the responsible employee and opens the right task in their browser."
  ],
  [
    "See what is holding up the lot",
    "Managers see waiting vehicles, missed handoffs and blockers during the working day, not after it."
  ]
] as const;

const handoffStages = [
  ["Sales", "Trade parked"],
  ["Service", "Mechanical complete"],
  ["Detail", "Vehicle ready"],
  ["Merchandising", "Capture requested"],
  ["Halo pipeline", "Capture, process, ship"]
] as const;

const roadmap = [
  ["Merchandising", "Available first"],
  ["Appraisals", "Next"],
  ["Reconditioning", "Next"],
  ["Future Halo Flows", "Shaped with members"]
] as const;

const prismNavigation: Array<{ icon: HaloIconName; label: string; meta: string }> = [
  { icon: "grid", label: "Overview", meta: "38" },
  { icon: "car", label: "Vehicles", meta: "142" },
  { icon: "route", label: "Workflows", meta: "12" },
  { icon: "alert", label: "Alerts", meta: "2" }
] as const;

const boardStageLabels: Record<FlowStageId, string> = {
  arrival: "New Arrival",
  mechanical: "Mechanical",
  detail: "Detail",
  imagery: "Final Imagery",
  listed: "Listed"
};

const rooftopOptions: PrismSelectOption[] = [
  { value: "Downtown Motors", label: "Downtown Motors" },
  { value: "North Store", label: "North Store" }
];

const workflowOptions: PrismSelectOption[] = [
  { value: "Merchandising", label: "Merchandising" },
  { value: "Reconditioning", label: "Reconditioning" }
];

const periodOptions: PrismSelectOption[] = [
  { value: "Today", label: "Today" },
  { value: "Last 7 days", label: "Last 7 days" }
];

const stageFilterOptions: PrismSelectOption[] = [
  { value: "all", label: "All stages" },
  ...workflowStages.map((stage) => ({ value: stage.id, label: stage.label }))
];

const slaFilterOptions: PrismSelectOption[] = [
  { value: "all", label: "All SLA states" },
  { value: "On track", label: "On track" },
  { value: "At risk", label: "At risk" },
  { value: "Met", label: "Met" }
];

const densityOptions: PrismSelectOption[] = [
  { value: "comfortable", label: "Comfortable" },
  { value: "compact", label: "Compact" }
];

const getOwnerLabel = (owner: string) => (owner === "Lot team" ? "Lot Team" : owner);

const boardStatusTone = (vehicle: FlowVehicle, boardAdvanced: boolean) => {
  if (vehicle.blockerTitle || vehicle.status === "Waiting on part") return "review";
  if (vehicle.stockNumber === heroVehicle.stockNumber && boardAdvanced) return "processing";
  if (vehicle.needsAttention) return "review";
  if (vehicle.currentStage === "listed") return "published";
  if (vehicle.notificationState === "sent") return "capturing";
  if (vehicle.currentStage === "mechanical" || vehicle.currentStage === "detail") return "processing";
  return "queued";
};

const boardStatusLabel = (
  vehicle: FlowVehicle,
  boardAdvanced: boolean,
  boardWorkflowPhase: BoardWorkflowPhase
) => {
  if (vehicle.stockNumber === heroVehicle.stockNumber && !boardAdvanced) {
    if (boardWorkflowPhase === "moving") return "Moving to Final Imagery…";
    if (boardWorkflowPhase === "active") return "Detail Complete";
  }
  if (vehicle.stockNumber === heroVehicle.stockNumber && boardAdvanced) return "Capture started";
  return vehicle.status;
};

const vehicleObservations = (vehicle: FlowVehicle) => {
  if (vehicle.observations?.length) return vehicle.observations;
  return [];
};

const boardSlaLabel = (vehicle: FlowVehicle) => {
  return vehicle.slaState;
};

const flowSteps: Array<{
  id: string;
  title: string;
  body: string;
  mobileBody: string;
  screen: FlowScreen;
}> = [
  {
    id: "scan-vin",
    title: "Scan VIN.",
    body: "The person standing at the vehicle scans the VIN and opens its current stage and assigned job.",
    mobileBody: "Scan the VIN to open the vehicle’s current stage and job.",
    screen: "scanVin"
  },
  {
    id: "detail-complete",
    title: "Mark Detail complete.",
    body: "The detailer declares the work complete at the vehicle. No manager has to copy the update from a whiteboard into another system.",
    mobileBody: "The detailer marks the job complete at the vehicle.",
    screen: "detailComplete"
  },
  {
    id: "operations-update",
    title: "Halo advances the vehicle.",
    body: "Halo moves the VIN to Final Imagery, assigns Merchandising and sends the next person the exact job.",
    mobileBody: "Halo advances the VIN, assigns Merchandising and sends the next job.",
    screen: "operationsUpdate"
  },
  {
    id: "sms-received",
    title: "Native SMS received.",
    body: "The next employee receives a secure Halo Capture link with the vehicle, dealership, and task context.",
    mobileBody: "The next employee receives a secure Halo Capture link.",
    screen: "smsReceived"
  },
  {
    id: "browser-opens",
    title: "Browser opens Halo.",
    body: "The secure link opens the exact Halo task in the employee’s browser.",
    mobileBody: "The secure link opens the exact Halo task in the browser.",
    screen: "browserOpens"
  },
  {
    id: "guided-capture",
    title: "Guided Capture starts.",
    body: "The real Halo Guided Capture interface opens with the vehicle task already loaded.",
    mobileBody: "Guided Capture opens with the vehicle task already loaded.",
    screen: "guidedCapture"
  },
  {
    id: "board-updates",
    title: "Operations Board updates.",
    body: "Managers see #9217 move from Detail to Final Imagery with SMS sent and capture pending.",
    mobileBody: "Managers see #9217 move to Final Imagery with capture pending.",
    screen: "boardUpdates"
  }
] as const;

const heroVehicle = {
  stockNumber: "#9217",
  vin: "ZPBUA1ZL3KLA04393",
  year: 2019,
  make: "Lamborghini",
  model: "Urus"
} as const;

const boardInventory: Record<FlowStageId, FlowVehicle[]> = {
  arrival: [
    {
      stockNumber: "#9274",
      vin: "1FTFW1E80PKE9274",
      year: 2023,
      make: "Ford",
      model: "F-150",
      currentStage: "arrival",
      responsibleTeam: "Lot team",
      timeInStage: "34 min",
      notificationState: "not-required",
      status: "Queued",
      slaState: "On track"
    },
    {
      stockNumber: "#9281",
      vin: "2HKRS4H78RH9281",
      year: 2024,
      make: "Honda",
      model: "CR-V",
      currentStage: "arrival",
      responsibleTeam: "Lot team",
      timeInStage: "49 min",
      notificationState: "not-required",
      status: "Queued",
      slaState: "On track"
    },
    {
      stockNumber: "#9286",
      vin: "2GNAXKEV6N69286",
      year: 2022,
      make: "Chevrolet",
      model: "Equinox",
      currentStage: "arrival",
      responsibleTeam: "Lot team",
      timeInStage: "1h 12m",
      notificationState: "not-required",
      status: "Queued",
      slaState: "On track"
    }
  ],
  mechanical: [
    {
      stockNumber: "#9248",
      vin: "1C4HJXDG7NW9248",
      year: 2022,
      make: "Jeep",
      model: "Wrangler",
      currentStage: "mechanical",
      responsibleTeam: "Service",
      timeInStage: "44 min",
      notificationState: "pending",
      status: "In progress",
      slaState: "On track"
    },
    {
      stockNumber: "#9260",
      vin: "5NMJBCAE9PH9260",
      year: 2023,
      make: "Hyundai",
      model: "Tucson",
      currentStage: "mechanical",
      responsibleTeam: "Service",
      timeInStage: "2h 18m",
      notificationState: "pending",
      needsAttention: true,
      status: "Review needed",
      slaState: "At risk"
    }
  ],
  detail: [
    {
      ...heroVehicle,
      currentStage: "detail",
      responsibleTeam: "Detail",
      timeInStage: "Ready",
      notificationState: "pending",
      status: "Ready to complete",
      slaState: "On track",
      event: "Detail is ready to complete"
    },
    {
      stockNumber: "#9194",
      vin: "5TDGZRBH4MS9194",
      year: 2021,
      make: "Toyota",
      model: "Highlander",
      currentStage: "detail",
      responsibleTeam: "Detail",
      timeInStage: "31 min",
      notificationState: "pending",
      status: "In progress",
      slaState: "On track"
    },
    {
      stockNumber: "#9251",
      vin: "5XYK6CAF7RG9251",
      year: 2024,
      make: "Kia",
      model: "Sportage",
      currentStage: "detail",
      responsibleTeam: "Detail",
      timeInStage: "16 min",
      notificationState: "pending",
      status: "In progress",
      slaState: "On track"
    }
  ],
  imagery: [
    {
      stockNumber: "#9229",
      vin: "JM3KFBDM7P09229",
      year: 2023,
      make: "Mazda",
      model: "CX-5",
      currentStage: "imagery",
      responsibleTeam: "Merchandising",
      timeInStage: "18 min",
      notificationState: "sent",
      status: "Notified",
      slaState: "On track",
      event: "Waiting for capture to begin"
    },
    {
      stockNumber: "#9233",
      vin: "5N1BT3BB7PC9233",
      year: 2023,
      make: "Nissan",
      model: "Kicks",
      currentStage: "imagery",
      responsibleTeam: "Merchandising",
      timeInStage: "27 min",
      notificationState: "sent",
      status: "Capture pending",
      slaState: "On track",
      event: "Cleaning recommended before publication",
      observations: [
        "Exterior cleaning recommended",
        "Dirt detected on passenger side.",
        "Recommended: Quick clean and recapture before publication."
      ]
    }
  ],
  listed: [
    {
      stockNumber: "#9182",
      vin: "5UXTY5C04N99182",
      year: 2022,
      make: "BMW",
      model: "X3",
      currentStage: "listed",
      responsibleTeam: "Manager",
      timeInStage: "Complete",
      notificationState: "not-required",
      status: "Published",
      slaState: "Met"
    },
    {
      stockNumber: "#9205",
      vin: "3VV3B7AX4RM9205",
      year: 2024,
      make: "Volkswagen",
      model: "Tiguan",
      currentStage: "listed",
      responsibleTeam: "Manager",
      timeInStage: "Complete",
      notificationState: "not-required",
      status: "Published",
      slaState: "Met"
    }
  ]
};

function createBoardInventory(hasAdvanced: boolean): Record<FlowStageId, FlowVehicle[]> {
  if (!hasAdvanced) return boardInventory;

  return {
    ...boardInventory,
    detail: boardInventory.detail.filter((vehicle) => vehicle.stockNumber !== heroVehicle.stockNumber),
    imagery: [
      {
        ...heroVehicle,
        currentStage: "imagery",
        responsibleTeam: "Merchandising",
        timeInStage: "Just now",
        notificationState: "sent",
        status: "Capture started",
        slaState: "On track",
        event: "Guided Capture has begun",
        assignedTo: getAssigneeForTeam("Merchandising").name,
        contactState: "Secure SMS opened"
      },
      ...boardInventory.imagery
    ]
  };
}

const getStageIndex = (stageId: FlowStageId) => workflowStages.findIndex((stage) => stage.id === stageId);

const getNextStage = (stageId: FlowStageId) => {
  const nextStage = workflowStages[getStageIndex(stageId) + 1];
  return nextStage?.id;
};

const getStageTeam = (stageId: FlowStageId) =>
  workflowStages.find((stage) => stage.id === stageId)?.team ?? "Manager";

const getAssigneeForTeam = (team: string) => assigneesByTeam[team] ?? assigneesByTeam.Manager;

const getOperationalRank = (vehicle: FlowVehicle) => {
  if (vehicle.slaState === "At risk") return 0;
  if (vehicle.blockerTitle) return 1;
  if (vehicle.needsAttention) return 2;
  return 3;
};

const createInitialTimeline = (vehicle: FlowVehicle): TimelineEvent[] => {
  const events: TimelineEvent[] = [];

  if (vehicle.needsAttention) {
    events.push({
      id: `${vehicle.stockNumber}-attention`,
      stockNumber: vehicle.stockNumber,
      type: "automation",
      title: "Review needed",
      body: "Vehicle has exceeded the expected dwell window.",
      meta: "Halo automation · Today, 2:08 PM",
      source: "Halo"
    });
  }

  if (vehicle.event) {
    events.push({
      id: `${vehicle.stockNumber}-event`,
      stockNumber: vehicle.stockNumber,
      type: "automation",
      title: vehicle.event,
      body: `${boardStageLabels[vehicle.currentStage]} is the current workflow stage.`,
      meta: "Halo automation · Today, 2:04 PM",
      source: "Halo"
    });
  }

  events.push({
    id: `${vehicle.stockNumber}-stage`,
    stockNumber: vehicle.stockNumber,
    type: "stage",
    title: `Moved to ${boardStageLabels[vehicle.currentStage]}`,
    body: `${getStageTeam(vehicle.currentStage)} owns the current action.`,
    meta: "Halo automation · Today, 10:42 AM",
    source: "Halo"
  });

  return events;
};

const createStageOverride = (
  vehicle: FlowVehicle,
  destinationStage: FlowStageId,
  event: string,
  options?: Partial<StageOverride>
): StageOverride => {
  const stageTeam = getStageTeam(destinationStage);
  const defaults = stageStatusDefaults[destinationStage];
  return {
    stage: destinationStage,
    previousStage: vehicle.currentStage,
    status: defaults.status,
    responsibleTeam: stageTeam,
    timeInStage: defaults.timeInStage,
    notificationState: defaults.notificationState,
    slaState: defaults.slaState,
    event,
    assignedTo: getAssigneeForTeam(stageTeam).name,
    needsAttention: false,
    contactState: undefined,
    unreadReply: false,
    blockerTitle: undefined,
    ...options
  };
};

export function HaloFlowsSection() {
  const [activeStepIndex, setActiveStepIndex] = useState<number | null>(null);
  const [replayVersion, setReplayVersion] = useState(0);
  const [captureLaunchOpen, setCaptureLaunchOpen] = useState(false);
  const [selectedVehicleStock, setSelectedVehicleStock] = useState<string | null>(null);
  const [boardSearch, setBoardSearch] = useState("");
  const [stageFilter, setStageFilter] = useState<FlowStageId | "all">("all");
  const [ownerFilter, setOwnerFilter] = useState("all");
  const [slaFilter, setSlaFilter] = useState<SlaState | "all">("all");
  const [boardView, setBoardView] = useState<"board" | "table">("board");
  const [density, setDensity] = useState<"comfortable" | "compact">("comfortable");
  const [stageOverrides, setStageOverrides] = useState<Record<string, StageOverride>>({});
  const [vehicleTimelines, setVehicleTimelines] = useState<Record<string, TimelineEvent[]>>({});
  const [confirmationMode, setConfirmationMode] = useState<ConfirmationMode>(null);
  const [manualStage, setManualStage] = useState<FlowStageId>("arrival");
  const [actionNote, setActionNote] = useState("");
  const [nudgeComposerOpen, setNudgeComposerOpen] = useState(false);
  const [nudgeMessage, setNudgeMessage] = useState("");
  const [sendState, setSendState] = useState<"idle" | "sending" | "delivered" | "failed">("idle");
  const [replyAnnouncement, setReplyAnnouncement] = useState("");
  const [blockerDraft, setBlockerDraft] = useState("Waiting for centre cap installation");
  const [dragEnabled, setDragEnabled] = useState(false);
  const [draggedStock, setDraggedStock] = useState<string | null>(null);
  const [dragOverStage, setDragOverStage] = useState<FlowStageId | null>(null);
  const [pendingDragMove, setPendingDragMove] = useState<PendingDragMove | null>(null);
  const [dragMoveNote, setDragMoveNote] = useState("");
  const [boardAnnouncement, setBoardAnnouncement] = useState("");
  const [boardHasAdvanced, setBoardHasAdvanced] = useState(false);
  const [boardWorkflowPhase, setBoardWorkflowPhase] = useState<BoardWorkflowPhase>("resting");
  const [showBoardHint, setShowBoardHint] = useState(false);
  const [boardHintDismissed, setBoardHintDismissed] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
  const [mobileStage, setMobileStage] = useState<FlowStageId>("arrival");
  const [vinConfirmed, setVinConfirmed] = useState(false);
  const [vinReviewReady, setVinReviewReady] = useState(false);
  const [vinResetKey, setVinResetKey] = useState(0);
  const [vinScanStarted, setVinScanStarted] = useState(false);
  const [detailActionComplete, setDetailActionComplete] = useState(false);
  const [detailActionProcessing, setDetailActionProcessing] = useState(false);
  const [captureStartedFromLaunch, setCaptureStartedFromLaunch] = useState(false);
  const [reduceVinMotion, setReduceVinMotion] = useState(false);
  const [phonePresentationScale, setPhonePresentationScale] = useState(1);
  const activeStepIndexRef = useRef<number | null>(null);
  const activationLockRef = useRef(false);
  const activationLockTimerRef = useRef<number | null>(null);
  const candidateStepRef = useRef<number | null>(null);
  const candidateSinceRef = useRef<number | null>(null);
  const candidateTimerRef = useRef<number | null>(null);
  const hasActivatedStepRef = useRef(false);
  const lastScrollYRef = useRef(0);
  const scrollDirectionRef = useRef<"down" | "up">("down");
  const stepRefs = useRef<Array<HTMLElement | null>>([]);
  const storyStepsRef = useRef<HTMLDivElement | null>(null);
  const boardStoryRef = useRef<HTMLDivElement | null>(null);
  const storyPagerFrameRef = useRef<number | null>(null);
  const productStickyRef = useRef<HTMLDivElement | null>(null);
  const mobileActiveStepHeaderRef = useRef<HTMLButtonElement | null>(null);
  const mobileStoryControlsRef = useRef<HTMLDivElement | null>(null);
  const vehicleCardRefs = useRef<Record<string, HTMLButtonElement | null>>({});
  const drawerCloseRef = useRef<HTMLButtonElement | null>(null);
  const mobileMenuButtonRef = useRef<HTMLButtonElement | null>(null);
  const mobileFilterButtonRef = useRef<HTMLButtonElement | null>(null);
  const mobileMenuCloseRef = useRef<HTMLButtonElement | null>(null);
  const mobileFilterCloseRef = useRef<HTMLButtonElement | null>(null);
  const boardSequenceTimersRef = useRef<number[]>([]);
  const boardReplayArmedRef = useRef(true);
  const detailActionTimerRef = useRef<number | null>(null);

  const clearBoardSequenceTimers = useCallback(() => {
    boardSequenceTimersRef.current.forEach((timer) => window.clearTimeout(timer));
    boardSequenceTimersRef.current = [];
  }, []);

  const startBoardWorkflowSequence = useCallback(() => {
    clearBoardSequenceTimers();
    setBoardHasAdvanced(false);
    setBoardWorkflowPhase("resting");
    setShowBoardHint(false);

    const transitionDocument = document as Document & {
      startViewTransition?: (callback: () => void) => { finished: Promise<void> };
    };

    const advanceBoard = () => {
      const startViewTransition = transitionDocument.startViewTransition?.bind(transitionDocument);
      const applyBoardAdvance = () => {
        setBoardHasAdvanced(true);
        setBoardWorkflowPhase("settled");
        setMobileStage("imagery");
        setBoardAnnouncement(`${heroVehicle.stockNumber} moved to Final Imagery. Capture started.`);
      };

      if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches && startViewTransition) {
        startViewTransition(applyBoardAdvance);
        return;
      }

      applyBoardAdvance();
    };

    boardSequenceTimersRef.current = [
      window.setTimeout(() => setBoardWorkflowPhase("active"), 520),
      window.setTimeout(() => setBoardWorkflowPhase("moving"), 1040),
      window.setTimeout(advanceBoard, 1480),
      window.setTimeout(() => {
        if (!boardHintDismissed) setShowBoardHint(true);
      }, 2220),
      window.setTimeout(() => setShowBoardHint(false), 7220)
    ];
  }, [boardHintDismissed, clearBoardSequenceTimers]);

  const handleBoardInteraction = useCallback(() => {
    setBoardHintDismissed(true);
    setShowBoardHint(false);
  }, []);

  const resetStepExperience = useCallback((index: number) => {
    setCaptureLaunchOpen(false);
    setVinConfirmed(false);
    setVinReviewReady(false);
    setVinScanStarted(index === 0);
    setDetailActionComplete(false);
    setDetailActionProcessing(false);
    setCaptureStartedFromLaunch(false);
    if (detailActionTimerRef.current) {
      window.clearTimeout(detailActionTimerRef.current);
      detailActionTimerRef.current = null;
    }
    setVinResetKey((key) => key + 1);
    setReplayVersion((version) => version + 1);
  }, []);

  const scrollCardIntoPresentationPosition = useCallback((index: number) => {
    const card = stepRefs.current[index];
    if (!card) return;

    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const mobilePager = window.matchMedia("(max-width: 767px)").matches;
    if (mobilePager) {
      card.scrollIntoView({
        behavior: reduceMotion ? "auto" : "smooth",
        block: "start",
        inline: "nearest"
      });
      return;
    }

    card.scrollIntoView({
      behavior: reduceMotion ? "auto" : "smooth",
      block: "center",
      inline: "nearest"
    });
  }, []);

  const commitActiveStep = useCallback(
    (index: number, forceReplay = false) => {
      if (index < 0 || index >= flowSteps.length) return;
      const isSameStep = index === activeStepIndexRef.current;
      if (isSameStep && !forceReplay && hasActivatedStepRef.current) return;

      resetStepExperience(index);
      hasActivatedStepRef.current = true;
      activeStepIndexRef.current = index;
      setActiveStepIndex(index);
    },
    [resetStepExperience]
  );

  const activateStep = useCallback(
    (index: number, source: StepActivationSource) => {
      if (index < 0 || index >= flowSteps.length) return;
      if (activationLockTimerRef.current) {
        window.clearTimeout(activationLockTimerRef.current);
        activationLockTimerRef.current = null;
      }

      if (source === "click" || source === "keyboard") {
        activationLockRef.current = true;
        candidateStepRef.current = null;
        candidateSinceRef.current = null;
        if (candidateTimerRef.current) {
          window.clearTimeout(candidateTimerRef.current);
          candidateTimerRef.current = null;
        }
        activationLockTimerRef.current = window.setTimeout(() => {
          activationLockRef.current = false;
          activationLockTimerRef.current = null;
        }, 1800);
      }

      commitActiveStep(index, source !== "scroll");

      if (source === "click" || source === "keyboard") scrollCardIntoPresentationPosition(index);
    },
    [commitActiveStep, scrollCardIntoPresentationPosition]
  );

  useEffect(() => {
    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    setReduceVinMotion(reduceMotion);
  }, []);

  useEffect(() => {
    let frame = 0;

    const calculatePhoneScale = () => {
      frame = 0;
      const mobile = window.matchMedia("(max-width: 767px)").matches;
      const tabletPortrait = window.matchMedia(
        "(min-width: 768px) and (max-width: 1020px) and (orientation: portrait)"
      ).matches;

      if (!mobile && !tabletPortrait) {
        setPhonePresentationScale(1);
        return;
      }

      const sticky = productStickyRef.current;
      if (!sticky) return;

      const stickyStyles = window.getComputedStyle(sticky);
      const stack = sticky.querySelector(`.${styles.demoStack}`) as HTMLElement | null;
      const stackStyles = stack ? window.getComputedStyle(stack) : null;
      const rowGap = stackStyles ? Number.parseFloat(stackStyles.rowGap) || 0 : 0;
      const cardHeight = mobileActiveStepHeaderRef.current?.getBoundingClientRect().height ?? 0;
      const controlsHeight = mobileStoryControlsRef.current?.getBoundingClientRect().height ?? 0;
      const stickyWidth = sticky.getBoundingClientRect().width;
      const stickyHeight =
        sticky.getBoundingClientRect().height ||
        window.innerHeight - (Number.parseFloat(stickyStyles.top) || 0);
      const verticalRows = mobile ? cardHeight + controlsHeight + rowGap * 2 : controlsHeight + rowGap;
      const availableHeight = Math.max(1, stickyHeight - verticalRows);
      const availableWidth = Math.max(1, stickyWidth);

      const nextScale = Math.min(
        1,
        availableWidth / PHONE_DESIGN_WIDTH,
        availableHeight / PHONE_DESIGN_HEIGHT
      );
      setPhonePresentationScale(Math.max(0.34, Math.round(nextScale * 1000) / 1000));
    };

    const requestScale = () => {
      if (frame) return;
      frame = window.requestAnimationFrame(calculatePhoneScale);
    };

    const resizeObserver = new ResizeObserver(requestScale);
    [productStickyRef.current, mobileActiveStepHeaderRef.current, mobileStoryControlsRef.current].forEach(
      (element) => {
        if (element) resizeObserver.observe(element);
      }
    );

    requestScale();
    window.addEventListener("resize", requestScale);
    window.visualViewport?.addEventListener("resize", requestScale);

    return () => {
      if (frame) window.cancelAnimationFrame(frame);
      resizeObserver.disconnect();
      window.removeEventListener("resize", requestScale);
      window.visualViewport?.removeEventListener("resize", requestScale);
    };
  }, [activeStepIndex]);

  useEffect(() => {
    return () => {
      if (activationLockTimerRef.current) window.clearTimeout(activationLockTimerRef.current);
      if (storyPagerFrameRef.current) window.cancelAnimationFrame(storyPagerFrameRef.current);
      if (detailActionTimerRef.current) window.clearTimeout(detailActionTimerRef.current);
      clearBoardSequenceTimers();
    };
  }, [clearBoardSequenceTimers]);

  useEffect(() => {
    const boardElement = boardStoryRef.current;
    if (!boardElement) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (!entry) return;

        if (entry.intersectionRatio <= 0) {
          boardReplayArmedRef.current = true;
          clearBoardSequenceTimers();
          setShowBoardHint(false);
          return;
        }

        if (entry.intersectionRatio < 0.36 || !boardReplayArmedRef.current) return;
        boardReplayArmedRef.current = false;
        startBoardWorkflowSequence();
      },
      {
        threshold: [0, 0.36]
      }
    );

    observer.observe(boardElement);

    return () => observer.disconnect();
  }, [clearBoardSequenceTimers, startBoardWorkflowSequence]);

  useEffect(() => {
    const activationBand = 48;
    const activationDwellMs = 120;
    let frame = 0;

    const proposeStep = (index: number) => {
      const now = performance.now();
      if (candidateStepRef.current !== index) {
        candidateStepRef.current = index;
        candidateSinceRef.current = now;
        if (candidateTimerRef.current) window.clearTimeout(candidateTimerRef.current);
        candidateTimerRef.current = window.setTimeout(() => {
          if (candidateStepRef.current !== index || activationLockRef.current) return;
          candidateStepRef.current = null;
          candidateSinceRef.current = null;
          candidateTimerRef.current = null;
          commitActiveStep(index);
        }, activationDwellMs);
        return;
      }

      if (candidateSinceRef.current !== null && now - candidateSinceRef.current >= activationDwellMs) {
        candidateStepRef.current = null;
        candidateSinceRef.current = null;
        if (candidateTimerRef.current) {
          window.clearTimeout(candidateTimerRef.current);
          candidateTimerRef.current = null;
        }
        commitActiveStep(index);
      }
    };

    const updateScrollDirection = () => {
      const nextScrollY = window.scrollY;
      if (Math.abs(nextScrollY - lastScrollYRef.current) < 2) return;
      scrollDirectionRef.current = nextScrollY > lastScrollYRef.current ? "down" : "up";
      lastScrollYRef.current = nextScrollY;
    };

    const evaluateActiveCard = () => {
      frame = 0;
      if (activationLockRef.current) return;

      const mobilePresentation = window.matchMedia("(max-width: 767px)").matches;
      if (mobilePresentation && storyStepsRef.current) {
        const storyRect = storyStepsRef.current.getBoundingClientRect();
        const stickyTop = productStickyRef.current
          ? Number.parseFloat(window.getComputedStyle(productStickyRef.current).top) || 0
          : 0;
        const stepHeight = Math.max(1, storyRect.height / flowSteps.length);
        const progress = (stickyTop - storyRect.top) / stepHeight;
        const nextIndex = Math.min(flowSteps.length - 1, Math.max(0, Math.floor(progress + 0.58)));
        commitActiveStep(nextIndex);
        return;
      }

      const activationY = window.innerHeight * (mobilePresentation ? 0.18 : 0.5);
      let bestIndex: number | null = activeStepIndexRef.current;
      let bestDistance = Number.POSITIVE_INFINITY;

      stepRefs.current.forEach((card, index) => {
        if (!card) return;
        const rect = card.getBoundingClientRect();
        if (rect.bottom < 0 || rect.top > window.innerHeight) return;
        const center = rect.top + rect.height / 2;
        const distance = Math.abs(center - activationY);
        if (distance < bestDistance) {
          bestDistance = distance;
          bestIndex = index;
        }
      });

      const current = activeStepIndexRef.current;
      if (bestIndex === null) return;

      const candidateCard = stepRefs.current[bestIndex];
      if (!candidateCard) return;

      const candidateRect = candidateCard.getBoundingClientRect();
      const candidateCenter = candidateRect.top + candidateRect.height / 2;
      const visibleHeight =
        Math.min(candidateRect.bottom, window.innerHeight) - Math.max(candidateRect.top, 0);
      const visibleRatio = candidateRect.height > 0 ? Math.max(0, visibleHeight) / candidateRect.height : 0;

      if (current === null) {
        const isInsideActivationBand = Math.abs(candidateCenter - activationY) <= 80;
        if (visibleRatio >= 0.5 || isInsideActivationBand) proposeStep(bestIndex);
        return;
      }

      if (bestIndex === current) {
        candidateStepRef.current = null;
        candidateSinceRef.current = null;
        return;
      }

      const direction = scrollDirectionRef.current;
      const crossedActivationLine =
        direction === "down"
          ? bestIndex > current && candidateCenter <= activationY + activationBand
          : bestIndex < current && candidateCenter >= activationY - activationBand;

      if (!crossedActivationLine) return;
      proposeStep(bestIndex);
    };

    const requestEvaluation = () => {
      updateScrollDirection();
      if (frame) return;
      frame = window.requestAnimationFrame(evaluateActiveCard);
    };

    lastScrollYRef.current = window.scrollY;
    window.addEventListener("scroll", requestEvaluation, { passive: true });
    window.addEventListener("resize", requestEvaluation);
    requestEvaluation();

    return () => {
      if (frame) window.cancelAnimationFrame(frame);
      if (candidateTimerRef.current) window.clearTimeout(candidateTimerRef.current);
      window.removeEventListener("scroll", requestEvaluation);
      window.removeEventListener("resize", requestEvaluation);
    };
  }, [commitActiveStep]);

  const handleMobileStoryScroll = () => {
    if (typeof window === "undefined") return;
    if (!window.matchMedia("(max-width: 767px)").matches) return;
    const container = storyStepsRef.current;
    if (!container) return;

    if (storyPagerFrameRef.current) window.cancelAnimationFrame(storyPagerFrameRef.current);
    storyPagerFrameRef.current = window.requestAnimationFrame(() => {
      storyPagerFrameRef.current = null;
      const containerRect = container.getBoundingClientRect();
      const centerX = containerRect.left + containerRect.width / 2;
      let nearestIndex = displayedStepIndex;
      let nearestDistance = Number.POSITIVE_INFINITY;

      stepRefs.current.forEach((card, index) => {
        if (!card) return;
        const rect = card.getBoundingClientRect();
        const distance = Math.abs(rect.left + rect.width / 2 - centerX);
        if (distance < nearestDistance) {
          nearestDistance = distance;
          nearestIndex = index;
        }
      });

      commitActiveStep(nearestIndex);
    });
  };

  useEffect(() => {
    if (!selectedVehicleStock) return;

    drawerCloseRef.current?.focus();

    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      const stockToRestore = selectedVehicleStock;
      setSelectedVehicleStock(null);
      window.requestAnimationFrame(() => vehicleCardRefs.current[stockToRestore]?.focus());
    };

    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [selectedVehicleStock]);

  useEffect(() => {
    if (!mobileMenuOpen && !mobileFiltersOpen) return;

    const closeOnEscape = (event: globalThis.KeyboardEvent) => {
      if (event.key !== "Escape") return;
      if (mobileMenuOpen) {
        setMobileMenuOpen(false);
        window.requestAnimationFrame(() => mobileMenuButtonRef.current?.focus());
      }
      if (mobileFiltersOpen) {
        setMobileFiltersOpen(false);
        window.requestAnimationFrame(() => mobileFilterButtonRef.current?.focus());
      }
    };

    if (mobileMenuOpen) mobileMenuCloseRef.current?.focus();
    if (mobileFiltersOpen) mobileFilterCloseRef.current?.focus();
    window.addEventListener("keydown", closeOnEscape);

    return () => {
      window.removeEventListener("keydown", closeOnEscape);
    };
  }, [mobileFiltersOpen, mobileMenuOpen]);

  useEffect(() => {
    if (!selectedVehicleStock) return;
    setConfirmationMode(null);
    setNudgeComposerOpen(false);
    setSendState("idle");
    setActionNote("");
  }, [selectedVehicleStock]);

  useEffect(() => {
    const query = window.matchMedia("(min-width: 681px) and (pointer: fine)");
    const updateDragMode = () => setDragEnabled(query.matches);
    updateDragMode();
    query.addEventListener("change", updateDragMode);
    return () => query.removeEventListener("change", updateDragMode);
  }, []);

  const displayedStepIndex = activeStepIndex ?? 0;
  const activeStep = flowSteps[displayedStepIndex];
  const activeScreen = activeStep.screen;
  const vehicleIdentified = displayedStepIndex > 0 || vinConfirmed;
  const detailComplete = displayedStepIndex >= 2 || detailActionComplete;
  const notificationQueued = displayedStepIndex >= 2 || detailActionComplete;
  const notificationSent = displayedStepIndex >= 3;
  const browserOpened = displayedStepIndex >= 4;
  const captureOpened = displayedStepIndex >= 5 || captureStartedFromLaunch;
  const boardAdvanced = boardHasAdvanced;
  const showWorkflowBottomNav = !vehicleIdentified || (displayedStepIndex >= 1 && displayedStepIndex <= 2);
  const topChromeTimes = ["2:07", "2:08", "2:09", "2:10", "2:10", "2:11", "2:11"] as const;
  const topChromeTime = topChromeTimes[Math.min(displayedStepIndex, topChromeTimes.length - 1)];

  useEffect(() => {
    if (!vehicleIdentified || notificationSent) setCaptureLaunchOpen(false);
  }, [notificationSent, vehicleIdentified]);

  const completeDetailAction = () => {
    if (detailActionProcessing || detailActionComplete) return;
    setDetailActionProcessing(true);
    if (detailActionTimerRef.current) window.clearTimeout(detailActionTimerRef.current);
    detailActionTimerRef.current = window.setTimeout(() => {
      setDetailActionComplete(true);
      setDetailActionProcessing(false);
      detailActionTimerRef.current = null;
    }, 620);
  };

  const board = useMemo(() => {
    const baseBoard = createBoardInventory(boardAdvanced);
    const stagedBoard = workflowStages.reduce(
      (accumulator, stage) => ({
        ...accumulator,
        [stage.id]: []
      }),
      {} as Record<FlowStageId, FlowVehicle[]>
    );

    Object.values(baseBoard)
      .flat()
      .forEach((vehicle) => {
        const override = stageOverrides[vehicle.stockNumber];
        const stagedVehicle: FlowVehicle = override
          ? {
              ...vehicle,
              currentStage: override.stage,
              responsibleTeam: override.responsibleTeam,
              timeInStage: override.timeInStage,
              notificationState: override.notificationState,
              needsAttention: override.needsAttention,
              status: override.status,
              slaState: override.slaState,
              event: override.event,
              assignedTo: override.assignedTo,
              contactState: override.contactState,
              unreadReply: override.unreadReply,
              blockerTitle: override.blockerTitle
            }
          : {
              ...vehicle,
              assignedTo: getAssigneeForTeam(vehicle.responsibleTeam).name
            };

        stagedBoard[stagedVehicle.currentStage].push(stagedVehicle);
      });

    workflowStages.forEach((stage) => {
      stagedBoard[stage.id].sort((left, right) => getOperationalRank(left) - getOperationalRank(right));
    });

    return stagedBoard;
  }, [boardAdvanced, stageOverrides]);
  const boardRows = useMemo(() => Object.values(board).flat(), [board]);
  const filteredBoard = useMemo(() => {
    const search = boardSearch.trim().toLowerCase();
    return workflowStages.reduce(
      (accumulator, stage) => {
        const vehicles = board[stage.id].filter((vehicle) => {
          const matchesStage = stageFilter === "all" || vehicle.currentStage === stageFilter;
          const matchesOwner = ownerFilter === "all" || vehicle.responsibleTeam === ownerFilter;
          const matchesSla = slaFilter === "all" || vehicle.slaState === slaFilter;
          const haystack = [
            vehicle.stockNumber,
            vehicle.vin,
            vehicle.year,
            vehicle.make,
            vehicle.model,
            vehicle.status,
            vehicle.responsibleTeam,
            boardStageLabels[vehicle.currentStage],
            vehicle.event
          ]
            .filter(Boolean)
            .join(" ")
            .toLowerCase();
          return matchesStage && matchesOwner && matchesSla && (!search || haystack.includes(search));
        });

        return {
          ...accumulator,
          [stage.id]: vehicles
        };
      },
      {} as Record<FlowStageId, FlowVehicle[]>
    );
  }, [board, boardSearch, ownerFilter, slaFilter, stageFilter]);
  const filteredRows = useMemo(() => Object.values(filteredBoard).flat(), [filteredBoard]);
  const ownerOptions = useMemo(
    () => Array.from(new Set(boardRows.map((vehicle) => vehicle.responsibleTeam))),
    [boardRows]
  );
  const ownerFilterOptions = useMemo<PrismSelectOption[]>(
    () => [
      { value: "all", label: "All owners" },
      ...ownerOptions.map((owner) => ({ value: owner, label: getOwnerLabel(owner) }))
    ],
    [ownerOptions]
  );
  const selectedBoardVehicle = selectedVehicleStock
    ? boardRows.find((vehicle) => vehicle.stockNumber === selectedVehicleStock)
    : undefined;
  const selectedTimeline = selectedBoardVehicle
    ? (vehicleTimelines[selectedBoardVehicle.stockNumber] ?? createInitialTimeline(selectedBoardVehicle))
    : [];
  const selectedObservations = selectedBoardVehicle ? vehicleObservations(selectedBoardVehicle) : [];
  const selectedNextStage = selectedBoardVehicle
    ? getNextStage(selectedBoardVehicle.currentStage)
    : undefined;
  const selectedOwner = selectedBoardVehicle
    ? getAssigneeForTeam(selectedBoardVehicle.responsibleTeam)
    : assigneesByTeam.Manager;
  const selectedNextOwner = selectedNextStage
    ? getAssigneeForTeam(getStageTeam(selectedNextStage))
    : assigneesByTeam.Manager;
  useEffect(() => {
    if (!selectedBoardVehicle?.unreadReply) return;
    const stockNumber = selectedBoardVehicle.stockNumber;
    const timer = window.setTimeout(() => {
      setStageOverrides((current) => {
        const currentOverride = current[stockNumber];
        if (!currentOverride) return current;
        return {
          ...current,
          [stockNumber]: {
            ...currentOverride,
            unreadReply: false,
            contactState: "Reply viewed"
          }
        };
      });
    }, 350);
    return () => window.clearTimeout(timer);
  }, [selectedBoardVehicle?.stockNumber, selectedBoardVehicle?.unreadReply]);
  const addTimelineEvent = (stockNumber: string, event: TimelineEvent) => {
    setVehicleTimelines((current) => ({
      ...current,
      [stockNumber]: [event, ...(current[stockNumber] ?? [])]
    }));
  };
  const openStageConfirmation = (mode: ConfirmationMode, destination?: FlowStageId) => {
    if (!selectedBoardVehicle || !mode) return;
    setManualStage(
      destination ?? getNextStage(selectedBoardVehicle.currentStage) ?? selectedBoardVehicle.currentStage
    );
    setActionNote("");
    setConfirmationMode(mode);
  };
  const confirmStageMove = () => {
    if (!selectedBoardVehicle || !confirmationMode) return;
    const destinationStage = confirmationMode === "next" ? selectedNextStage : manualStage;
    if (!destinationStage) return;
    const isNonSequential = confirmationMode === "change" && destinationStage !== selectedNextStage;
    const note = actionNote.trim();
    if (isNonSequential && !note) return;
    const destinationLabel = boardStageLabels[destinationStage];
    const destinationTeam = getStageTeam(destinationStage);
    const eventTitle =
      confirmationMode === "next" ? `Moved to ${destinationLabel}` : `Stage changed to ${destinationLabel}`;
    const eventBody =
      confirmationMode === "next"
        ? `${managerName} moved the vehicle from ${boardStageLabels[selectedBoardVehicle.currentStage]} to ${destinationLabel}. ${destinationTeam} was assigned.`
        : `${managerName} changed the stage from ${boardStageLabels[selectedBoardVehicle.currentStage]} to ${destinationLabel}.${note ? ` Reason: ${note}` : ""}`;

    setStageOverrides((current) => ({
      ...current,
      [selectedBoardVehicle.stockNumber]: createStageOverride(
        selectedBoardVehicle,
        destinationStage,
        eventTitle,
        {
          contactState:
            destinationStage === "imagery" ? "SMS ready for Merchandising" : "Stage updated manually"
        }
      )
    }));
    addTimelineEvent(selectedBoardVehicle.stockNumber, {
      id: `${selectedBoardVehicle.stockNumber}-stage-${Date.now()}`,
      stockNumber: selectedBoardVehicle.stockNumber,
      type: "stage",
      title: eventTitle,
      body: eventBody,
      meta: `Manual · Today, 2:14 PM${note && confirmationMode === "next" ? ` · ${note}` : ""}`,
      source: "Manual"
    });
    setMobileStage(destinationStage);
    setConfirmationMode(null);
    setActionNote("");
  };
  const moveVehicleToStage = (
    vehicle: FlowVehicle,
    destinationStage: FlowStageId,
    note: string,
    moveSource: "drag" | "drawer"
  ) => {
    const destinationLabel = boardStageLabels[destinationStage];
    const destinationTeam = getStageTeam(destinationStage);
    const sourceLabel = boardStageLabels[vehicle.currentStage];
    const eventTitle = `Moved to ${destinationLabel}`;
    const eventBody = `${managerName} moved ${vehicle.stockNumber} from ${sourceLabel} to ${destinationLabel}. ${destinationTeam} assigned.${note ? ` Note: ${note}` : ""}`;

    setStageOverrides((current) => ({
      ...current,
      [vehicle.stockNumber]: createStageOverride(vehicle, destinationStage, eventTitle, {
        contactState: moveSource === "drag" ? "Moved from board" : "Stage updated manually",
        blockerTitle: vehicle.blockerTitle,
        needsAttention: vehicle.blockerTitle ? vehicle.needsAttention : false,
        slaState: vehicle.blockerTitle ? vehicle.slaState : stageStatusDefaults[destinationStage].slaState
      })
    }));
    addTimelineEvent(vehicle.stockNumber, {
      id: `${vehicle.stockNumber}-drag-stage-${Date.now()}`,
      stockNumber: vehicle.stockNumber,
      type: "stage",
      title: eventTitle,
      body: eventBody,
      meta: `Manual · Today, 2:41 PM`,
      source: "Manual"
    });
    setMobileStage(destinationStage);
    setBoardAnnouncement(`${vehicle.stockNumber} moved to ${destinationLabel}.`);
  };
  const isNonSequentialDragMove = (move: PendingDragMove) =>
    getStageIndex(move.destinationStage) !== getStageIndex(move.sourceStage) + 1;
  const isBlockedForwardDragMove = (move: PendingDragMove) =>
    Boolean(move.vehicle.blockerTitle) &&
    getStageIndex(move.destinationStage) > getStageIndex(move.sourceStage);
  const confirmDragMove = () => {
    if (!pendingDragMove) return;
    const note = dragMoveNote.trim();
    const requiresReason =
      isNonSequentialDragMove(pendingDragMove) || isBlockedForwardDragMove(pendingDragMove);
    if (requiresReason && !note) return;
    moveVehicleToStage(pendingDragMove.vehicle, pendingDragMove.destinationStage, note, "drag");
    const stockToRestore = pendingDragMove.vehicle.stockNumber;
    setPendingDragMove(null);
    setDraggedStock(null);
    setDragOverStage(null);
    setDragMoveNote("");
    window.requestAnimationFrame(() => vehicleCardRefs.current[stockToRestore]?.focus());
  };
  const cancelDragMove = () => {
    const stockToRestore = pendingDragMove?.vehicle.stockNumber;
    setPendingDragMove(null);
    setDraggedStock(null);
    setDragOverStage(null);
    setDragMoveNote("");
    setBoardAnnouncement("Vehicle move cancelled.");
    if (stockToRestore) {
      window.requestAnimationFrame(() => vehicleCardRefs.current[stockToRestore]?.focus());
    }
  };
  const resolvePendingDragBlocker = () => {
    if (!pendingDragMove) return;
    const vehicle = pendingDragMove.vehicle;
    const resolvedVehicle: FlowVehicle = {
      ...vehicle,
      blockerTitle: undefined,
      needsAttention: false,
      slaState: "On track",
      status: vehicle.status === "Waiting on part" ? "In progress" : vehicle.status,
      event: "Blocker resolved"
    };
    setStageOverrides((current) => ({
      ...current,
      [vehicle.stockNumber]: createStageOverride(vehicle, vehicle.currentStage, "Blocker resolved", {
        status: resolvedVehicle.status,
        responsibleTeam: vehicle.responsibleTeam,
        assignedTo: vehicle.assignedTo ?? getAssigneeForTeam(vehicle.responsibleTeam).name,
        timeInStage: vehicle.timeInStage,
        notificationState: vehicle.notificationState,
        slaState: "On track",
        needsAttention: false,
        blockerTitle: undefined,
        contactState: "Blocker resolved",
        unreadReply: false
      })
    }));
    addTimelineEvent(vehicle.stockNumber, {
      id: `${vehicle.stockNumber}-drag-blocker-resolved-${Date.now()}`,
      stockNumber: vehicle.stockNumber,
      type: "blocker",
      title: "Blocker resolved",
      body: "Blocker resolved before stage movement.",
      meta: `Resolved by ${managerName} · Today, 2:40 PM`,
      source: "Manual"
    });
    setPendingDragMove({
      ...pendingDragMove,
      vehicle: resolvedVehicle
    });
    setBoardAnnouncement(`Blocker resolved for ${vehicle.stockNumber}. Confirm the move when ready.`);
  };
  const handleCardDragStart = (event: ReactDragEvent<HTMLButtonElement>, vehicle: FlowVehicle) => {
    if (!dragEnabled) return;
    event.dataTransfer.effectAllowed = "move";
    event.dataTransfer.setData("text/plain", vehicle.stockNumber);
    setDraggedStock(vehicle.stockNumber);
    setBoardAnnouncement(
      `${vehicle.stockNumber} picked up. Valid destinations are New Arrival, Mechanical, Detail, Final Imagery, and Listed.`
    );
  };
  const handleCardDragEnd = () => {
    setDraggedStock(null);
    setDragOverStage(null);
  };
  const handleLaneDragOver = (event: ReactDragEvent<HTMLElement>, stageId: FlowStageId) => {
    if (!dragEnabled || !draggedStock) return;
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";
    setDragOverStage(stageId);
  };
  const handleLaneDrop = (event: ReactDragEvent<HTMLElement>, destinationStage: FlowStageId) => {
    event.preventDefault();
    if (!dragEnabled) return;
    const stockNumber = event.dataTransfer.getData("text/plain") || draggedStock;
    const vehicle = boardRows.find((item) => item.stockNumber === stockNumber);
    setDragOverStage(null);
    setDraggedStock(null);
    if (!vehicle || vehicle.currentStage === destinationStage) {
      setBoardAnnouncement("Vehicle returned to its original lane.");
      return;
    }
    setPendingDragMove({
      destinationStage,
      sourceStage: vehicle.currentStage,
      vehicle
    });
    setDragMoveNote("");
    setBoardAnnouncement(
      `${vehicle.stockNumber} dropped on ${boardStageLabels[destinationStage]}. Confirm the move to update the board.`
    );
  };
  const startNudge = () => {
    if (!selectedBoardVehicle) return;
    const recipient = selectedBoardVehicle.assignedTo
      ? {
          ...selectedOwner,
          name: selectedBoardVehicle.assignedTo
        }
      : selectedOwner;
    setNudgeMessage(
      selectedBoardVehicle.currentStage === "imagery"
        ? `${selectedBoardVehicle.stockNumber} is ready for final imagery. Please open the Halo task and begin capture when available.`
        : selectedBoardVehicle.needsAttention
          ? `${selectedBoardVehicle.stockNumber} is approaching its workflow SLA. Please reply with the current status or any blocker.`
          : `Can you please provide an update on stock ${selectedBoardVehicle.stockNumber}? Reply here if anything is blocking the next stage.`
    );
    setSendState("idle");
    setNudgeComposerOpen(true);
    setReplyAnnouncement("");
    setBlockerDraft("Waiting for centre cap installation");
    setStageOverrides((current) => ({
      ...current,
      [selectedBoardVehicle.stockNumber]: createStageOverride(
        selectedBoardVehicle,
        selectedBoardVehicle.currentStage,
        selectedBoardVehicle.event ?? "Vehicle update requested",
        {
          status: selectedBoardVehicle.status,
          responsibleTeam: selectedBoardVehicle.responsibleTeam,
          assignedTo: recipient.name,
          needsAttention: selectedBoardVehicle.needsAttention,
          notificationState: selectedBoardVehicle.notificationState,
          slaState: selectedBoardVehicle.slaState,
          timeInStage: selectedBoardVehicle.timeInStage,
          contactState: `Draft SMS to ${recipient.name}`,
          blockerTitle: selectedBoardVehicle.blockerTitle,
          unreadReply: selectedBoardVehicle.unreadReply
        }
      )
    }));
  };
  const sendNudge = () => {
    if (!selectedBoardVehicle || !nudgeMessage.trim()) return;
    const recipientName = selectedBoardVehicle.assignedTo ?? selectedOwner.name;
    setSendState("sending");
    addTimelineEvent(selectedBoardVehicle.stockNumber, {
      id: `${selectedBoardVehicle.stockNumber}-sms-out-${Date.now()}`,
      stockNumber: selectedBoardVehicle.stockNumber,
      type: "sms-out",
      title: `SMS sent to ${recipientName}`,
      body: nudgeMessage.trim(),
      meta: `Sending · Sent by ${managerName} · Today, 2:18 PM`,
      source: "SMS"
    });

    window.setTimeout(() => {
      setSendState("delivered");
      setNudgeComposerOpen(false);
      setStageOverrides((current) => {
        const currentOverride = current[selectedBoardVehicle.stockNumber];
        return {
          ...current,
          [selectedBoardVehicle.stockNumber]: {
            ...(currentOverride ??
              createStageOverride(
                selectedBoardVehicle,
                selectedBoardVehicle.currentStage,
                selectedBoardVehicle.event ?? ""
              )),
            contactState: "Nudged just now",
            notificationState: "sent",
            event: `SMS delivered to ${recipientName}`
          }
        };
      });
      addTimelineEvent(selectedBoardVehicle.stockNumber, {
        id: `${selectedBoardVehicle.stockNumber}-sms-delivered-${Date.now()}`,
        stockNumber: selectedBoardVehicle.stockNumber,
        type: "sms-out",
        title: `SMS delivered to ${recipientName}`,
        body: nudgeMessage.trim(),
        meta: `Delivered · Sent by ${managerName} · Today, 2:18 PM`,
        source: "SMS"
      });

      window.setTimeout(() => {
        const reply = "Sorry, we are waiting for a center cap that needs installing.";
        setReplyAnnouncement(`Reply received from ${recipientName}.`);
        setStageOverrides((current) => {
          const currentOverride = current[selectedBoardVehicle.stockNumber];
          return {
            ...current,
            [selectedBoardVehicle.stockNumber]: {
              ...(currentOverride ??
                createStageOverride(
                  selectedBoardVehicle,
                  selectedBoardVehicle.currentStage,
                  selectedBoardVehicle.event ?? ""
                )),
              contactState: "Reply received · 2m",
              unreadReply: true,
              event: "Reply received"
            }
          };
        });
        addTimelineEvent(selectedBoardVehicle.stockNumber, {
          id: `${selectedBoardVehicle.stockNumber}-sms-in-${Date.now()}`,
          stockNumber: selectedBoardVehicle.stockNumber,
          type: "sms-in",
          title: `Reply from ${recipientName} · ${selectedBoardVehicle.responsibleTeam}`,
          body: reply,
          meta: "SMS · Today, 2:23 PM",
          source: "SMS",
          unread: true,
          actionable: "blocker"
        });
      }, 1200);
    }, 700);
  };
  const markAsBlocker = () => {
    if (!selectedBoardVehicle) return;
    const title = blockerDraft.trim() || "Waiting for centre cap installation";
    setStageOverrides((current) => ({
      ...current,
      [selectedBoardVehicle.stockNumber]: createStageOverride(
        selectedBoardVehicle,
        selectedBoardVehicle.currentStage,
        "Waiting on part",
        {
          status: "Waiting on part",
          responsibleTeam: selectedBoardVehicle.responsibleTeam,
          assignedTo: selectedBoardVehicle.assignedTo ?? selectedOwner.name,
          timeInStage: selectedBoardVehicle.timeInStage,
          notificationState: selectedBoardVehicle.notificationState,
          slaState: "At risk",
          needsAttention: true,
          blockerTitle: title,
          contactState: "Blocker created",
          unreadReply: false
        }
      )
    }));
    addTimelineEvent(selectedBoardVehicle.stockNumber, {
      id: `${selectedBoardVehicle.stockNumber}-blocker-${Date.now()}`,
      stockNumber: selectedBoardVehicle.stockNumber,
      type: "blocker",
      title: "Blocker created",
      body: title,
      meta: `Created by ${managerName} · Today, 2:25 PM`,
      source: "Manual"
    });
  };
  const resolveBlocker = () => {
    if (!selectedBoardVehicle) return;
    setStageOverrides((current) => ({
      ...current,
      [selectedBoardVehicle.stockNumber]: createStageOverride(
        selectedBoardVehicle,
        selectedBoardVehicle.currentStage,
        "Blocker resolved",
        {
          status: "In progress",
          responsibleTeam: selectedBoardVehicle.responsibleTeam,
          assignedTo: selectedBoardVehicle.assignedTo ?? selectedOwner.name,
          timeInStage: "Just now",
          notificationState: selectedBoardVehicle.notificationState,
          slaState: "On track",
          needsAttention: false,
          contactState: "Blocker resolved",
          blockerTitle: undefined,
          unreadReply: false
        }
      )
    }));
    addTimelineEvent(selectedBoardVehicle.stockNumber, {
      id: `${selectedBoardVehicle.stockNumber}-blocker-resolved-${Date.now()}`,
      stockNumber: selectedBoardVehicle.stockNumber,
      type: "blocker",
      title: "Blocker resolved",
      body: "Vehicle can continue through the workflow.",
      meta: `Resolved by ${managerName} · Today, 2:29 PM`,
      source: "Manual"
    });
  };
  const closeVehicleDrawer = () => {
    const stockToRestore = selectedVehicleStock;
    setSelectedVehicleStock(null);
    setConfirmationMode(null);
    setNudgeComposerOpen(false);
    if (stockToRestore) {
      window.requestAnimationFrame(() => vehicleCardRefs.current[stockToRestore]?.focus());
    }
  };
  const getRecommendedAction = (vehicle: FlowVehicle | undefined) => {
    if (!vehicle) return "";
    if (vehicle.currentStage === "listed") return "No action required. Monitor listing health.";
    if (vehicle.stockNumber === heroVehicle.stockNumber)
      return "Monitor capture start and listing readiness.";
    if (vehicle.needsAttention) return "Review the waiting stage and assign the next responsible owner.";
    return "Continue monitoring stage movement and SLA timing.";
  };
  const activeFilterCount =
    (stageFilter !== "all" ? 1 : 0) + (ownerFilter !== "all" ? 1 : 0) + (slaFilter !== "all" ? 1 : 0);
  const trapDrawerFocus = (event: ReactKeyboardEvent<HTMLElement>) => {
    if (event.key !== "Tab") return;
    const focusable = Array.from(
      event.currentTarget.querySelectorAll<HTMLElement>(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      )
    ).filter((element) => !element.hasAttribute("disabled"));
    const first = focusable[0];
    const last = focusable[focusable.length - 1];
    if (!first || !last) return;
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  };
  const resetFilters = () => {
    setBoardSearch("");
    setStageFilter("all");
    setOwnerFilter("all");
    setSlaFilter("all");
    setDensity("comfortable");
  };
  const readyForImagery = board.imagery.length;
  const attentionCount = boardRows.filter((vehicle) => vehicle.needsAttention).length;
  return (
    <section className={styles.section} id="halo-flows">
      <div className={styles.opening}>
        <HaloEyebrow>HALO FLOWS · LIVE VEHICLE OPERATIONS</HaloEyebrow>
        <h2 className="sectionTitle">Replace the whiteboard with a live handoff for every vehicle.</h2>
        <div className={styles.body}>
          <p>
            Getting a vehicle online is a live chain of dealership jobs. A salesperson parks the trade.
            Service finishes mechanical reconditioning. Detail prepares it. Merchandising starts capture. The
            people and shifts change, while most stores still rely on a whiteboard because their core systems
            do not move the next person forward in real time.
          </p>
          <p>
            Halo Flows is the orchestration layer around that chain. At the vehicle, each person scans the VIN
            and marks their work complete. Halo advances the next stage, sends the next person the exact job
            and gives managers a live view of what is moving, waiting or blocked. Halo&apos;s core pipeline
            then handles the image job from guided capture through processing and delivery.
          </p>
        </div>
        <ol className={styles.handoffChain} aria-label="Live dealership vehicle handoff">
          {handoffStages.map(([owner, status], index) => (
            <li data-pipeline={index === handoffStages.length - 1 ? "true" : "false"} key={owner}>
              <span>{owner}</span>
              <strong>{status}</strong>
            </li>
          ))}
        </ol>
        <p className={styles.signature}>Scan the VIN. Mark the job done. Halo moves it forward.</p>
      </div>

      <div className={styles.productStory}>
        <div className={styles.productSticky} ref={productStickyRef}>
          <div className={styles.demoStack}>
            <button
              className={styles.mobileActiveStepHeader}
              onClick={() => activateStep(displayedStepIndex, "click")}
              ref={mobileActiveStepHeaderRef}
              type="button"
            >
              <span>
                <strong>{String(displayedStepIndex + 1).padStart(2, "0")}</strong>
                {activeStep.title}
              </span>
              <p>{activeStep.body}</p>
            </button>
            <div
              className={styles.phoneShell}
              data-step={displayedStepIndex}
              style={{ "--mobile-phone-scale": phonePresentationScale } as CSSProperties}
              aria-label="Halo Flows mobile vehicle workflow detail view"
            >
              <div className={styles.phoneScale}>
                <HaloPhoneFrame
                  className={styles.flowsPhoneFrame}
                  mode={
                    captureOpened
                      ? "capture"
                      : browserOpened
                        ? "browser"
                        : notificationSent
                          ? "messages"
                          : "app"
                  }
                  style={{ "--halo-phone-width": `${PHONE_DESIGN_WIDTH}px` } as CSSProperties}
                  time={topChromeTime}
                >
                  <main
                    key={`${activeStep.id}-${replayVersion}`}
                    className={styles.appScreen}
                    data-mode={captureOpened ? "capture" : notificationSent ? "messages" : "flows"}
                    data-screen={activeScreen}
                    data-step={displayedStepIndex}
                  >
                    {!notificationSent ? (
                      <HaloMobileShell
                        activeNav={vehicleIdentified ? "tasks" : "scan"}
                        dealership="Downtown Motors"
                        leading={!vehicleIdentified ? "capture" : undefined}
                        mode={vehicleIdentified ? "focused" : "full"}
                        onCapture={() => {
                          if (!vehicleIdentified) {
                            resetStepExperience(0);
                            activeStepIndexRef.current = 0;
                            setActiveStepIndex(0);
                          } else {
                            setCaptureLaunchOpen(true);
                          }
                        }}
                        showBottomNav={showWorkflowBottomNav}
                        subtitle={vehicleIdentified ? "Detail" : "Downtown Motors"}
                        title={vehicleIdentified ? `${heroVehicle.stockNumber} · Urus` : "Identify Vehicle"}
                      >
                        {!vehicleIdentified ? (
                          <>
                            <div className={styles.vinIdentification}>
                              <HaloMobileScannerViewport
                                guidance={vinReviewReady ? "review" : "scanning"}
                                imageSrc="/product/vin-plate.png"
                                state={vinReviewReady ? "found" : vinScanStarted ? "scanning" : "idle"}
                                statusText={vinReviewReady ? "VIN captured" : undefined}
                              />
                              <HaloMobileVinVerificationControl
                                autoPopulate={vinScanStarted}
                                instantPopulate={reduceVinMotion}
                                onConfirm={() => {
                                  setVinConfirmed(true);
                                }}
                                onReadyChange={setVinReviewReady}
                                recognizedVin={heroVehicle.vin}
                                resetKey={vinResetKey}
                              />
                            </div>
                          </>
                        ) : (
                          <>
                            <HaloMobileVehicleHandoffSummary
                              stockNumber={heroVehicle.stockNumber}
                              vehicle={`${heroVehicle.year} ${heroVehicle.make} ${heroVehicle.model}`}
                            />

                            {captureLaunchOpen ? (
                              <HaloMobileCaptureLaunchSheet
                                mode={detailComplete ? "ready" : "not-ready"}
                                stockNumber={heroVehicle.stockNumber}
                                vehicle={`${heroVehicle.year} ${heroVehicle.make} ${heroVehicle.model}`}
                                vin={heroVehicle.vin}
                              />
                            ) : null}

                            <HaloMobileDetailCompletion
                              complete={notificationQueued}
                              onComplete={completeDetailAction}
                              processing={detailActionProcessing}
                            />
                          </>
                        )}
                      </HaloMobileShell>
                    ) : !browserOpened ? (
                      <section className={styles.messagesApp} aria-label="SMS from Halo">
                        <div className={styles.messagesHeader}>
                          <button type="button" aria-label="Back to conversations">
                            <HaloIcon name="chevronLeft" size="lg" />
                          </button>
                          <div className={styles.senderIdentity}>
                            <Image
                              alt=""
                              aria-hidden="true"
                              height={512}
                              src="/brand/halo-app-icon_512.png"
                              width={512}
                            />
                            <strong>Halo</strong>
                            <span>iMessage</span>
                          </div>
                          <span aria-hidden="true" />
                        </div>
                        <div className={styles.messagesThread}>
                          <time>Today 2:07 PM</time>
                          <div className={styles.messageBubble}>
                            <p>
                              Stock #9217 is ready for final imagery.
                              <br />
                              2019 Lamborghini Urus
                              <br />
                              Downtown Motors
                            </p>
                          </div>
                          <time>Today 2:11 PM</time>
                          <div className={styles.messageBubble}>
                            <p>
                              Your capture task is ready.
                              <br />
                              <a href="#halo-flows" onClick={(event) => event.preventDefault()}>
                                halocompass.com/c/7DF82
                              </a>
                            </p>
                          </div>
                          <span className={styles.messageStatus}>Delivered</span>
                        </div>
                        <div className={styles.messageComposer} aria-hidden="true">
                          <span>iMessage</span>
                        </div>
                      </section>
                    ) : !captureOpened ? (
                      <section className={styles.browserLaunch} aria-label="Halo Capture opened in browser">
                        <header className={styles.captureLaunchHeader}>
                          <div>
                            <strong>Halo Capture</strong>
                            <span>Secure task</span>
                          </div>
                          <span>
                            <HaloIcon name="check" size="xs" />
                            Offline ready
                          </span>
                        </header>
                        <div className={styles.captureLaunchBody}>
                          <section className={styles.captureVehicleRow} aria-label="Vehicle task loaded">
                            <Image
                              alt=""
                              aria-hidden="true"
                              height={900}
                              src="/product/lambo-image.png"
                              width={1600}
                            />
                            <div>
                              <span>{heroVehicle.stockNumber}</span>
                              <strong>{`${heroVehicle.year} ${heroVehicle.make} ${heroVehicle.model}`}</strong>
                              <small>Final Imagery · VIN ending {heroVehicle.vin.slice(-4)}</small>
                            </div>
                          </section>
                          <span className={styles.captureTaskMeta}>
                            <span aria-hidden="true" />
                            Final Imagery task
                          </span>
                          <section className={styles.captureLaunchTask}>
                            <h3>Ready for final imagery</h3>
                            <p>
                              Detail is complete.
                              <br />
                              Capture the required listing views for this vehicle.
                            </p>
                          </section>
                          <span className={styles.captureTrustRow}>
                            <HaloIcon name="check" size="xs" />
                            Secure task verified
                          </span>
                          <HaloMobileButton fullWidth onClick={() => setCaptureStartedFromLaunch(true)}>
                            Begin Guided Capture
                          </HaloMobileButton>
                          <div className={styles.captureUtility}>
                            <button className={styles.captureProblemAction} type="button">
                              Report a problem
                            </button>
                            <p className={styles.captureSecurityNote}>
                              <HaloIcon name="lock" size="xs" />
                              This secure task is assigned to this vehicle. Please confirm the vehicle before
                              capture.
                            </p>
                            <Image
                              alt=""
                              aria-hidden="true"
                              className={styles.captureWatermark}
                              height={192}
                              src="/brand/halo-watermark.png"
                              width={471}
                            />
                          </div>
                        </div>
                      </section>
                    ) : (
                      <section
                        className={styles.captureTask}
                        aria-label="Halo Guided Capture task opened from SMS"
                      >
                        <Image
                          alt="Halo Guided Capture interface for final imagery"
                          className={styles.captureScreenshot}
                          height={2622}
                          src="/product/halo-ui-real.png"
                          width={1206}
                        />
                      </section>
                    )}
                  </main>
                </HaloPhoneFrame>
              </div>
            </div>
            <div
              className={styles.mobileStoryControls}
              aria-label="Halo Flows mobile step indicators"
              ref={mobileStoryControlsRef}
            >
              <span>
                {displayedStepIndex + 1} / {flowSteps.length}
              </span>
              <div>
                {flowSteps.map((step, index) => (
                  <button
                    aria-label={`Show ${step.title}`}
                    aria-current={index === displayedStepIndex ? "step" : undefined}
                    data-active={index === displayedStepIndex ? "true" : "false"}
                    key={step.id}
                    onClick={() => activateStep(index, "click")}
                    type="button"
                  />
                ))}
              </div>
            </div>
          </div>
        </div>

        <div
          className={styles.storySteps}
          aria-label="Halo Flows live workflow sequence"
          onScroll={handleMobileStoryScroll}
          ref={storyStepsRef}
        >
          {flowSteps.map((step, index) => (
            <button
              aria-current={index === displayedStepIndex ? "step" : undefined}
              className={styles.storyStepCard}
              data-state={
                index === displayedStepIndex
                  ? "current"
                  : activeStepIndex !== null && index < displayedStepIndex
                    ? "complete"
                    : "upcoming"
              }
              data-step-index={index}
              key={step.id}
              onClick={() => activateStep(index, "click")}
              onKeyDown={(event) => {
                if (event.key !== "Enter" && event.key !== " ") return;
                event.preventDefault();
                activateStep(index, "keyboard");
              }}
              ref={(node) => {
                stepRefs.current[index] = node;
              }}
              type="button"
            >
              <span>{String(index + 1).padStart(2, "0")}</span>
              <h3>{step.title}</h3>
              <p>{step.body}</p>
              {index === 3 ? <strong>Receive the task. Tap the link. Begin the work.</strong> : null}
            </button>
          ))}
        </div>
      </div>

      <div
        className={styles.boardStory}
        data-advanced={boardAdvanced}
        data-board-phase={boardWorkflowPhase}
        ref={boardStoryRef}
      >
        <div className={styles.boardIntro}>
          <div>
            <span className={styles.boardLabel}>HALO FLOW BOARD</span>
            <h3>Every vehicle. Every stage. Live.</h3>
            <p>
              Each completed handoff updates the Halo Flow Board in real time. No one has to wait for the
              whiteboard to be checked or for another system to be updated later. Every department can see
              what is finished, what comes next, who has been notified and which vehicles need attention.
            </p>
          </div>
          <div className={styles.boardMetrics} aria-label="Halo Flow Board summary">
            <span>
              <strong>38</strong> active vehicles
            </span>
            <span>
              <strong>7</strong> ready for detail
            </span>
            <span>
              <strong>{readyForImagery}</strong> awaiting final imagery
            </span>
            <span>
              <strong>2</strong> need attention
            </span>
          </div>
        </div>

        <p className={styles.boardHelper} data-visible={showBoardHint ? "true" : "false"}>
          Click any vehicle to inspect its live workflow.
        </p>

        <div className={styles.flowBoard} aria-label="Downtown Motors Halo Operations Board">
          <div className={styles.prismShell} data-sidebar={sidebarCollapsed ? "collapsed" : "expanded"}>
            <aside className={styles.prismSidebar} aria-label="Operations Board navigation">
              <button
                aria-label={sidebarCollapsed ? "Expand navigation" : "Collapse navigation"}
                aria-expanded={!sidebarCollapsed}
                className={styles.sidebarToggle}
                onClick={() => setSidebarCollapsed((collapsed) => !collapsed)}
                title={sidebarCollapsed ? "Expand navigation" : "Collapse navigation"}
                type="button"
              >
                <HaloIcon name={sidebarCollapsed ? "chevronRight" : "chevronLeft"} />
              </button>
              <div className={styles.prismBrand}>
                <Image
                  alt="Halo"
                  className={styles.prismWordmark}
                  height={72}
                  src="/brand/halo-prism-wordmark-light.svg"
                  width={174}
                />
                <Image
                  alt="Halo"
                  className={styles.prismIconMark}
                  height={100}
                  src="/brand/halo-prism-icon-light.svg"
                  width={77}
                />
              </div>
              <nav className={styles.prismNav}>
                {prismNavigation.map((item) => (
                  <button
                    aria-current={item.label === "Workflows" ? "page" : undefined}
                    className={item.label === "Workflows" ? styles.activeNavItem : ""}
                    key={item.label}
                    title={`${item.label} · ${item.meta}`}
                    type="button"
                  >
                    <HaloIcon name={item.icon} />
                    <span>{item.label}</span>
                    <small>{item.meta}</small>
                  </button>
                ))}
              </nav>
              <div className={styles.prismSidebarPanel}>
                <span>Today</span>
                <strong>{boardRows.length}</strong>
                <small>vehicles in merchandising flow</small>
              </div>
            </aside>

            <div className={styles.prismWorkspace}>
              <div className={styles.mobilePrismHeader}>
                <Image alt="Halo" height={100} src="/brand/halo-prism-icon-light.svg" width={77} />
                <div>
                  <strong>Workflows</strong>
                  <span>Downtown Motors</span>
                </div>
                <button
                  aria-label="Open navigation"
                  onClick={() => setMobileMenuOpen(true)}
                  ref={mobileMenuButtonRef}
                  type="button"
                >
                  <HaloIcon name="menu" />
                </button>
              </div>
              <div className={styles.prismCommandBar} aria-label="Operations Board command bar">
                <label className={styles.prismSearch}>
                  <HaloIcon name="search" />
                  <input
                    aria-label="Search by stock number, VIN, vehicle, stage, or owner"
                    onChange={(event) => setBoardSearch(event.target.value)}
                    placeholder="Search stock, VIN, stage, or owner"
                    type="search"
                    value={boardSearch}
                  />
                </label>
                <PrismSelect
                  ariaLabel="Rooftop selector"
                  className={styles.desktopOnlyControl}
                  defaultValue="Downtown Motors"
                  label="Rooftop"
                  leadingIcon="pin"
                  options={rooftopOptions}
                  width="rooftop"
                />
                <PrismSelect
                  ariaLabel="Workflow selector"
                  className={styles.desktopOnlyControl}
                  defaultValue="Merchandising"
                  label="Workflow"
                  leadingIcon="route"
                  options={workflowOptions}
                  width="workflow"
                />
                <PrismSelect
                  ariaLabel="Period selector"
                  className={styles.desktopOnlyControl}
                  defaultValue="Today"
                  label="Period"
                  leadingIcon="calendar"
                  options={periodOptions}
                  width="period"
                />
                <span className={styles.liveIndicator}>Live</span>
              </div>

              <main className={styles.prismContent}>
                <section className={styles.prismMain}>
                  <div className={styles.prismPanel}>
                    <div className={styles.prismPanelHeader}>
                      <div>
                        <h4>Operations Board</h4>
                        <p>Vehicles moving through merchandising in real time.</p>
                      </div>
                    </div>

                    <div className={styles.prismKpis} aria-label="Operations Board summary">
                      <article data-focus="true">
                        <strong>{readyForImagery}</strong>
                        <span>Ready for imagery</span>
                      </article>
                      <article>
                        <strong>{attentionCount}</strong>
                        <span>At risk</span>
                      </article>
                      <article>
                        <strong>{board.listed.length}</strong>
                        <span>Listed today</span>
                      </article>
                    </div>
                  </div>

                  <section className={styles.prismPanel}>
                    <div className={styles.prismToolbar}>
                      <div>
                        <h5>Board</h5>
                      </div>
                      <div className={styles.prismFilters}>
                        <PrismSelect
                          ariaLabel="Filter by workflow stage"
                          className={styles.desktopOnlyControl}
                          label="Stage"
                          leadingIcon="filter"
                          onChange={(value) => setStageFilter(value as FlowStageId | "all")}
                          options={stageFilterOptions}
                          value={stageFilter}
                          width="medium"
                        />
                        <PrismSelect
                          ariaLabel="Filter by owner"
                          className={styles.desktopOnlyControl}
                          label="Owner"
                          leadingIcon="car"
                          onChange={setOwnerFilter}
                          options={ownerFilterOptions}
                          value={ownerFilter}
                          width="medium"
                        />
                        <PrismSelect
                          ariaLabel="Filter by SLA"
                          className={styles.desktopOnlyControl}
                          label="SLA"
                          leadingIcon="alert"
                          onChange={(value) => setSlaFilter(value as SlaState | "all")}
                          options={slaFilterOptions}
                          value={slaFilter}
                          width="medium"
                        />
                        <div className={styles.segmentedControl} aria-label="View control">
                          <button
                            aria-pressed={boardView === "board"}
                            onClick={() => setBoardView("board")}
                            type="button"
                          >
                            <HaloIcon name="board" />
                            Board
                          </button>
                          <button
                            aria-pressed={boardView === "table"}
                            onClick={() => setBoardView("table")}
                            type="button"
                          >
                            <HaloIcon name="list" />
                            Table
                          </button>
                        </div>
                        <div className={styles.segmentedControl} aria-label="Density control">
                          <button
                            aria-pressed={density === "comfortable"}
                            onClick={() => setDensity("comfortable")}
                            type="button"
                          >
                            <HaloIcon name="sliders" />
                            Comfortable
                          </button>
                          <button
                            aria-pressed={density === "compact"}
                            onClick={() => setDensity("compact")}
                            type="button"
                          >
                            <HaloIcon name="sliders" />
                            Compact
                          </button>
                        </div>
                        <button
                          aria-label={`Open filters${activeFilterCount ? `, ${activeFilterCount} active` : ""}`}
                          className={styles.mobileFilterButton}
                          onClick={() => setMobileFiltersOpen(true)}
                          ref={mobileFilterButtonRef}
                          type="button"
                        >
                          <HaloIcon name="filter" />
                          Filters {activeFilterCount ? `(${activeFilterCount})` : ""}
                        </button>
                      </div>
                    </div>
                    {boardView === "board" ? (
                      <div className={styles.kanbanScroller} data-density={density}>
                        <div className={styles.mobileStageTabs} aria-label="Workflow stages">
                          {workflowStages.map((stage) => (
                            <button
                              aria-current={mobileStage === stage.id ? "true" : undefined}
                              key={`mobile-stage-${stage.id}`}
                              onClick={() => setMobileStage(stage.id)}
                              type="button"
                            >
                              {stage.id === "arrival"
                                ? "Arrival"
                                : stage.id === "imagery"
                                  ? "Imagery"
                                  : stage.label}
                              <span>{filteredBoard[stage.id].length}</span>
                            </button>
                          ))}
                        </div>
                        <div className={styles.kanbanBoard} aria-label="Vehicle workflow Kanban board">
                          {workflowStages.map((stage) => {
                            const vehicles = filteredBoard[stage.id];
                            return (
                              <section
                                aria-label={`${stage.label}, ${vehicles.length} vehicles`}
                                className={styles.kanbanLane}
                                data-drag-over={dragOverStage === stage.id}
                                data-dragging={Boolean(draggedStock)}
                                data-mobile-active={mobileStage === stage.id}
                                key={`lane-${stage.id}`}
                                onDragLeave={(event) => {
                                  if (event.currentTarget.contains(event.relatedTarget as Node)) return;
                                  setDragOverStage(null);
                                }}
                                onDragOver={(event) => handleLaneDragOver(event, stage.id)}
                                onDrop={(event) => handleLaneDrop(event, stage.id)}
                              >
                                <div className={styles.laneHeader}>
                                  <div>
                                    <h6>{stage.label}</h6>
                                    <span>{stage.team}</span>
                                  </div>
                                  <strong aria-label={`${vehicles.length} vehicles`}>
                                    {vehicles.length}
                                  </strong>
                                </div>
                                <div className={styles.laneCards}>
                                  {vehicles.map((vehicle) => {
                                    const observations = vehicleObservations(vehicle);
                                    return (
                                      <button
                                        aria-pressed={selectedVehicleStock === vehicle.stockNumber}
                                        className={styles.vehicleCard}
                                        data-owner={vehicle.responsibleTeam}
                                        draggable={dragEnabled}
                                        data-dragging={draggedStock === vehicle.stockNumber}
                                        data-draggable={dragEnabled}
                                        data-featured={vehicle.stockNumber === heroVehicle.stockNumber}
                                        data-selected={selectedVehicleStock === vehicle.stockNumber}
                                        data-sla={boardSlaLabel(vehicle)}
                                        key={`card-${vehicle.stockNumber}`}
                                        onClick={() => {
                                          handleBoardInteraction();
                                          setSelectedVehicleStock(vehicle.stockNumber);
                                        }}
                                        onDragEnd={handleCardDragEnd}
                                        onDragStart={(event) => handleCardDragStart(event, vehicle)}
                                        ref={(node) => {
                                          vehicleCardRefs.current[vehicle.stockNumber] = node;
                                        }}
                                        type="button"
                                      >
                                        <span className={styles.cardTop}>
                                          <span className={styles.cardMeta}>{vehicle.stockNumber}</span>
                                          <span className={styles.prismSla} data-sla={boardSlaLabel(vehicle)}>
                                            {boardSlaLabel(vehicle)}
                                          </span>
                                        </span>
                                        <strong>
                                          {vehicle.year} {vehicle.make} {vehicle.model}
                                        </strong>
                                        <span
                                          className={styles.prismStatus}
                                          data-status={boardStatusTone(vehicle, boardAdvanced)}
                                        >
                                          {boardStatusLabel(vehicle, boardAdvanced, boardWorkflowPhase)}
                                        </span>
                                        {observations.length ? (
                                          <span className={styles.cardObservation}>Vehicle Observations</span>
                                        ) : null}
                                        <span className={styles.cardFooterRow}>
                                          <span className={styles.cardTime}>{vehicle.timeInStage}</span>
                                          <span
                                            className={styles.cardOwner}
                                            data-card-owner
                                            title={vehicle.responsibleTeam}
                                          >
                                            {vehicle.responsibleTeam}
                                          </span>
                                        </span>
                                        {vehicle.blockerTitle || vehicle.contactState || vehicle.event ? (
                                          <span className={styles.cardFooter}>
                                            {vehicle.blockerTitle ? (
                                              <em data-priority="high">Blocked · {vehicle.blockerTitle}</em>
                                            ) : null}
                                            {vehicle.contactState ? (
                                              <em data-priority={vehicle.unreadReply ? "high" : "normal"}>
                                                {vehicle.contactState}
                                              </em>
                                            ) : null}
                                            {vehicle.event ? <em>{vehicle.event}</em> : null}
                                          </span>
                                        ) : null}
                                      </button>
                                    );
                                  })}
                                  {vehicles.length === 0 ? (
                                    <p className={styles.emptyLane}>No vehicles match these filters.</p>
                                  ) : null}
                                </div>
                                {board[stage.id].length > vehicles.length ? (
                                  <p className={styles.laneFooter}>
                                    {board[stage.id].length - vehicles.length} hidden by filters
                                  </p>
                                ) : stage.id === "listed" && board[stage.id].length > 3 ? (
                                  <button className={styles.laneFooterAction} type="button">
                                    View all listed
                                  </button>
                                ) : null}
                              </section>
                            );
                          })}
                        </div>
                      </div>
                    ) : (
                      <div className={styles.prismTableWrap}>
                        <table className={styles.prismTable}>
                          <thead>
                            <tr>
                              <th>Vehicle</th>
                              <th>Stage</th>
                              <th>Status</th>
                              <th>Owner</th>
                              <th>Age</th>
                              <th>SLA</th>
                            </tr>
                          </thead>
                          <tbody>
                            {filteredRows.map((vehicle) => (
                              <tr
                                data-featured={vehicle.stockNumber === heroVehicle.stockNumber}
                                key={`row-${vehicle.stockNumber}`}
                                onClick={() => {
                                  handleBoardInteraction();
                                  setSelectedVehicleStock(vehicle.stockNumber);
                                }}
                              >
                                <td>
                                  <strong>{vehicle.stockNumber}</strong>
                                  <span>
                                    {vehicle.year} {vehicle.make} {vehicle.model}
                                  </span>
                                </td>
                                <td>{boardStageLabels[vehicle.currentStage]}</td>
                                <td>
                                  <span
                                    className={styles.prismStatus}
                                    data-status={boardStatusTone(vehicle, boardAdvanced)}
                                  >
                                    {boardStatusLabel(vehicle, boardAdvanced, boardWorkflowPhase)}
                                  </span>
                                </td>
                                <td>{vehicle.responsibleTeam}</td>
                                <td>{vehicle.timeInStage}</td>
                                <td>
                                  <span className={styles.prismSla} data-sla={boardSlaLabel(vehicle)}>
                                    {boardSlaLabel(vehicle)}
                                  </span>
                                  {vehicle.contactState ? <span>{vehicle.contactState}</span> : null}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </section>
                </section>

                <p className={styles.srOnly} aria-live="polite">
                  {boardAnnouncement}
                </p>

                {pendingDragMove ? (
                  <div className={styles.dragConfirmLayer} role="presentation" onMouseDown={cancelDragMove}>
                    <aside
                      aria-labelledby="drag-confirm-title"
                      aria-modal="true"
                      className={styles.dragConfirm}
                      onKeyDown={trapDrawerFocus}
                      onMouseDown={(event) => event.stopPropagation()}
                      role="dialog"
                    >
                      <div>
                        <span>Confirm stage move</span>
                        <strong id="drag-confirm-title">
                          Move {pendingDragMove.vehicle.stockNumber} to{" "}
                          {boardStageLabels[pendingDragMove.destinationStage]}?
                        </strong>
                      </div>
                      <dl>
                        <div>
                          <dt>Current stage</dt>
                          <dd>{boardStageLabels[pendingDragMove.sourceStage]}</dd>
                        </div>
                        <div>
                          <dt>Destination</dt>
                          <dd>{boardStageLabels[pendingDragMove.destinationStage]}</dd>
                        </div>
                        <div>
                          <dt>Next owner</dt>
                          <dd>{getStageTeam(pendingDragMove.destinationStage)}</dd>
                        </div>
                      </dl>
                      {isNonSequentialDragMove(pendingDragMove) ? (
                        <p className={styles.dragWarning}>
                          This move skips or reverses expected workflow stages. A reason is required and will
                          be recorded on the vehicle timeline.
                        </p>
                      ) : (
                        <p>
                          This will mark {boardStageLabels[pendingDragMove.sourceStage]} complete, assign{" "}
                          {getStageTeam(pendingDragMove.destinationStage)}, update the board, and record the
                          stage change.
                        </p>
                      )}
                      {isBlockedForwardDragMove(pendingDragMove) ? (
                        <div className={styles.dragBlocker}>
                          <strong>This vehicle is blocked</strong>
                          <p>{pendingDragMove.vehicle.blockerTitle}</p>
                          <button onClick={resolvePendingDragBlocker} type="button">
                            Resolve blocker first
                          </button>
                        </div>
                      ) : null}
                      <label>
                        {isNonSequentialDragMove(pendingDragMove) || isBlockedForwardDragMove(pendingDragMove)
                          ? "Reason required"
                          : "Optional handoff note"}
                        <textarea
                          onChange={(event) => setDragMoveNote(event.target.value)}
                          placeholder={
                            isNonSequentialDragMove(pendingDragMove)
                              ? "Explain why this vehicle should move outside the expected sequence"
                              : "Add a note about the handoff"
                          }
                          value={dragMoveNote}
                        />
                      </label>
                      <div className={styles.confirmActions}>
                        <button onClick={cancelDragMove} type="button">
                          Cancel
                        </button>
                        <button
                          disabled={
                            (isNonSequentialDragMove(pendingDragMove) ||
                              isBlockedForwardDragMove(pendingDragMove)) &&
                            !dragMoveNote.trim()
                          }
                          onClick={confirmDragMove}
                          type="button"
                        >
                          {isBlockedForwardDragMove(pendingDragMove) ? "Override and move" : "Move vehicle"}
                        </button>
                      </div>
                    </aside>
                  </div>
                ) : null}

                {mobileMenuOpen ? (
                  <div
                    className={styles.mobileOverlay}
                    onMouseDown={() => {
                      setMobileMenuOpen(false);
                      window.requestAnimationFrame(() => mobileMenuButtonRef.current?.focus());
                    }}
                    role="presentation"
                  >
                    <aside
                      aria-label="Mobile navigation"
                      aria-modal="true"
                      className={styles.mobileNavDrawer}
                      onMouseDown={(event) => event.stopPropagation()}
                      onKeyDown={trapDrawerFocus}
                      role="dialog"
                    >
                      <div className={styles.mobileDrawerHead}>
                        <Image
                          alt="Halo"
                          height={72}
                          src="/brand/halo-prism-wordmark-light.svg"
                          width={174}
                        />
                        <button
                          aria-label="Close navigation"
                          onClick={() => {
                            setMobileMenuOpen(false);
                            window.requestAnimationFrame(() => mobileMenuButtonRef.current?.focus());
                          }}
                          ref={mobileMenuCloseRef}
                          type="button"
                        >
                          <HaloIcon name="x" />
                        </button>
                      </div>
                      <nav className={styles.mobileDrawerNav}>
                        {prismNavigation.map((item) => (
                          <button
                            aria-current={item.label === "Workflows" ? "page" : undefined}
                            key={`mobile-nav-${item.label}`}
                            type="button"
                          >
                            <HaloIcon name={item.icon} />
                            <span>{item.label}</span>
                            <small>{item.meta}</small>
                          </button>
                        ))}
                      </nav>
                      <p>Downtown Motors · Merchandising workflow</p>
                    </aside>
                  </div>
                ) : null}

                {mobileFiltersOpen ? (
                  <div
                    className={styles.mobileOverlay}
                    onMouseDown={() => {
                      setMobileFiltersOpen(false);
                      window.requestAnimationFrame(() => mobileFilterButtonRef.current?.focus());
                    }}
                    role="presentation"
                  >
                    <aside
                      aria-label="Mobile filters"
                      aria-modal="true"
                      className={styles.mobileFilterSheet}
                      onMouseDown={(event) => event.stopPropagation()}
                      onKeyDown={trapDrawerFocus}
                      role="dialog"
                    >
                      <div className={styles.mobileSheetHead}>
                        <div>
                          <span>Filters</span>
                          <strong>Operations Board</strong>
                        </div>
                        <button
                          aria-label="Close filters"
                          onClick={() => {
                            setMobileFiltersOpen(false);
                            window.requestAnimationFrame(() => mobileFilterButtonRef.current?.focus());
                          }}
                          ref={mobileFilterCloseRef}
                          type="button"
                        >
                          <HaloIcon name="x" />
                        </button>
                      </div>
                      <div className={styles.mobileSheetFields}>
                        <PrismSelect
                          ariaLabel="Filter by workflow stage"
                          label="Stage"
                          onChange={(value) => setStageFilter(value as FlowStageId | "all")}
                          options={stageFilterOptions}
                          size="standard"
                          value={stageFilter}
                          width="full"
                        />
                        <PrismSelect
                          ariaLabel="Filter by owner"
                          label="Owner"
                          onChange={setOwnerFilter}
                          options={ownerFilterOptions}
                          size="standard"
                          value={ownerFilter}
                          width="full"
                        />
                        <PrismSelect
                          ariaLabel="Filter by SLA"
                          label="SLA"
                          onChange={(value) => setSlaFilter(value as SlaState | "all")}
                          options={slaFilterOptions}
                          size="standard"
                          value={slaFilter}
                          width="full"
                        />
                        <PrismSelect
                          ariaLabel="Board density"
                          label="Density"
                          onChange={(value) => setDensity(value as "comfortable" | "compact")}
                          options={densityOptions}
                          size="standard"
                          value={density}
                          width="full"
                        />
                      </div>
                      <div className={styles.mobileSheetActions}>
                        <button onClick={resetFilters} type="button">
                          Reset
                        </button>
                        <button
                          onClick={() => {
                            setMobileFiltersOpen(false);
                            window.requestAnimationFrame(() => mobileFilterButtonRef.current?.focus());
                          }}
                          type="button"
                        >
                          Apply filters
                        </button>
                      </div>
                    </aside>
                  </div>
                ) : null}

                {selectedBoardVehicle ? (
                  <div className={styles.drawerLayer} role="presentation" onMouseDown={closeVehicleDrawer}>
                    <aside
                      aria-labelledby="vehicle-detail-title"
                      aria-modal="true"
                      className={styles.prismInspector}
                      onKeyDown={trapDrawerFocus}
                      onMouseDown={(event) => event.stopPropagation()}
                      role="dialog"
                    >
                      <div className={styles.inspectorHead}>
                        <div>
                          <span>Selected vehicle</span>
                          <strong id="vehicle-detail-title">{selectedBoardVehicle.stockNumber}</strong>
                          <small>
                            {selectedBoardVehicle.year} {selectedBoardVehicle.make}{" "}
                            {selectedBoardVehicle.model}
                          </small>
                          <small>
                            Current stage: {boardStageLabels[selectedBoardVehicle.currentStage]} · Status:{" "}
                            {boardStatusLabel(selectedBoardVehicle, boardAdvanced, boardWorkflowPhase)} · SLA:{" "}
                            {selectedBoardVehicle.slaState}
                          </small>
                        </div>
                        <button
                          aria-label="Close vehicle details"
                          className={styles.drawerClose}
                          onClick={closeVehicleDrawer}
                          ref={drawerCloseRef}
                          type="button"
                        >
                          <HaloIcon name="x" />
                        </button>
                      </div>
                      <div className={styles.inspectorScroll}>
                        <div className={styles.inspectorMetrics}>
                          <article>
                            <span>Current stage</span>
                            <strong>{boardStageLabels[selectedBoardVehicle.currentStage]}</strong>
                          </article>
                          <article>
                            <span>Status</span>
                            <strong>
                              {boardStatusLabel(selectedBoardVehicle, boardAdvanced, boardWorkflowPhase)}
                            </strong>
                          </article>
                          <article>
                            <span>Current owner</span>
                            <strong>{selectedBoardVehicle.responsibleTeam}</strong>
                          </article>
                          <article>
                            <span>Assigned to</span>
                            <strong>{selectedBoardVehicle.assignedTo ?? selectedOwner.name}</strong>
                          </article>
                          <article>
                            <span>Next owner</span>
                            <strong>{selectedNextStage ? selectedNextOwner.role : "Complete"}</strong>
                          </article>
                          <article>
                            <span>Time in stage</span>
                            <strong>{selectedBoardVehicle.timeInStage}</strong>
                          </article>
                        </div>

                        <section className={styles.inspectorSection} aria-labelledby="workflow-action-title">
                          <span id="workflow-action-title">Primary workflow action</span>
                          <p>{getRecommendedAction(selectedBoardVehicle)}</p>
                          {selectedNextStage ? (
                            <button
                              className={styles.inspectorAction}
                              onClick={() => openStageConfirmation("next", selectedNextStage)}
                              type="button"
                            >
                              Move to {boardStageLabels[selectedNextStage]}
                            </button>
                          ) : (
                            <p className={styles.resolvedState}>Workflow complete</p>
                          )}
                          <button
                            className={styles.inspectorSecondaryAction}
                            onClick={() => openStageConfirmation("change", selectedBoardVehicle.currentStage)}
                            type="button"
                          >
                            Change stage
                          </button>
                          {confirmationMode ? (
                            <div
                              className={styles.confirmPanel}
                              role="group"
                              aria-label="Confirm stage change"
                            >
                              <strong>
                                {confirmationMode === "next"
                                  ? `Move ${selectedBoardVehicle.stockNumber} to ${selectedNextStage ? boardStageLabels[selectedNextStage] : "next stage"}?`
                                  : `Change ${selectedBoardVehicle.stockNumber} stage?`}
                              </strong>
                              {confirmationMode === "change" ? (
                                <PrismSelect
                                  ariaLabel="Destination stage"
                                  label="Destination stage"
                                  onChange={(value) => setManualStage(value as FlowStageId)}
                                  options={workflowStages.map((stage) => ({
                                    value: stage.id,
                                    label: stage.label
                                  }))}
                                  size="standard"
                                  value={manualStage}
                                  width="full"
                                />
                              ) : null}
                              <dl>
                                <div>
                                  <dt>Current stage</dt>
                                  <dd>{boardStageLabels[selectedBoardVehicle.currentStage]}</dd>
                                </div>
                                <div>
                                  <dt>Destination</dt>
                                  <dd>
                                    {
                                      boardStageLabels[
                                        confirmationMode === "next" && selectedNextStage
                                          ? selectedNextStage
                                          : manualStage
                                      ]
                                    }
                                  </dd>
                                </div>
                                <div>
                                  <dt>Next owner</dt>
                                  <dd>
                                    {
                                      getAssigneeForTeam(
                                        getStageTeam(
                                          confirmationMode === "next" && selectedNextStage
                                            ? selectedNextStage
                                            : manualStage
                                        )
                                      ).role
                                    }
                                  </dd>
                                </div>
                              </dl>
                              <p>
                                This will update the Operations Board, reset time in stage, assign the next
                                owner, and record the change on the vehicle timeline.
                              </p>
                              <label>
                                {confirmationMode === "change" && manualStage !== selectedNextStage
                                  ? "Reason for correction"
                                  : "Optional note"}
                                <textarea
                                  onChange={(event) => setActionNote(event.target.value)}
                                  placeholder="Add a note about the handoff"
                                  value={actionNote}
                                />
                              </label>
                              <div className={styles.confirmActions}>
                                <button onClick={() => setConfirmationMode(null)} type="button">
                                  Cancel
                                </button>
                                <button
                                  disabled={
                                    confirmationMode === "change" &&
                                    manualStage !== selectedNextStage &&
                                    !actionNote.trim()
                                  }
                                  onClick={confirmStageMove}
                                  type="button"
                                >
                                  Move vehicle
                                </button>
                              </div>
                            </div>
                          ) : null}
                        </section>

                        <section className={styles.inspectorSection} aria-labelledby="communication-title">
                          <span id="communication-title">Ownership and communication</span>
                          <div className={styles.ownerGrid}>
                            <article>
                              <small>Current owner</small>
                              <strong>{selectedBoardVehicle.responsibleTeam}</strong>
                            </article>
                            <article>
                              <small>Assigned to</small>
                              <strong>{selectedBoardVehicle.assignedTo ?? selectedOwner.name}</strong>
                            </article>
                            <article>
                              <small>Next owner</small>
                              <strong>{selectedNextStage ? selectedNextOwner.role : "Manager"}</strong>
                            </article>
                          </div>
                          {selectedBoardVehicle.contactState ? (
                            <p className={styles.contactState}>{selectedBoardVehicle.contactState}</p>
                          ) : null}
                          <button
                            className={styles.inspectorSecondaryAction}
                            onClick={startNudge}
                            type="button"
                          >
                            Nudge {selectedBoardVehicle.assignedTo ?? selectedOwner.name}
                          </button>
                          {nudgeComposerOpen ? (
                            <div className={styles.smsComposer} aria-live="polite">
                              <strong>Nudge {selectedBoardVehicle.assignedTo ?? selectedOwner.name}</strong>
                              <p>
                                {selectedBoardVehicle.responsibleTeam} · Mobile ending in{" "}
                                {selectedOwner.mobile}
                              </p>
                              <small>
                                Vehicle: {selectedBoardVehicle.stockNumber} · {selectedBoardVehicle.year}{" "}
                                {selectedBoardVehicle.make} {selectedBoardVehicle.model}
                              </small>
                              <label>
                                Message
                                <textarea
                                  onChange={(event) => setNudgeMessage(event.target.value)}
                                  value={nudgeMessage}
                                />
                              </label>
                              <div className={styles.suggestionRow}>
                                {[
                                  "Can you please provide an update?",
                                  "Please complete the current stage when ready.",
                                  "Reply here if anything is blocking it."
                                ].map((suggestion) => (
                                  <button
                                    key={suggestion}
                                    onClick={() =>
                                      setNudgeMessage(
                                        `${suggestion} Stock ${selectedBoardVehicle.stockNumber}.`
                                      )
                                    }
                                    type="button"
                                  >
                                    {suggestion}
                                  </button>
                                ))}
                              </div>
                              <div className={styles.confirmActions}>
                                <button onClick={() => setNudgeComposerOpen(false)} type="button">
                                  Cancel
                                </button>
                                <button
                                  disabled={!nudgeMessage.trim() || sendState === "sending"}
                                  onClick={sendNudge}
                                  type="button"
                                >
                                  {sendState === "sending" ? "Sending" : "Send SMS"}
                                </button>
                              </div>
                            </div>
                          ) : null}
                          {sendState === "delivered" ? (
                            <p className={styles.contactState}>SMS delivered. Waiting for reply.</p>
                          ) : null}
                          <p className={styles.srOnly} aria-live="polite">
                            {replyAnnouncement}
                          </p>
                        </section>

                        {selectedObservations.length ? (
                          <section
                            className={styles.inspectorSection}
                            aria-labelledby="vehicle-observations-title"
                          >
                            <span id="vehicle-observations-title">Vehicle Observations</span>
                            <div className={styles.observationList}>
                              {selectedObservations.map((observation) => (
                                <p key={observation}>
                                  <i aria-hidden="true" />
                                  {observation}
                                </p>
                              ))}
                            </div>
                          </section>
                        ) : null}

                        {selectedBoardVehicle.blockerTitle ||
                        selectedTimeline.some((event) => event.actionable) ? (
                          <section className={styles.inspectorSection} aria-labelledby="blockers-title">
                            <span id="blockers-title">Blockers and notes</span>
                            {selectedBoardVehicle.blockerTitle ? (
                              <>
                                <p className={styles.blockerState}>{selectedBoardVehicle.blockerTitle}</p>
                                <button
                                  className={styles.inspectorSecondaryAction}
                                  onClick={resolveBlocker}
                                  type="button"
                                >
                                  Resolve blocker
                                </button>
                              </>
                            ) : (
                              <>
                                <label>
                                  Blocker title
                                  <input
                                    onChange={(event) => setBlockerDraft(event.target.value)}
                                    value={blockerDraft}
                                  />
                                </label>
                                <button
                                  className={styles.inspectorSecondaryAction}
                                  onClick={markAsBlocker}
                                  type="button"
                                >
                                  Mark as blocker
                                </button>
                              </>
                            )}
                          </section>
                        ) : null}

                        <section
                          className={styles.inspectorSection}
                          aria-labelledby="workflow-progress-title"
                        >
                          <span id="workflow-progress-title">Workflow progression</span>
                          <div className={styles.inspectorTimeline}>
                            {workflowStages.map((stage) => {
                              const selectedStageIndex = workflowStages.findIndex(
                                (item) => item.id === selectedBoardVehicle.currentStage
                              );
                              const stageIndex = workflowStages.findIndex((item) => item.id === stage.id);
                              const state =
                                stageIndex < selectedStageIndex
                                  ? "complete"
                                  : stageIndex === selectedStageIndex
                                    ? "active"
                                    : "pending";
                              return (
                                <span data-state={state} key={`timeline-${stage.id}`}>
                                  {stage.label} ·{" "}
                                  {state === "complete"
                                    ? "Complete"
                                    : state === "active"
                                      ? "Active"
                                      : "Pending"}
                                </span>
                              );
                            })}
                          </div>
                        </section>

                        <section className={styles.inspectorSection} aria-labelledby="activity-title">
                          <span id="activity-title">Activity and SMS conversation</span>
                          <div className={styles.activityTimeline}>
                            {selectedTimeline.map((event) => (
                              <article data-type={event.type} key={event.id}>
                                <div>
                                  <strong>{event.title}</strong>
                                  <small>
                                    {event.meta} · {event.source}
                                  </small>
                                </div>
                                <p>
                                  {event.type === "sms-in" || event.type === "sms-out"
                                    ? `“${event.body}”`
                                    : event.body}
                                </p>
                                {event.actionable === "blocker" && !selectedBoardVehicle.blockerTitle ? (
                                  <button onClick={markAsBlocker} type="button">
                                    Mark as blocker
                                  </button>
                                ) : null}
                              </article>
                            ))}
                          </div>
                        </section>
                      </div>
                    </aside>
                  </div>
                ) : null}
              </main>
            </div>
          </div>
        </div>

        <div className={styles.workflowClose}>
          <h3>The handoff happens at the vehicle.</h3>
          <p>
            Each participant uses the phone already in their hand. The job stays with the VIN, the next person
            is prompted and managers see the work move forward while the store is operating.
          </p>
        </div>
      </div>

      <div className={styles.value}>
        <div>
          <h3>Halo Flows coordinates the people. Halo&apos;s pipeline handles the photos.</h3>
          <p>
            Flows does not add another image-processing handoff. It keeps the dealership&apos;s live
            operational steps connected to the VIN, then hands the vehicle into Halo&apos;s automated photo
            pipeline when it is ready for capture.
          </p>
        </div>
        <div className={styles.valueGrid}>
          {values.map(([title, body]) => (
            <article key={title}>
              <h4>{title}</h4>
              <p>{body}</p>
            </article>
          ))}
        </div>
      </div>

      <div className={styles.founding}>
        <div>
          <HaloEyebrow>FOUNDING DEALER MEMBERS</HaloEyebrow>
          <h3>Stay close to what Halo builds next.</h3>
          <p>
            Founding Dealer Members join a 24-month Design Partner Program. We start with Merchandising, learn
            from the way your group works, and use that experience to shape Appraisals, Reconditioning, and
            other dealership jobs.
          </p>
          <p>
            Every new Halo Flow introduced during the program is included at no additional software cost for
            those 24 months.
          </p>
        </div>
        <div className={styles.roadmap}>
          {roadmap.map(([title, status]) => (
            <article key={title}>
              <h4>{title}</h4>
              <p>{status}</p>
            </article>
          ))}
        </div>
        <aside className={styles.included}>
          <strong>Included with membership</strong>
          <p>
            Halo Flows · Merchandising is included from launch. Every additional Halo Flow introduced during
            the 24-month Design Partner Program is included at no additional software cost during the program.
          </p>
        </aside>
      </div>
    </section>
  );
}
