// useCrossTabSync：跨标签同步 Hook
// 依据：02-architecture-design.md §4.4 跨标签同步
// - BroadcastChannel：同源标签间实时同步（首选）
// - storage 事件：降级方案（BroadcastChannel 不可用时）
// - 同步内容：子女切换 / 子女解绑 / 通知偏好更新
// - 防回环：消息携带 source，接收方忽略自己的消息

"use client";

import { useEffect } from "react";
import { useChildStore } from "@/store/child-store";
import type { SyncMessage } from "@/types";

const CHANNEL_NAME = "parent-sync";
const STORAGE_EVENT_KEY = "parent_sync_event";
const SOURCE_ID = `tab-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;

export function useCrossTabSync() {
  useEffect(() => {
    // 方案 1：BroadcastChannel（首选）
    let bc: BroadcastChannel | null = null;
    if ("BroadcastChannel" in window) {
      bc = new BroadcastChannel(CHANNEL_NAME);
      bc.onmessage = (event: MessageEvent<SyncMessage>) => {
        const msg = event.data;
        if (!msg || msg.source === SOURCE_ID) return; // 防回环

        switch (msg.type) {
          case "child-switched":
            // 同步子女切换（不广播，避免循环）
            useChildStore.setState({ currentChildId: msg.childId });
            break;
          case "child-unbound":
            // 子女解绑：刷新子女列表
            // 由各页面自行处理（useMyChildren 会重新请求）
            break;
          case "preferences-updated":
            // 通知偏好更新：清除 localStorage 缓存，触发重新加载
            localStorage.removeItem("parent_notification_preferences");
            break;
        }
      };
    }

    // 方案 2：storage 事件降级（BroadcastChannel 不可用时）
    function handleStorageEvent(e: StorageEvent) {
      if (e.key !== STORAGE_EVENT_KEY || !e.newValue) return;
      try {
        const msg = JSON.parse(e.newValue) as SyncMessage;
        if (msg.source === SOURCE_ID) return;

        switch (msg.type) {
          case "child-switched":
            useChildStore.setState({ currentChildId: msg.childId });
            break;
          case "child-unbound":
            break;
          case "preferences-updated":
            localStorage.removeItem("parent_notification_preferences");
            break;
        }
      } catch {
        // 忽略解析错误
      }
    }
    window.addEventListener("storage", handleStorageEvent);

    return () => {
      bc?.close();
      window.removeEventListener("storage", handleStorageEvent);
    };
  }, []);
}

// 导出 source ID 供其他模块广播时使用
export { SOURCE_ID as SYNC_SOURCE_ID };

// 广播跨标签消息（供 child-store / preference hook 使用）
export function broadcastSync(msg: Omit<SyncMessage, "source">) {
  const fullMsg: SyncMessage = { ...msg, source: SOURCE_ID } as SyncMessage;

  // BroadcastChannel
  if ("BroadcastChannel" in window) {
    const bc = new BroadcastChannel(CHANNEL_NAME);
    bc.postMessage(fullMsg);
    bc.close();
  }

  // storage 事件降级
  try {
    localStorage.setItem(STORAGE_EVENT_KEY, JSON.stringify(fullMsg));
    // 立即清除（storage 事件只在值变化时触发）
    setTimeout(() => localStorage.removeItem(STORAGE_EVENT_KEY), 0);
  } catch {
    // 忽略
  }
}
