document.addEventListener('DOMContentLoaded', function() {
    const editorSection = document.getElementById('editor-section');

    // Only run the script if the editor section exists
    if (!editorSection) {
        return;
    }

    const titleInput = document.getElementById('titleInput');
    const descriptionInput = document.getElementById('descriptionInput');
    const imageUrlInput = document.getElementById('imageUrlInput');
    const ctaInput = document.getElementById('ctaInput');
    const checkoutHtmlInput = document.getElementById('checkoutHtmlInput');

    const previewTitle = document.getElementById('previewTitle');
    const previewDescription = document.getElementById('previewDescription');
    const previewImage = document.getElementById('previewImage');
    const previewCtaContainer = document.getElementById('previewCtaContainer');

    // --- Initialize Form from Preview --- 
    const initEditor = () => {
        if (previewTitle) titleInput.value = previewTitle.textContent.trim();
        if (previewDescription) descriptionInput.value = previewDescription.textContent.trim();
        if (previewImage) imageUrlInput.value = previewImage.src;
        
        const ctaButton = document.getElementById('previewCta');
        if (ctaButton) ctaInput.value = ctaButton.textContent.trim();
    };

    // --- Event Listeners for Live Preview --- 
    titleInput.addEventListener('input', () => {
        if (previewTitle) previewTitle.textContent = titleInput.value || 'Your Awesome Ebook Title';
    });

    descriptionInput.addEventListener('input', () => {
        if (previewDescription) previewDescription.textContent = descriptionInput.value || 'A compelling description...';
    });

    imageUrlInput.addEventListener('input', () => {
        if (previewImage) previewImage.src = imageUrlInput.value || 'https://images.pexels.com/photos/1907785/pexels-photo-1907785.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1';
    });

    const updateCtaView = () => {
        if (!previewCtaContainer) return;

        const checkoutValue = checkoutHtmlInput.value.trim();
        if (checkoutValue !== '') {
            previewCtaContainer.innerHTML = checkoutValue;
        } else {
            const ctaButton = document.createElement('button');
            ctaButton.id = 'previewCta';
            ctaButton.className = 'btn btn-primary btn-lg mt-3';
            ctaButton.textContent = ctaInput.value.trim() || 'Download Now';
            previewCtaContainer.innerHTML = '';
            previewCtaContainer.appendChild(ctaButton);
        }
    };

    checkoutHtmlInput.addEventListener('input', updateCtaView);
    ctaInput.addEventListener('input', updateCtaView);

    // --- Initial Run --- 
    initEditor();
    updateCtaView(); 
});
