"use client";

import { useEffect } from "react";

import {
  dispatchPlayCatalogRefresh,
  type PlayCatalogRefreshSource,
} from "@/lib/play-catalog-events";
import { getLotteryEcho } from "@/lib/lottery-echo";

/**
 * 订阅大厅频道玩法目录相关 WS，触发 `lottery-play-catalog-refresh`。
 */
export function usePlayEffectiveWs(): void {
  useEffect(() => {
    const echo = getLotteryEcho();
    if (!echo) {
      return;
    }

    const channel = echo.channel("lottery-hall");

    const onRefresh = (source: PlayCatalogRefreshSource) => (): void => {
      dispatchPlayCatalogRefresh(source);
    };

    channel.listen(".play.toggle", onRefresh("play_toggle"));
    channel.listen(".odds.update", onRefresh("odds"));
    channel.listen(".play.catalog_updated", (payload: { module?: string }) => {
      const payloadModule = payload?.module;
      const source: PlayCatalogRefreshSource =
        payloadModule === "odds"
          ? "odds"
          : payloadModule === "risk_cap"
            ? "risk_cap"
            : "play_config";
      dispatchPlayCatalogRefresh(source);
    });

    return () => {
      channel.stopListening(".play.toggle");
      channel.stopListening(".odds.update");
      channel.stopListening(".play.catalog_updated");
    };
  }, []);
}
