"use client";

import type { LoginStatus } from "@/data/schemas/auth";
import type { ChatUpgradeReason } from "@/stores/chat/chat-state";
import { AppEnvUtil } from "@/utils/app-env";
import { BrowserDetector } from "@/utils/browser-detect";

export interface ExternalBrowserPromptState {
  hasInitialized: boolean;
  isLoading: boolean;
  loginStatus: LoginStatus;
  isInAppBrowser?: boolean;
}

export interface InsufficientCreditsMessageLimitView {
  title: string;
  description: string;
  ctaLabel: string;
}

export interface MessageLimitBannerState {
  upgradePromptVisible: boolean;
  upgradeReason: ChatUpgradeReason | null;
}

export function deriveIsGuest(loginStatus: LoginStatus): boolean {
  return loginStatus === "guest";
}

export function shouldShowMessageLimitBanner({
  upgradePromptVisible,
  upgradeReason,
}: MessageLimitBannerState): boolean {
  return upgradePromptVisible && upgradeReason === "insufficient_credits";
}

export function getInsufficientCreditsMessageLimitView():
  InsufficientCreditsMessageLimitView {
  return {
    title: "Out of Daily Free Chats",
    description: "",
    ctaLabel: "Top up credits to continue",
  };
}

export function isChatDevelopmentEnvironment(): boolean {
  return AppEnvUtil.isDevelopment();
}

export function shouldStartExternalBrowserPrompt({
  hasInitialized,
  isLoading,
  loginStatus,
  isInAppBrowser = BrowserDetector.isInAppBrowser(),
}: ExternalBrowserPromptState): boolean {
  if (!hasInitialized || isLoading) return false;
  return (
    isChatDevelopmentEnvironment() ||
    (loginStatus === "facebook" && isInAppBrowser)
  );
}

export function getInsufficientCreditsSubscriptionType(
  isVip: boolean,
): "vip" | "topup" {
  return isVip ? "topup" : "vip";
}
