import { replaceVariables } from '@/lib/utils';
import { cleanText } from '@/lib/pdfTextUtils';

/**
 * Parses unified HTML content into structured segments for processing.
 * Wraps the HTML parsing logic used in PDF generation.
 */
export const parseUnifiedContent = (htmlContent) => {
    if (!htmlContent) return [];
    
    // Create a temporary DOM element to parse HTML
    const container = document.createElement('div');
    container.innerHTML = htmlContent;
    
    return Array.from(container.childNodes).map(node => {
        if (node.nodeType === Node.TEXT_NODE) {
            return { type: 'text', content: node.textContent };
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            const tagName = node.tagName.toLowerCase();
            if (tagName === 'ul' || tagName === 'ol') {
                return { 
                    type: 'list', 
                    ordered: tagName === 'ol', 
                    items: Array.from(node.children).map(li => ({
                         content: li.innerHTML,
                         indent: getIndentLevelFromClass(li.className)
                    }))
                };
            }
            // Add more parsing logic as needed
            return { type: 'element', tagName, content: node.innerHTML };
        }
        return null;
    }).filter(Boolean);
};

const getIndentLevelFromClass = (className) => {
    if (!className) return 0;
    const match = className.match(/ql-indent-(\d+)/);
    return match ? parseInt(match[1]) : 0;
};

/**
 * Calculates indentation style based on level (0-6)
 */
export const calculateIndentLevel = (level) => {
    const pixelsPerLevel = 32; // 2em approx
    return {
        paddingLeft: `${level * pixelsPerLevel}px`,
        marginLeft: 0 // ReactQuill uses padding for indent usually
    };
};

/**
 * Returns the CSS style for a specific bullet symbol based on depth/type
 */
export const getBulletSymbol = (depth, isOrdered) => {
    if (isOrdered) return 'decimal';
    
    // Cycle bullet types: disc -> circle -> square
    switch (depth % 3) {
        case 0: return 'disc';
        case 1: return 'circle';
        case 2: return 'square';
        default: return 'disc';
    }
};

/**
 * Validates formatting integrity
 */
export const validateFormattedContent = (content) => {
    if (typeof content !== 'string') return false;
    // Basic HTML validation checks if needed
    return true;
};