import { MessageSegment } from '../../../types';
import { EditorBlock, TextBlock, ImageBlock, blockTextToSegments, generateBlockId } from './blockEditorTypes';

export function segmentsToBlocks(segments: MessageSegment[]): EditorBlock[] {
  if (!segments || segments.length === 0) return [];

  const blocks: EditorBlock[] = [];

  for (const seg of segments) {
    if (seg.type === 'image' && seg.data?.url) {
      const imageBlock: ImageBlock = {
        id: generateBlockId(),
        type: 'image',
        localUri: seg.data.url,
        remoteUrl: seg.data.url,
        uploading: false,
        width: seg.data.width,
        height: seg.data.height,
      };
      blocks.push(imageBlock);
    } else if (seg.type === 'text') {
      const text = seg.data?.text || seg.data?.content || '';
      if (text) {
        const textBlock: TextBlock = {
          id: generateBlockId(),
          type: 'text',
          text,
          activeMentions: new Map(),
        };
        blocks.push(textBlock);
      }
    }
    // Skip at/other segment types — mentions from long posts are not editable in block editor
  }

  // Ensure at least one text block
  if (blocks.length === 0) {
    blocks.push({ id: generateBlockId(), type: 'text', text: '', activeMentions: new Map() });
  }

  return blocks;
}

export function blocksToSegments(blocks: EditorBlock[]): MessageSegment[] {
  const segments: MessageSegment[] = [];

  for (const block of blocks) {
    if (block.type === 'text') {
      const textSegments = blockTextToSegments(block.text, block.activeMentions);
      segments.push(...textSegments);
    } else if (block.type === 'image') {
      if (block.remoteUrl) {
        segments.push({
          type: 'image',
          data: {
            url: block.remoteUrl,
            width: block.width,
            height: block.height,
          },
        });
      }
    }
  }

  return mergeAdjacentTextSegments(segments);
}

function mergeAdjacentTextSegments(segments: MessageSegment[]): MessageSegment[] {
  if (segments.length === 0) return segments;

  const merged: MessageSegment[] = [];

  for (const seg of segments) {
    const last = merged[merged.length - 1];
    if (
      last &&
      last.type === 'text' &&
      seg.type === 'text'
    ) {
      const lastText = last.data?.text || last.data?.content || '';
      const curText = seg.data?.text || seg.data?.content || '';
      last.data = { text: lastText + curText };
    } else {
      merged.push({ ...seg });
    }
  }

  return merged;
}

export function blocksToContent(blocks: EditorBlock[]): string {
  return blocks
    .filter((b): b is typeof b & { type: 'text' } => b.type === 'text')
    .map(b => b.text)
    .join('\n')
    .trim();
}