import { v4 as uuidv4 } from 'uuid';

/**
 * Converts legacy block structure to section-based structure
 * Ensures every block has an indent level and title if missing.
 */
export const convertToSectionFormat = (blocks) => {
    if (!Array.isArray(blocks)) return [];
    
    return blocks.map(block => ({
        ...block,
        id: block.id || uuidv4(),
        indent: typeof block.indent === 'number' ? block.indent : 0,
        title: block.title || '',
        // Ensure content is string for text blocks, object for others remains
        content: block.content,
        // Map legacy types if necessary, keeping 'unified_text' as primary for rich text
        type: block.type || 'unified_text'
    }));
};

/**
 * Calculates hierarchical numbering for a section based on its position in the list
 * Returns string like "1.0", "1.1", "1.1.2", or "A", "B" depending on scheme
 */
export const getSectionNumbering = (blocks, currentIndex) => {
    const currentBlock = blocks[currentIndex];
    if (!currentBlock) return '';
    if (currentBlock.type === 'spacer' || currentBlock.type === 'image') return '';
    
    const counters = {}; // Key: indent level, Value: current count
    
    for (let i = 0; i <= currentIndex; i++) {
        const block = blocks[i];
        const level = block.indent || 0;
        
        // Reset deeper levels
        for (let l = level + 1; l <= 5; l++) {
            counters[l] = 0;
        }
        
        // Increment current level
        counters[level] = (counters[level] || 0) + 1;
    }
    
    // Construct label based on counters up to current level
    const parts = [];
    for (let l = 0; l <= (currentBlock.indent || 0); l++) {
        parts.push(counters[l] || 1);
    }
    
    return parts.join('.');
};

export const indentSection = (blocks, index) => {
    const newBlocks = [...blocks];
    const current = newBlocks[index];
    if (index > 0 && (current.indent || 0) < 5) {
        newBlocks[index] = { ...current, indent: (current.indent || 0) + 1 };
    }
    return newBlocks;
};

export const outdentSection = (blocks, index) => {
    const newBlocks = [...blocks];
    const current = newBlocks[index];
    if ((current.indent || 0) > 0) {
        newBlocks[index] = { ...current, indent: (current.indent || 0) - 1 };
    }
    return newBlocks;
};

export const reorderSections = (blocks, startIndex, endIndex) => {
    const result = Array.from(blocks);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);
    return result;
};

export const addSection = (blocks, type = 'unified_text', title = '') => {
    const newId = uuidv4();
    let content = '';

    // Initialize unified_text with a structured array containing a single plain text line
    // This ensures no automatic bullets are applied upon creation
    if (type === 'unified_text') {
        content = [{
            id: uuidv4(),
            type: 'text', 
            content: '',
            indent: 0,
            isBold: false
        }];
    } else if (type === 'unified_text_html') {
         // Fallback for html string if needed internally, though unlikely with this update
         content = '<p>New section content...</p>';
    }

    return [
        ...blocks,
        {
            id: newId,
            type,
            title,
            content,
            indent: 0,
            styles: {}
        }
    ];
};

export const deleteSection = (blocks, id) => {
    return blocks.filter(b => b.id !== id);
};