export function mergeBlockTexts(texts: string[]): string {
    return texts.join("\n\n");
}

export function computeSpanTargetStart(
    totalCount: number,
    sourceStartIndex: number,
    sourceEndIndex: number,
    insertionIndex: number
): number {
    if (totalCount <= 0) return 0;
    if (sourceStartIndex < 0 || sourceEndIndex < sourceStartIndex || sourceEndIndex >= totalCount) return sourceStartIndex;

    const movedCount = sourceEndIndex - sourceStartIndex + 1;
    const clampedInsertion = Math.max(0, Math.min(totalCount, insertionIndex));
    if (clampedInsertion >= sourceStartIndex && clampedInsertion <= sourceEndIndex + 1) return sourceStartIndex;
    return clampedInsertion <= sourceStartIndex ? clampedInsertion : clampedInsertion - movedCount;
}

export function moveContiguousSpan<T>(
    items: T[],
    sourceStartIndex: number,
    sourceEndIndex: number,
    insertionIndex: number
): { reordered: T[]; targetStart: number; changed: boolean } {
    if (items.length === 0) return { reordered: items, targetStart: 0, changed: false };
    if (sourceStartIndex < 0 || sourceEndIndex < sourceStartIndex || sourceEndIndex >= items.length) {
        return { reordered: items, targetStart: sourceStartIndex, changed: false };
    }

    const targetStart = computeSpanTargetStart(items.length, sourceStartIndex, sourceEndIndex, insertionIndex);
    if (targetStart === sourceStartIndex) {
        return { reordered: items, targetStart, changed: false };
    }

    const moved = items.slice(sourceStartIndex, sourceEndIndex + 1);
    const remaining = [...items.slice(0, sourceStartIndex), ...items.slice(sourceEndIndex + 1)];
    const reordered = [...remaining.slice(0, targetStart), ...moved, ...remaining.slice(targetStart)];
    return { reordered, targetStart, changed: true };
}

export function buildDropIndicatorText(insertionIndex: number, totalCount: number): string {
    const clamped = Math.max(0, Math.min(totalCount, insertionIndex));
    if (totalCount <= 0) return "将插入到文档开头";
    if (clamped >= totalCount) return "将插入到文档末尾";
    return `将插入到第 ${clamped + 1} 块之前`;
}
