"use client";

/**
 * Payment → User 同步器
 *
 * 支付成功后刷新用户权益、清理套餐缓存，并消费首充标记。
 */
import { useEffect, useRef } from "react";
import { shallowEqual } from "@xstate/react";

import { useChatDispatch } from "@/stores/chat/chat-context";
import { useUserDispatch } from "@/stores/user/user-context";
import { hasPendingChatUnlock } from "@/lib/navigation/chat_unlock_session";
import {
  usePaymentDispatch,
  usePaymentSelector,
} from "@/stores/payment/payment-context";
import { getPaymentRepository } from "@/data/repositories/payment_repository";

export function PaymentSuccessSync() {
  const paymentState = usePaymentSelector(
    (state) => ({
      currentOrderId: state.context.currentOrderId,
      isPaid: state.matches("paid"),
      orderStatus: state.context.orderStatus,
    }),
    shallowEqual,
  );
  const paymentDispatch = usePaymentDispatch();
  const userDispatch = useUserDispatch();
  const lastPaidKeyRef = useRef<string | null>(null);

  useEffect(() => {
    if (!paymentState.isPaid || !paymentState.currentOrderId) return;

    const paidKey = `${paymentState.currentOrderId}:${paymentState.orderStatus}`;
    if (lastPaidKeyRef.current === paidKey) return;
    lastPaidKeyRef.current = paidKey;
    paymentDispatch({ type: "PaymentFirstRechargeConsumed" });

    const syncPaymentSuccess = async () => {
      await getPaymentRepository().clearCachedPlans();
      userDispatch({ type: "UserFetch" });
    };

    void syncPaymentSuccess();
  }, [
    paymentState.currentOrderId,
    paymentState.isPaid,
    paymentState.orderStatus,
    paymentDispatch,
    userDispatch,
  ]);

  return null;
}

/** Payment → Chat bridge, mounted only while the chat route is active. */
export function ChatPaymentSuccessSync() {
  const paymentState = usePaymentSelector(
    (state) => ({
      currentOrderId: state.context.currentOrderId,
      isPaid: state.matches("paid"),
      orderStatus: state.context.orderStatus,
    }),
    shallowEqual,
  );
  const chatDispatch = useChatDispatch();
  const lastPaidKeyRef = useRef<string | null>(null);

  useEffect(() => {
    if (!paymentState.isPaid || !paymentState.currentOrderId) return;

    const paidKey = `${paymentState.currentOrderId}:${paymentState.orderStatus}`;
    if (lastPaidKeyRef.current === paidKey) return;
    lastPaidKeyRef.current = paidKey;

    let cancelled = false;
    void (async () => {
      if (await hasPendingChatUnlock()) return;
      if (!cancelled) chatDispatch({ type: "ChatPaymentSucceeded" });
    })();

    return () => {
      cancelled = true;
    };
  }, [
    chatDispatch,
    paymentState.currentOrderId,
    paymentState.isPaid,
    paymentState.orderStatus,
  ]);

  return null;
}
