"use client";

import type { LoginStatus } from "@/data/dto/auth";
import type { ChatUpgradeReason } from "@/stores/chat/chat-state";
import { AppEnvUtil, BrowserDetector } from "@/utils";

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

export type InsufficientCreditsAction = "auth" | "topup";

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

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(
  loginStatus: LoginStatus,
): InsufficientCreditsMessageLimitView {
  if (loginStatus === "guest" || loginStatus === "notLoggedIn") {
    return {
      title: "Log in to get more free chats",
      description: "Free chats refresh every day.",
      ctaLabel: "Log in to continue",
      action: "auth",
    };
  }

  return {
    title: "Insufficient credits",
    description: "Free chats refresh every day.",
    ctaLabel: "Top up credits to continue",
    action: "topup",
  };
}

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

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

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