// Zustand store：子女切换状态
// 依据：02-architecture-design.md §4.3 状态管理分层（Client Business 层）
// - ARB-020 §22.5 ISSUE-009 裁决：双层 switchChild
//   · 前端缓存层（本 store）：Zustand + localStorage + BroadcastChannel
//   · 后端审计层（hook 调 mutation）：parent-bff 写 Redis parent:selected:{parentId} TTL 30s
// - 本 store 的 switchChild 仅负责前端缓存更新，后端 mutation 由 useChildSwitcher hook 调用
// - 多子女切换：currentChildId 持久化到 localStorage
// - 跨标签同步：通过 BroadcastChannel 通知（P4-8 实现 hook，此处仅广播事件）

import { create } from "zustand";
import type { ChildInfo } from "@/types";

const CURRENT_CHILD_KEY = "parent_current_child_id";

// BroadcastChannel（跨标签同步，ISSUE-009 + P4-8）
let bc: BroadcastChannel | null = null;
if (typeof window !== "undefined" && "BroadcastChannel" in window) {
  bc = new BroadcastChannel("parent-sync");
}

interface ChildStoreState {
  children: ChildInfo[];
  currentChildId: string | null;
  isLoading: boolean;
  setChildren: (children: ChildInfo[]) => void;
  switchChild: (childId: string) => void;
  setLoading: (loading: boolean) => void;
  reset: () => void;
}

function loadCurrentChildId(): string | null {
  if (typeof window === "undefined") return null;
  return localStorage.getItem(CURRENT_CHILD_KEY);
}

function persistCurrentChildId(childId: string): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(CURRENT_CHILD_KEY, childId);
}

export const useChildStore = create<ChildStoreState>((set, get) => ({
  children: [],
  currentChildId: loadCurrentChildId(),
  isLoading: false,

  setChildren: (children) => {
    const currentId = get().currentChildId;
    // 若当前未选中或已选中的不在列表中，默认选第一个（非归档）
    const activeChildren = children.filter((c) => !c.isArchived);
    let nextCurrentId = currentId;
    if (!nextCurrentId || !children.some((c) => c.id === nextCurrentId)) {
      nextCurrentId = activeChildren[0]?.id ?? children[0]?.id ?? null;
      if (nextCurrentId) {
        persistCurrentChildId(nextCurrentId);
      }
    }
    set({ children, currentChildId: nextCurrentId });
  },

  // ARB-020 §22.5：前端缓存层（后端 mutation 由 useChildSwitcher hook 调用）
  switchChild: (childId) => {
    const exists = get().children.some((c) => c.id === childId);
    if (!exists) return;
    persistCurrentChildId(childId);
    set({ currentChildId: childId });

    // 广播跨标签同步事件（P4-8）
    bc?.postMessage({
      type: "child-switched",
      childId,
      ts: Date.now(),
      source: "unknown",
    });
  },

  setLoading: (isLoading) => set({ isLoading }),

  reset: () => {
    if (typeof window !== "undefined") {
      localStorage.removeItem(CURRENT_CHILD_KEY);
    }
    set({ children: [], currentChildId: null, isLoading: false });
  },
}));

// 监听跨标签同步（P4-8：接收其他标签的切换事件）
if (bc && typeof window !== "undefined") {
  bc.onmessage = (event) => {
    if (event.data?.type === "child-switched") {
      useChildStore.setState({ currentChildId: event.data.childId });
    }
  };
}
