document.addEventListener('DOMContentLoaded', () => {

    // --- STATE MANAGEMENT ---
    let isEditMode = false;
    let selectedElement = null;
    let dragState = {
        isDragging: false,
        isResizing: false,
        isDraggingWindow: false,
        isScrubbing: false, // BARU: untuk slider numerik
        targetWindow: null,
        scrubbingInput: null,
        initialX: 0, initialY: 0,
        initialElLeft: 0, initialElTop: 0, // Sekarang untuk transform
        initialElWidth: 0, initialElHeight: 0,
        initialValue: 0 // BARU: untuk slider numerik
    };

    // --- DOM ELEMENT SELECTORS ---
    const editorCanvas = document.getElementById('editor-canvas');
    const propertiesPanel = document.getElementById('properties-panel');
    const toolbox = document.getElementById('toolbox');
    const modeToggle = document.getElementById('mode-toggle');
    const saveButton = document.getElementById('save-button');
    const deleteButton = document.getElementById('delete-button');
    const resetButton = document.getElementById('reset-button'); // BARU
    const tabButtons = document.querySelectorAll('.ve-tab-button');
    const tabPanes = document.querySelectorAll('.ve-tab-pane');

    // --- INITIALIZATION ---
    function init() {
        adoptNativeElements(); 
        loadState();
        setupEventListeners();
        enterViewMode();
    }

    // --- EVENT LISTENERS SETUP ---
    function setupEventListeners() {
        modeToggle.addEventListener('click', toggleEditMode);
        editorCanvas.addEventListener('mousedown', handleCanvasMouseDown);
        document.addEventListener('mousemove', handleDocumentMouseMove);
        document.addEventListener('mouseup', handleDocumentMouseUp);
        
        propertiesPanel.addEventListener('input', handlePropertyChange);
        propertiesPanel.addEventListener('mousedown', handleScrubberMouseDown); // BARU: untuk slider
        
        saveButton.addEventListener('click', saveState);
        deleteButton.addEventListener('click', deleteSelectedElement);
        resetButton.addEventListener('click', resetAllSettings); // BARU
        toolbox.addEventListener('click', handleToolboxClick);

        document.querySelectorAll('.ve-window-header').forEach(header => {
            header.addEventListener('mousedown', handleWindowDragStart);
        });
        
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                tabButtons.forEach(btn => btn.classList.remove('ve-active'));
                tabPanes.forEach(pane => pane.classList.remove('ve-active'));
                button.classList.add('ve-active');
                document.getElementById(button.dataset.tab).classList.add('ve-active');
            });
        });
    }

    // --- MODE MANAGEMENT ---
    function toggleEditMode() {
        isEditMode = !isEditMode;
        isEditMode ? enterEditMode() : enterViewMode();
    }

    function enterEditMode() {
        document.body.classList.add('edit-mode');
        if (selectedElement) propertiesPanel.classList.remove('ve-hidden');
        toolbox.classList.remove('ve-hidden');
        modeToggle.querySelector('.fa-eye').style.display = 'none';
        modeToggle.querySelector('.fa-pencil').style.display = 'block';
    }

    function enterViewMode() {
        deselectElement();
        document.body.classList.remove('edit-mode');
        toolbox.classList.add('ve-hidden');
        modeToggle.querySelector('.fa-eye').style.display = 'block';
        modeToggle.querySelector('.fa-pencil').style.display = 'none';
    }
    
    // --- ELEMENT CREATION & DELETION ---
    function handleToolboxClick(e) {
        if (e.target.tagName === 'BUTTON') {
            const type = e.target.dataset.type;
            const newElementState = {
                tag: type.toUpperCase(),
                id: `el-${Date.now()}`,
                // DIUBAH: Gunakan transform untuk posisi awal
                style: `transform: translate(100px, 100px); z-index: 10;`,
                innerHTML: `Elemen ${type} Baru`,
                attributes: {}
            };

            if (type === 'img') {
                newElementState.style += `width: 150px; height: 100px;`;
                newElementState.attributes.src = 'https://via.placeholder.com/150x100.png?text=Gambar+Baru';
                newElementState.innerHTML = '';
            }
             if (type === 'button') newElementState.style += `width: 120px; height: 40px;`;
             if (type === 'div') newElementState.style += `width: 150px; height: 150px; background-color: #ddeeff; border: 1px solid #ccc;`;

            const newElement = createElementFromState(newElementState);
            editorCanvas.appendChild(newElement);
            selectElement(newElement);
        }
    }

    function deleteSelectedElement() {
        if (selectedElement && confirm('Anda yakin ingin menghapus elemen ini?')) {
            const elId = selectedElement.id;
            selectedElement.remove();
            deselectElement();
            console.log(`Elemen #${elId} telah dihapus.`);
        }
    }

    // --- BARU: Fungsi untuk Reset Pengaturan ---
    function resetAllSettings() {
        if (confirm('Anda yakin ingin mereset semua perubahan? Tindakan ini akan menghapus data dari local storage dan memuat ulang halaman.')) {
            localStorage.removeItem('visualEditorState');
            alert('Pengaturan telah direset. Halaman akan dimuat ulang.');
            location.reload();
        }
    }

    // --- ELEMENT SELECTION ---
    function selectElement(element) {
        if (selectedElement) selectedElement.classList.remove('selected');
        selectedElement = element;
        selectedElement.classList.add('selected');
        propertiesPanel.classList.remove('ve-hidden');
        
        // BARU: Perbarui tampilan ID di panel properti
        const selectedIdSpan = document.getElementById('selected-element-id');
        if (selectedIdSpan) {
            selectedIdSpan.textContent = selectedElement.id;
        }

        updatePropertiesPanel();
    }

    function deselectElement() {
        if (selectedElement) selectedElement.classList.remove('selected');
        selectedElement = null;
        propertiesPanel.classList.add('ve-hidden');

        // BARU: Reset tampilan ID saat tidak ada elemen terpilih
        const selectedIdSpan = document.getElementById('selected-element-id');
        if (selectedIdSpan) {
            selectedIdSpan.textContent = 'Tidak ada';
        }
    }

    // --- DRAGGING, RESIZING & SCRUBBING LOGIC ---
    function handleWindowDragStart(e) {
        if (e.target.classList.contains('ve-window-header')) {
            dragState.isDraggingWindow = true;
            dragState.targetWindow = e.currentTarget.closest('.ve-floating-window');
            dragState.initialX = e.clientX - dragState.targetWindow.offsetLeft;
            dragState.initialY = e.clientY - dragState.targetWindow.offsetTop;
        }
    }

    function handleCanvasMouseDown(e) {
        if (!isEditMode) return;
        const target = e.target.closest('.editable-element');
        if (target && editorCanvas.contains(target)) {
             if (e.offsetX >= target.offsetWidth - 12 && e.offsetY >= target.offsetHeight - 12 && target.classList.contains('selected')) {
                dragState.isResizing = true;
            } else {
                dragState.isDragging = true;
            }
            selectElement(target);
            dragState.initialX = e.clientX;
            dragState.initialY = e.clientY;
            
            // DIUBAH: Dapatkan posisi transform yang ada, atau default ke 0
            const currentTransform = new DOMMatrix(getComputedStyle(selectedElement).transform);
            dragState.initialElLeft = currentTransform.m41; // Nilai X dari translate
            dragState.initialElTop = currentTransform.m42;  // Nilai Y dari translate

            dragState.initialElWidth = selectedElement.offsetWidth;
            dragState.initialElHeight = selectedElement.offsetHeight;
        } else {
            deselectElement();
        }
    }
    
    // BARU: Logika untuk Scrubber/Slider
    function handleScrubberMouseDown(e) {
        if (!e.target.classList.contains('ve-scrubber')) return;
        e.preventDefault();
        
        dragState.isScrubbing = true;
        // Input adalah elemen di dalam wrapper, sebelum scrubber
        dragState.scrubbingInput = e.target.parentElement.querySelector('input');
        dragState.initialX = e.clientX;
        dragState.initialValue = parseFloat(dragState.scrubbingInput.value) || 0;
    }

    function handleDocumentMouseMove(e) {
        if (dragState.isDraggingWindow) {
            e.preventDefault();
            dragState.targetWindow.style.left = `${e.clientX - dragState.initialX}px`;
            dragState.targetWindow.style.top = `${e.clientY - dragState.initialY}px`;
        }
        if (dragState.isDragging && selectedElement) {
            e.preventDefault();
            const dx = e.clientX - dragState.initialX;
            const dy = e.clientY - dragState.initialY;
            const newX = dragState.initialElLeft + dx;
            const newY = dragState.initialElTop + dy;
            selectedElement.style.transform = `translate(${newX}px, ${newY}px)`;
        }
        if (dragState.isResizing && selectedElement) {
            e.preventDefault();
            const dw = e.clientX - dragState.initialX;
            const dh = e.clientY - dragState.initialY;
            selectedElement.style.width = `${dragState.initialElWidth + dw > 20 ? dragState.initialElWidth + dw : 20}px`;
            selectedElement.style.height = `${dragState.initialElHeight + dh > 20 ? dragState.initialElHeight + dh : 20}px`;
        }
        if(dragState.isScrubbing) {
            e.preventDefault();
            const dx = e.clientX - dragState.initialX;
            let step = e.shiftKey ? 10 : 1; // Geser lebih cepat dengan tombol Shift
            const newValue = Math.round(dragState.initialValue + (dx * step));
            dragState.scrubbingInput.value = newValue;
            dragState.scrubbingInput.dispatchEvent(new Event('input', { bubbles: true }));
        }
    }

    function handleDocumentMouseUp() {
        dragState.isDragging = false;
        dragState.isResizing = false;
        dragState.isDraggingWindow = false;
        dragState.isScrubbing = false; // BARU
        dragState.targetWindow = null;
        dragState.scrubbingInput = null; // BARU
    }

    // --- PROPERTIES PANEL LOGIC ---
    function handlePropertyChange(e) {
        if (!selectedElement) return;
        const propPath = e.target.dataset.prop;
        if (!propPath) return;

        let currentObject = selectedElement;
        const pathParts = propPath.split('.');
        for (let i = 0; i < pathParts.length - 1; i++) {
            currentObject = currentObject[pathParts[i]];
        }
        const finalProp = pathParts[pathParts.length - 1];
        let value = e.target.value;

        // Tambahkan 'px' jika input adalah number dan merupakan properti style tertentu
        if (e.target.type === 'number' && value && propPath.startsWith('style.')) {
             value += 'px';
        }
        
        currentObject[finalProp] = value;
    }
    
    function updatePropertiesPanel() {
        if (!selectedElement) return;
        
        propertiesPanel.querySelectorAll('.ve-prop-group').forEach(group => {
            const tags = group.dataset.forTag.split(' ');
            group.hidden = !tags.includes(selectedElement.tagName);
        });

        propertiesPanel.querySelectorAll('[data-prop]').forEach(input => {
             const propPath = input.dataset.prop;
             let currentObject = selectedElement;
             const pathParts = propPath.split('.');
             for (let i = 0; i < pathParts.length - 1; i++) {
                currentObject = currentObject[pathParts[i]];
             }
             const finalProp = pathParts[pathParts.length - 1];
             let value = currentObject[finalProp] || '';
             
             if (typeof value === 'string') {
                value = value.replace(/"/g, '').replace(/px$/, '');
             }
             input.value = value;
        });
    }

    // --- DATA PERSISTENCE ---
    function saveState() {
        const canvasState = [];
        editorCanvas.querySelectorAll('.editable-element').forEach(el => {
            const elState = {
                tag: el.tagName,
                id: el.id,
                style: el.getAttribute('style'),
                innerHTML: el.innerHTML,
                attributes: {
                    'data-onrefresh': el.dataset.onrefresh || '',
                    'data-onclick': el.dataset.onclick || ''
                }
            };
            if (el.tagName === 'IMG') elState.attributes.src = el.src;
            if (el.tagName === 'INPUT') elState.attributes.placeholder = el.placeholder;
            
            canvasState.push(elState);
        });
        localStorage.setItem('visualEditorState', JSON.stringify(canvasState));
        alert('Pengaturan berhasil disimpan!'); // BARU
    }

    function loadState() {
        const savedState = JSON.parse(localStorage.getItem('visualEditorState'));
        if (savedState && savedState.length > 0) {
            savedState.forEach(elState => {
                let el = document.getElementById(elState.id);
                if (el) {
                    // Hanya set style jika ada di state, agar tidak menimpa style asli
                    if(elState.style) el.setAttribute('style', elState.style);

                    // Jangan timpa innerHTML elemen yang dikontrol oleh Vue atau framework lain
                    const isVueControlled = el.hasAttribute('data-v-app') || el.closest('[data-v-app]');
                    if (el.tagName !== 'IMG' && el.tagName !== 'INPUT' && !isVueControlled) {
                        el.innerHTML = elState.innerHTML;
                    }
                    for (const [key, value] of Object.entries(elState.attributes)) {
                       if(value) el.setAttribute(key, value); else el.removeAttribute(key);
                    }
                } else {
                    el = createElementFromState(elState);
                    editorCanvas.appendChild(el);
                }
            });
        }
    }

    // DIUBAH: Mengadopsi semua elemen turunan, tidak hanya anak langsung
    function adoptNativeElements() {
        editorCanvas.querySelectorAll('*').forEach(el => {
            // Jangan adopsi UI editor itu sendiri atau elemen di dalamnya
            if (el.closest('#tool, .ve-floating-window')) return;
            
            // Jangan adopsi ulang elemen yang sudah diadopsi
            if (el.classList.contains('editable-element')) return;

            // Beri ID unik jika tidak ada
            if (!el.id) {
                el.id = `el-native-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
            }
            el.classList.add('editable-element');
            addInteractiveListeners(el);
        });
    }
    
    function createElementFromState(state) {
        const el = document.createElement(state.tag);
        el.id = state.id;
        el.className = 'editable-element';
        if(state.style) el.setAttribute('style', state.style);
        if (state.tag !== 'IMG') el.innerHTML = state.innerHTML;
        for (const [key, value] of Object.entries(state.attributes)) {
            if(value) el.setAttribute(key, value);
        }
        addInteractiveListeners(el);
        return el;
    }

    function addInteractiveListeners(el) {
        el.addEventListener('click', (e) => {
            // Pastikan event ini hanya untuk elemen itu sendiri dan bukan child-nya, kecuali dalam mode non-edit
            if (!isEditMode && e.currentTarget === el) {
                const onclickScript = el.dataset.onclick;
                if (onclickScript) {
                    try {
                        new Function(onclickScript).call(el);
                    } catch (err) { console.error(`Error executing onClick for #${el.id}:`, err); }
                }
            }
        });
    }

    // --- START THE APP ---
    init();
});