/**
 * Sidebar 状态机（XState v5）
 *
 * 原始 Dart: lib/ui/sidebar/bloc/sidebar bloc + sidebar state + sidebar event
 *
 * 设计要点：
 *   - XState v5 `setup({...}).createMachine({...})` 声明式 API
 *   - Sidebar 无异步副作用（纯 UI 状态），仅用 `assign` 处理
 *   - 保持事件类型名与原 Dart 一致
 *   - actions inline 在 setup() 中（确保类型推断正确）
 */
import { setup, assign } from "xstate";

import { BottomNavItem, SidebarState, initialState } from "./sidebar-state";
import type { SidebarEvent } from "./sidebar-events";

// 重新导出 State / Event 类型，保持 machine 文件的公共 API 不变
export type { SidebarState } from "./sidebar-state";
export { initialState } from "./sidebar-state";
export type { SidebarEvent } from "./sidebar-events";

// ============================================================
// Machine
// ============================================================
export const sidebarMachine = setup({
  types: {
    context: {} as SidebarState,
    events: {} as SidebarEvent,
  },
  actions: {
    showPage: assign(({ event }) => {
      if (event.type !== "SidebarShowPage") return {};
      return {
        currentPage: event.page,
        selectedBottomNavItem: event.bottomNavItem ?? BottomNavItem.None,
      };
    }),

    clearBottomNav: assign(() => ({
      selectedBottomNavItem: BottomNavItem.None,
    })),

    updateCharacter: assign(({ event }) => {
      if (event.type !== "SidebarUpdateCharacter") return {};
      return {
        characterName: event.name,
        characterProgress: event.progress,
      };
    }),
  },
}).createMachine({
  id: "sidebar",
  initial: "idle",
  context: initialState,
  states: {
    /**
     * Sidebar 是纯数据状态（无异步副作用），仅用 idle 状态
     * 所有事件均在 idle 状态内处理
     */
    idle: {
      on: {
        SidebarShowPage: {
          actions: "showPage",
        },
        SidebarClearBottomNav: {
          actions: "clearBottomNav",
        },
        SidebarUpdateCharacter: {
          actions: "updateCharacter",
        },
      },
    },
  },
});

export type SidebarMachine = typeof sidebarMachine;
