window.ComponentRegistry = {
    definitions: {},
    
    // Alle Ordner sind jetzt beim Start geschlossen (open: false)

    folders: [
        { id: "kontakt",    name: "Kontakt",    open: false },
        { id: "sicherungen",name: "Sicherungen",open: false },
        { id: "verbraucher",name: "Verbraucher",open: false },
        { id: "klemmen",    name: "Klemmen",    open: false },
        { id: "elektronik", name: "Elektronik", open: false },
        { id: "custom",     name: "Eigene Bauteile", open: false }
    ],

    register: function(id, config) {
        this.definitions[id] = config;
    },

    loadCustomComponents: function() {
        const saved = localStorage.getItem('customComponents');
        if (saved) {
            try {
                const comps = JSON.parse(saved);
                comps.forEach(comp => {
                    this.register(comp.id, {
                        folder: comp.folder || 'custom',
                        title: comp.title,
                        svg: comp.svg,
                        defaultData: comp.defaultData || {},
                        isCustom: true // Unsichtbare Markierung für selbst erstellte Bauteile
                    });
                });
            } catch (e) {
                console.error(e);
            }
        }
    },

    buildSidebar: function() {
        this.loadCustomComponents();

        const area3 = document.getElementById('area-3');
        if (!area3) return;

        area3.innerHTML = '';
        
        const title = document.createElement('h2');
        title.textContent = 'Bauteile';
        area3.appendChild(title);

        this.folders.forEach(folder => {
            const itemsInFolder = Object.keys(this.definitions)
                .filter(key => this.definitions[key].folder === folder.id)
                .map(key => ({ id: key, ...this.definitions[key] }));

            if (itemsInFolder.length === 0) return;

            const folderDiv = document.createElement('div');
            folderDiv.className = `folder ${folder.open ? 'open' : ''}`;
            
            const header = document.createElement('div');
            header.className = 'folder-header';
            header.textContent = folder.name;
            folderDiv.appendChild(header);

            const content = document.createElement('div');
            content.className = 'folder-content';

            itemsInFolder.forEach(item => {
                const compDiv = document.createElement('div');
                compDiv.className = 'component-item';
                compDiv.draggable = true;
                compDiv.dataset.type = item.id;
                
                if (item.defaultData) {
                    for (const [key, val] of Object.entries(item.defaultData)) {
                        compDiv.dataset[key] = val;
                    }
                }
                
                if (item.title) compDiv.title = item.title;

                // Mülleimer nur generieren, wenn es ein selbst erstelltes Bauteil ist
                let deleteBtnHTML = '';
                if (item.isCustom) {
                    deleteBtnHTML = `<button class="delete-comp-btn" data-id="${item.id}" title="Eigenes Bauteil löschen" style="position: absolute; top: 5px; right: 32px; background: #ecf0f1; border: 1px solid #bdc3c7; border-radius: 3px; cursor: pointer; font-size: 12px; padding: 2px 5px; z-index: 10; color: #e74c3c;">🗑️</button>`;
                }

                compDiv.innerHTML = `
                    <button class="edit-comp-btn" title="Bauteil bearbeiten">✏️</button>
                    ${deleteBtnHTML}
                    ${item.svg}
                `;
                content.appendChild(compDiv);
            });

            folderDiv.appendChild(content);
            area3.appendChild(folderDiv);
        });

        if (typeof attachDragListeners === 'function') {
            attachDragListeners();
        }
    }
};

// Globaler Event-Listener für das Löschen von eigenen Bauteilen
document.addEventListener('click', (e) => {
    const deleteBtn = e.target.closest('.delete-comp-btn');
    if (deleteBtn) {
        e.stopPropagation();
        e.preventDefault();
        
        const compId = deleteBtn.dataset.id;
        
        if (confirm('Möchtest du dieses eigene Bauteil wirklich dauerhaft aus der Bibliothek löschen?')) {
            // 1. Aus dem LocalStorage löschen
            let currentDB = [];
            try { currentDB = JSON.parse(localStorage.getItem('customComponents') || '[]'); } catch {}
            currentDB = currentDB.filter(c => c.id !== compId);
            localStorage.setItem('customComponents', JSON.stringify(currentDB));
            
            // 2. Aus dem Laufzeit-Speicher löschen
            if (window.ComponentRegistry.definitions[compId]) {
                delete window.ComponentRegistry.definitions[compId];
            }
            
            // 3. Seitenleiste sofort neu laden
            window.ComponentRegistry.buildSidebar();
        }
    }
});

document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        window.ComponentRegistry.buildSidebar();
    }, 100);
});