/**
 * InsertrFormRenderer - Form renderer for content editing
 * Thin wrapper around the Editor system
 */
import { Editor } from './editor.js';

export class InsertrFormRenderer {
    constructor(apiClient = null) {
        this.apiClient = apiClient;
        this.editor = new Editor();
    }

    /**
     * Show edit form for any content element
     * @param {Object} meta - Element metadata {element, contentId, contentType}
     * @param {string|Object} currentContent - Current content value
     * @param {Function} onSave - Save callback
     * @param {Function} onCancel - Cancel callback
     */
    showEditForm(meta, currentContent, onSave, onCancel) {
        const { element } = meta;

        // Handle insertr-group elements by getting their viable children
        if (element.classList.contains('insertr-group')) {
            const children = this.getGroupChildren(element);
            const groupMeta = { ...meta, element: children };
            return this.editor.edit(groupMeta, currentContent, onSave, onCancel);
        }

        // All other elements use the editor directly
        return this.editor.edit(meta, currentContent, onSave, onCancel);
    }

    /**
     * Get viable children from group element
     */
    getGroupChildren(groupElement) {
        const children = [];
        for (const child of groupElement.children) {
            // Skip elements that don't have meaningful text content
            if (child.textContent.trim().length > 0) {
                children.push(child);
            }
        }
        return children;
    }

    /**
     * Close current form
     */
    closeForm() {
        this.editor.close();
    }


}