function togglePreview() {
    let container = document.getElementById('previewContainer');
    let icon = document.getElementById('previewToggleIcon');
    if (container.style.display === 'none') {
        container.style.display = 'block';
        icon.className = 'fa fa-chevron-down';
    } else {
        container.style.display = 'none';
        icon.className = 'fa fa-chevron-right';
    }
}

function refreshPreview() {
    let iframe = document.getElementById('previewIframe');
    if (iframe) {
        iframe.src = iframe.src;
    }
}

function resizePreviewIframe() {
    let iframe = document.getElementById('previewIframe');
    if (iframe && iframe.contentWindow) {
        try {
            let height = iframe.contentWindow.document.body.scrollHeight;
            iframe.style.height = Math.max(height + 20, 200) + 'px';
        } catch (e) {
            // Cross-origin issues - use default height
            iframe.style.height = '400px';
        }
    }
}

function confirmDelete() {
    if (confirm('Are you sure you want to remove this block from the page?')) {
        document.getElementById('deleteBlockForm').submit();
    }
}

// Repeater field functions
let repeaterRowCounts = {};

function initRepeaterCounts() {
    document.querySelectorAll('.repeater-field').forEach(function(repeater) {
        let fieldName = repeater.dataset.fieldName;
        let rows = repeater.querySelectorAll('.repeater-row');
        repeaterRowCounts[fieldName] = rows.length;
    });
}

function addRepeaterRow(fieldName) {
    let repeater = document.querySelector('.repeater-field[data-field-name="' + fieldName + '"]');
    if (!repeater) return;

    let maxRows = parseInt(repeater.dataset.maxRows) || 100;
    let container = document.getElementById('repeater_' + fieldName + '_rows');
    let currentRows = container.querySelectorAll('.repeater-row').length;

    if (currentRows >= maxRows) {
        alert('Maximum ' + maxRows + ' rows allowed.');
        return;
    }

    let template = document.getElementById('repeater_' + fieldName + '_template');
    if (!template) return;

    let rowIndex = repeaterRowCounts[fieldName] || 0;
    repeaterRowCounts[fieldName] = rowIndex + 1;

    let html = template.innerHTML;
    html = html.replace(/__ROW_INDEX__/g, rowIndex);
    html = html.replace(/__ROW_NUM__/g, currentRows + 1);

    let div = document.createElement('div');
    div.innerHTML = html;
    let newRow = div.firstElementChild;
    newRow.setAttribute('draggable', 'true');
    container.appendChild(newRow);

    updateRepeaterState(fieldName);
}

function removeRepeaterRow(btn) {
    let row = btn.closest('.repeater-row');
    let repeater = btn.closest('.repeater-field');
    let fieldName = repeater.dataset.fieldName;
    let minRows = parseInt(repeater.dataset.minRows) || 0;
    let container = repeater.querySelector('.repeater-rows');
    let currentRows = container.querySelectorAll('.repeater-row').length;

    if (currentRows <= minRows) {
        alert('Minimum ' + minRows + ' rows required.');
        return;
    }

    row.remove();
    reindexRepeaterRows(fieldName);
    updateRepeaterState(fieldName);
}

function reindexRepeaterRows(fieldName) {
    let container = document.getElementById('repeater_' + fieldName + '_rows');
    let rows = container.querySelectorAll('.repeater-row');

    rows.forEach(function(row, index) {
        row.querySelector('.repeater-row-number').textContent = 'Row ' + (index + 1);
    });
}

function updateRepeaterState(fieldName) {
    let repeater = document.querySelector('.repeater-field[data-field-name="' + fieldName + '"]');
    if (!repeater) return;

    let maxRows = parseInt(repeater.dataset.maxRows) || 100;
    let container = repeater.querySelector('.repeater-rows');
    let currentRows = container.querySelectorAll('.repeater-row').length;
    let addBtn = repeater.querySelector('.btn-add-row');

    if (addBtn) {
        addBtn.disabled = currentRows >= maxRows;
    }
}

// Initialize repeater counts on page load
document.addEventListener('DOMContentLoaded', function() {
    initRepeaterCounts();
    document.querySelectorAll('.repeater-field').forEach(function(repeater) {
        updateRepeaterState(repeater.dataset.fieldName);
        initRepeaterDragDrop(repeater);
    });
});

// Drag and drop functionality for repeater rows (uses shared handler from block-registry-drag.js)
let repeaterDragDrop = createDragDropHandler('.repeater-row', function(container) {
    let fieldName = container.closest('.repeater-field').dataset.fieldName;
    reindexRepeaterRows(fieldName);
});

function initRepeaterDragDrop(repeater) {
    let container = repeater.querySelector('.repeater-rows');
    if (!container) return;

    repeaterDragDrop.init(container);

    // Set grab cursor on drag handles
    container.querySelectorAll('.repeater-row .repeater-row-drag').forEach(function(handle) {
        handle.style.cursor = 'grab';
    });
}

// Initialize WYSIWYG editors if available
document.addEventListener('DOMContentLoaded', function() {
    let wysiwygFields = document.querySelectorAll('.wysiwyg');
    wysiwygFields.forEach(function(field) {
        if (typeof CKEDITOR !== 'undefined') {
            CKEDITOR.replace(field.id);
        } else if (typeof tinymce !== 'undefined') {
            tinymce.init({
                selector: '#' + field.id,
                height: 300
            });
        }
    });
});

// Media picker - opens media manager in popup
let currentMediaFieldId = null;

function openMediaPicker(fieldId) {
    currentMediaFieldId = fieldId;
    window.open('/admin/media-manager/tinymce', 'Media Manager', 'width=950,height=650');
}

// Callback function for media manager
window.insertMediaToTinyMCE = function(url) {
    try {
        if (currentMediaFieldId) {
            let inputField = document.getElementById(currentMediaFieldId);
            if (inputField) {
                inputField.value = url;
                // Trigger change event
                inputField.dispatchEvent(new Event('change'));

                // Auto-populate alt text from filename if alt field exists and is empty
                let altFieldId = currentMediaFieldId.replace('_url', '_alt');
                let altField = document.getElementById(altFieldId);
                if (altField && !altField.value) {
                    let altText = generateAltTextFromUrl(url);
                    altField.value = altText;
                }

                // Update preview if it's an image field
                try {
                    updateImagePreview(currentMediaFieldId, url);
                } catch (previewError) {
                    console.warn('Preview update failed:', previewError);
                }
            }
            currentMediaFieldId = null;
        }
    } catch (e) {
        console.error('Media insert error:', e);
    }
};

// Generate alt text from filename
function generateAltTextFromUrl(url) {
    try {
        // Get filename from URL
        let filename = url.split('/').pop();
        // Remove extension
        filename = filename.replace(/\.[^/.]+$/, '');
        // Replace dashes and underscores with spaces
        filename = filename.replace(/[-_]/g, ' ');
        // Capitalize first letter of each word
        filename = filename.replace(/\b\w/g, function(c) { return c.toUpperCase(); });
        return filename;
    } catch (e) {
        return '';
    }
}

// Update image preview when URL changes
function updateImagePreview(fieldId, url) {
    try {
        let inputElement = document.getElementById(fieldId);
        if (!inputElement) return;

        let row = inputElement.closest('.row');
        if (!row) return;

        let previewContainer = row.querySelector('.image-preview');

        if (url && isImageUrl(url)) {
            if (previewContainer) {
                let img = previewContainer.querySelector('img');
                if (img) {
                    img.src = url;
                } else {
                    let newImg = document.createElement('img');
                    newImg.src = url;
                    newImg.alt = 'Preview';
                    newImg.style.cssText = 'max-width: 200px; max-height: 150px; margin-top: 10px;';
                    previewContainer.innerHTML = '';
                    previewContainer.appendChild(newImg);
                }
            } else {
                // Create preview if it doesn't exist
                let preview = document.createElement('div');
                preview.className = 'image-preview';
                let newImg = document.createElement('img');
                newImg.src = url;
                newImg.alt = 'Preview';
                newImg.style.cssText = 'max-width: 200px; max-height: 150px; margin-top: 10px;';
                preview.appendChild(newImg);
                row.appendChild(preview);
            }
        } else if (previewContainer) {
            previewContainer.remove();
        }
    } catch (e) {
        console.warn('Image preview update error:', e);
    }
}

function isImageUrl(url) {
    return /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(url);
}

// Also update preview on manual input change
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.field-image input[type="text"], .field-file input[type="text"]').forEach(function(input) {
        input.addEventListener('change', function() {
            updateImagePreview(this.id, this.value);
        });
    });
});

// Cropper.js instances
let croppers = {};

// Initialize all croppers on page load
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.crop-target').forEach(function(img) {
        let fieldName = img.dataset.fieldName;
        if (img.src && img.src !== window.location.href) {
            initCropper(fieldName);
        }
    });

    // Watch for changes on image URL inputs
    document.querySelectorAll('.image-url-input').forEach(function(input) {
        input.addEventListener('change', function() {
            let fieldName = this.dataset.fieldName;
            let cropEnabled = this.dataset.cropEnabled === '1';

            if (cropEnabled && this.value) {
                let cropContainer = document.getElementById('crop_' + fieldName + '_container');
                let cropImage = document.getElementById('crop_' + fieldName + '_image');

                if (cropContainer && cropImage) {
                    cropImage.src = this.value;
                    cropContainer.style.display = '';
                    // Wait for image to load before initializing cropper
                    cropImage.onload = function() {
                        initCropper(fieldName);
                    };
                }
            }
        });
    });
});

function initCropper(fieldName) {
    // Destroy existing cropper
    destroyCropper(fieldName);

    let img = document.getElementById('crop_' + fieldName + '_image');
    if (!img || !img.src) return;

    let aspectRatio = img.dataset.aspectRatio;
    let minWidth = parseInt(img.dataset.minWidth) || 0;
    let maxWidth = parseInt(img.dataset.maxWidth) || 0;
    let ratio = NaN; // Free crop by default

    if (aspectRatio && aspectRatio.includes(':')) {
        let parts = aspectRatio.split(':');
        ratio = parseFloat(parts[0]) / parseFloat(parts[1]);
    }

    // Get existing crop coordinates
    let x = parseFloat(document.getElementById('field_' + fieldName + '_crop_x').value) || 0;
    let y = parseFloat(document.getElementById('field_' + fieldName + '_crop_y').value) || 0;
    let width = parseFloat(document.getElementById('field_' + fieldName + '_crop_width').value) || 0;
    let height = parseFloat(document.getElementById('field_' + fieldName + '_crop_height').value) || 0;

    let cropperOptions = {
        aspectRatio: ratio,
        viewMode: 2,
        autoCropArea: 1,
        zoomable: false,
        zoomOnWheel: false,
        responsive: true,
        crop: function(event) {
            // Update hidden inputs with crop coordinates
            document.getElementById('field_' + fieldName + '_crop_x').value = Math.round(event.detail.x);
            document.getElementById('field_' + fieldName + '_crop_y').value = Math.round(event.detail.y);
            document.getElementById('field_' + fieldName + '_crop_width').value = Math.round(event.detail.width);
            document.getElementById('field_' + fieldName + '_crop_height').value = Math.round(event.detail.height);

            // Warn if crop is too small for srcset sizes
            let warning = document.getElementById('crop_' + fieldName + '_warning');
            let cropWidth = Math.round(event.detail.width);
            if (minWidth > 0 && cropWidth < minWidth) {
                if (warning) {
                    warning.textContent = 'Crop is too small (' + cropWidth + 'px). Minimum width: ' + minWidth + 'px for responsive images.';
                    warning.style.color = '#c0392b';
                    warning.style.display = '';
                }
            } else if (maxWidth > 0 && cropWidth < maxWidth) {
                if (warning) {
                    warning.textContent = 'Image may appear soft on large screens (' + cropWidth + 'px). Recommended minimum width: ' + maxWidth + 'px.';
                    warning.style.color = '#856404';
                    warning.style.display = '';
                }
            } else if (warning) {
                warning.style.display = 'none';
            }
        }
    };

    // If we have existing crop data, use it
    if (width > 0 && height > 0) {
        cropperOptions.data = { x: x, y: y, width: width, height: height };
    }

    croppers[fieldName] = new Cropper(img, cropperOptions);
}

function destroyCropper(fieldName) {
    if (croppers[fieldName]) {
        croppers[fieldName].destroy();
        delete croppers[fieldName];
    }
}

function resetCrop(fieldName) {
    if (croppers[fieldName]) {
        croppers[fieldName].reset();
    }
    document.getElementById('field_' + fieldName + '_crop_x').value = 0;
    document.getElementById('field_' + fieldName + '_crop_y').value = 0;
    document.getElementById('field_' + fieldName + '_crop_width').value = 0;
    document.getElementById('field_' + fieldName + '_crop_height').value = 0;
}

// Override media manager callback to reinitialize cropper
let originalInsertMediaToTinyMCE = window.insertMediaToTinyMCE;
window.insertMediaToTinyMCE = function(url) {
    // Capture field ID before original function nulls it
    let fieldId = currentMediaFieldId;

    // Call the original function
    if (originalInsertMediaToTinyMCE) {
        originalInsertMediaToTinyMCE(url);
    }

    // Handle cropper reinitialization
    if (fieldId) {
        let fieldName = fieldId.replace('field_', '').replace('_url', '');
        let input = document.getElementById(fieldId);

        if (input && input.dataset.cropEnabled === '1') {
            let cropContainer = document.getElementById('crop_' + fieldName + '_container');
            let cropControls = document.getElementById('crop_' + fieldName + '_controls');
            let cropImage = document.getElementById('crop_' + fieldName + '_image');

            if (cropContainer && cropImage) {
                cropImage.src = url;
                cropContainer.style.display = '';
                if (cropControls) {
                    cropControls.style.display = '';
                }
                let cropResetBtn = document.getElementById('crop_' + fieldName + '_reset');
                if (cropResetBtn) {
                    cropResetBtn.style.display = '';
                }

                // Wait a moment for the image to load, then initialize cropper
                setTimeout(function() {
                    initCropper(fieldName);
                }, 200);
            }
        }
    }
};
