'use client';

/**
 * Renders room message content — markdown with @[type:id:label] mentions,
 * plus code-aware features: smart link previews and code references.
 */

import { memo, useMemo } from 'react';
import { ContentRenderer } from '@/components/shared/ContentRenderer';
import { LinkPreview } from '@/components/shared/LinkPreview';
import { CodeReference } from '@/components/shared/CodeReference';
import { extractUrls, detectLinkType, type UnfurlResult } from '@/lib/link-unfurl';
import { parseCodeRef, type CodeRef } from '@/lib/code-ref-parser';
import { cn } from '@/lib/utils';

interface MessageContentProps {
  content: string;
  onMentionClick?: (type: string, id: string, label: string) => void;
}

export const MessageContent = memo(function MessageContent({
  content,
  onMentionClick,
}: MessageContentProps) {
  // Extract standalone URLs for link preview rendering
  const urlResults = useMemo<UnfurlResult[]>(() => {
    const seen = new Set<string>();
    const results: UnfurlResult[] = [];
    for (const { url } of extractUrls(content)) {
      if (seen.has(url)) continue;
      const result = detectLinkType(url);
      if (result && !result.isExternal) {
        seen.add(url);
        results.push(result);
      }
    }
    return results;
  }, [content]);

  // Extract code references (file.rs:42 style)
  const codeRefs = useMemo<CodeRef[]>(() => {
    const seen = new Set<string>();
    const refs: CodeRef[] = [];
    const matches = content.match(/[^\s:]+:\d+(?:-\d+)?/g) ?? [];
    for (const match of matches) {
      if (seen.has(match)) continue;
      const parsed = parseCodeRef(match);
      if (parsed) {
        seen.add(match);
        refs.push(parsed);
      }
    }
    return refs;
  }, [content]);

  const hasLinkPreviews = urlResults.length > 0;
  const hasCodeRefs = codeRefs.length > 0;

  return (
    <div className={cn('space-y-2', !hasLinkPreviews && !hasCodeRefs && 'space-y-0')}>
      <ContentRenderer
        content={content}
        onMentionClick={onMentionClick}
      />

      {/* Code references */}
      {hasCodeRefs && (
        <div className="space-y-1">
          {codeRefs.map((ref, i) => (
            <CodeReference
              key={`ref-${i}-${ref.raw}`}
              ref={ref}
            />
          ))}
        </div>
      )}

      {/* Link previews */}
      {hasLinkPreviews && (
        <div className="space-y-1">
          {urlResults.map((result, i) => (
            <LinkPreview
              key={`link-${i}-${result.url}`}
              result={result}
            />
          ))}
        </div>
      )}
    </div>
  );
});
