"use client";

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

import {
  openChatInExternalBrowser,
  recordExternalBrowserPromptShown,
  resolveExternalBrowserPromptEligibility,
} from "@/lib/chat/chat_external_browser";

import {
  type ExternalBrowserPromptState,
  shouldStartExternalBrowserPrompt,
} from "../chat-screen.helpers";

const EXTERNAL_BROWSER_PROMPT_DELAY_MS = 3000;

export interface ExternalBrowserPromptController {
  open: boolean;
  close: () => void;
  confirm: () => Promise<void>;
}

export function useExternalBrowserPrompt({
  hasInitialized,
  isLoading,
  loginStatus,
}: ExternalBrowserPromptState): ExternalBrowserPromptController {
  const [open, setOpen] = useState(false);
  const promptShownRef = useRef(false);

  useEffect(() => {
    if (
      !shouldStartExternalBrowserPrompt({
        hasInitialized,
        isLoading,
        loginStatus,
      })
    ) {
      return;
    }

    let mounted = true;
    let timer: number | undefined;

    const init = async () => {
      if (promptShownRef.current) return;

      const eligibility = await resolveExternalBrowserPromptEligibility();
      if (!mounted || !eligibility.canShow) return;

      promptShownRef.current = true;
      timer = window.setTimeout(() => {
        if (!mounted) return;
        setOpen(true);
        void recordExternalBrowserPromptShown(eligibility.today);
      }, EXTERNAL_BROWSER_PROMPT_DELAY_MS);
    };

    void init();

    return () => {
      mounted = false;
      if (timer !== undefined) window.clearTimeout(timer);
    };
  }, [hasInitialized, isLoading, loginStatus]);

  const close = useCallback(() => {
    setOpen(false);
  }, []);

  const confirm = useCallback(async () => {
    setOpen(false);
    await openChatInExternalBrowser();
  }, []);

  return {
    open,
    close,
    confirm,
  };
}
