"use client";

import { useEffect, useRef, useState } from "react";

import {
  consumePendingChatPromotion,
  peekPendingChatUnlock,
} from "@/lib/navigation/chat_unlock_session";
import { useChatDispatch } from "@/stores/chat/chat-context";
import { Logger } from "@/utils/logger";

const log = new Logger("UseChatPromotionBootstrap");

export function useChatPromotionBootstrap(): boolean {
  const chatDispatch = useChatDispatch();
  const startedRef = useRef(false);
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    if (startedRef.current) return;
    startedRef.current = true;

    void (async () => {
      try {
        const [entryPromotion, pendingUnlock] = await Promise.all([
          consumePendingChatPromotion(),
          peekPendingChatUnlock(),
        ]);
        const promotion = entryPromotion ?? pendingUnlock?.promotion ?? null;

        if (promotion) {
          chatDispatch({
            type: "ChatPromotionInjected",
            promotion,
            messageId: pendingUnlock?.promotion
              ? pendingUnlock.messageId
              : undefined,
          });
        } else {
          chatDispatch({ type: "ChatPromotionCleared" });
        }
      } catch (error) {
        log.warn("Failed to restore chat promotion", error);
        chatDispatch({ type: "ChatPromotionCleared" });
      } finally {
        setIsReady(true);
      }
    })();
  }, [chatDispatch]);

  return isReady;
}
