/**
 * Get Started Machine — React Hook + Context
 *
 * Provides the XState machine via React context so all child components
 * in the get-started flow share the same machine instance.
 *
 * Usage:
 *   // In parent (GetStartedView or InlineGetStartedSection):
 *   const machine = useGetStartedMachineRoot({ inline: true });
 *   <GetStartedMachineProvider value={machine}>...</GetStartedMachineProvider>
 *
 *   // In child (any step component):
 *   const { state, send } = useGetStartedMachine();
 */

"use client";

import { createContext, useContext } from "react";
import { useMachine } from "@xstate/react";
import { getStartedMachine } from "../machines/get-started.machine";
import type { ServiceContext } from "../machines/get-started.types";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MachineState = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MachineSend = any;

interface GetStartedMachineContextValue {
  state: MachineState;
  send: MachineSend;
}

const GetStartedMachineContext = createContext<GetStartedMachineContextValue | null>(null);

export const GetStartedMachineProvider = GetStartedMachineContext.Provider;

interface UseGetStartedMachineOptions {
  inline?: boolean | undefined;
  serviceContext?: ServiceContext | undefined;
}

/**
 * Create a new machine instance. Call once at the root of the flow.
 */
export function useGetStartedMachineRoot(options?: UseGetStartedMachineOptions) {
  const [state, send] = useMachine(getStartedMachine, {
    input: {
      inline: options?.inline,
      serviceContext: options?.serviceContext,
    },
  });

  return { state, send };
}

/**
 * Access the machine from context. Call in child step components.
 */
export function useGetStartedMachine(): GetStartedMachineContextValue {
  const ctx = useContext(GetStartedMachineContext);
  if (!ctx) {
    throw new Error("useGetStartedMachine must be used within GetStartedMachineProvider");
  }
  return ctx;
}
