"use client";
import { ImageBubble } from "./image-bubble";
import { PrivateMessageCard } from "./private-message-card";
import { TextBubble } from "./text-bubble";
import { VoiceBubble } from "./voice-bubble";

export interface MessageContentProps {
  content: string;
  imageUrl?: string | null;
  imagePaywalled?: boolean;
  audioUrl?: string | null;
  messageId?: string;
  isFromAI: boolean;
  locked?: boolean | null;
  lockReason?: string | null;
  lockedPrivate?: boolean | null;
  privateMessageHint?: string | null;
  onUnlockPrivateMessage?: () => void;
  onUnlockVoiceMessage?: () => void;
}

const IMAGE_PLACEHOLDER = "[图片]";

export function MessageContent({
  content,
  imageUrl,
  imagePaywalled,
  audioUrl,
  messageId,
  isFromAI,
  locked,
  lockReason,
  lockedPrivate,
  privateMessageHint,
  onUnlockPrivateMessage,
  onUnlockVoiceMessage,
}: MessageContentProps) {
  const hasImage = imageUrl != null && imageUrl.length > 0;
  const hasAudio = audioUrl != null && audioUrl.length > 0;
  const hasText = content.length > 0 && content !== IMAGE_PLACEHOLDER;
  const isLockedPrivateMessage =
    lockedPrivate === true ||
    (locked === true && lockReason === "private_message");
  const isLockedVoiceMessage = locked === true && lockReason === "voice_message";

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        // 关键：在 row flex 父中撑开（不依赖 content 循环）—— 让 TextBubble 能拿到真实宽度
        flex: "1 1 0",
        // 防超长 content（图片 / 超长 url）撑爆父
        minWidth: 0,
        alignItems: isFromAI ? "flex-start" : "flex-end",
        gap: 8,
      }}
    >
      {isLockedPrivateMessage ? (
        <PrivateMessageCard
          hint={privateMessageHint}
          isUnlocking={false}
          onUnlock={onUnlockPrivateMessage}
        />
      ) : (
        <>
          {hasImage && imageUrl && (
            <ImageBubble
              messageId={messageId}
              imageUrl={imageUrl}
              imagePaywalled={imagePaywalled}
            />
          )}
          {hasAudio && audioUrl ? (
            <VoiceBubble
              messageId={messageId}
              audioUrl={audioUrl}
              isFromAI={isFromAI}
              locked={isLockedVoiceMessage}
              hint={privateMessageHint}
              isUnlocking={false}
              onUnlock={
                isLockedVoiceMessage
                  ? onUnlockVoiceMessage
                  : undefined
              }
            />
          ) : null}
          {hasText && !hasAudio ? (
            <TextBubble content={content} isFromAI={isFromAI} />
          ) : null}
        </>
      )}
    </div>
  );
}
