(function() {
    'use strict';

    window.IDVE = window.IDVE || {};

    IDVE.Blocks = {
        types: {},

        register: function(type, config) {
            this.types[type] = config;
        },

        get: function(type) {
            return this.types[type] || null;
        },

        getAll: function() {
            return this.types;
        },

        getDefaultData: function(type) {
            var def = this.types[type];
            if (!def) return {};
            var data = {};
            for (var i = 0; i < def.fields.length; i++) {
                var f = def.fields[i];
                data[f.name] = f.defaultValue !== undefined ? f.defaultValue : '';
            }
            return data;
        },

        getDefaultSettings: function() {
            return {
                margin: { top: 0, right: 0, bottom: 0, left: 0 },
                padding: { top: 0, right: 0, bottom: 0, left: 0 },
                backgroundColor: '',
                border: { width: {top:0,right:0,bottom:0,left:0}, color: '#000000', style: 'solid', radius: {topLeft:0,topRight:0,bottomRight:0,bottomLeft:0} },
                cssClass: '',
                cssId: '',
                visible: true
            };
        },

        renderPreview: function(type, data) {
            var def = this.types[type];
            if (def && def.preview) {
                return def.preview(data);
            }
            return '<p style="color:#999;font-style:italic">(' + type + ' block)</p>';
        },

        setPreview: function(type, previewFn) {
            if (this.types[type]) {
                this.types[type].preview = previewFn;
            }
        }
    };

    // ── Text Block ──
    IDVE.Blocks.register('text', {
        label: 'Text',
        icon: 'dashicons-editor-paragraph',
        category: 'content',
        fields: [
            { name: 'content', type: 'richtext', label: 'Content', defaultValue: '' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right','justify'], defaultValue: 'left' },
            { name: 'textColor', type: 'color', label: 'Text Color', defaultValue: '', tooltip: 'Leave empty to inherit from your theme.' },
            { name: 'fontSize', type: 'text', label: 'Font Size', defaultValue: '', tooltip: 'Any CSS value, e.g. 16px, 1.2em, or clamp(1rem, 2vw, 1.5rem).' }
        ],
        preview: function(data) {
            return data.content || '<p style="color:#999">Click to add text...</p>';
        }
    });

    // ── Heading Block ──
    IDVE.Blocks.register('heading', {
        label: 'Heading',
        icon: 'dashicons-heading',
        category: 'content',
        fields: [
            { name: 'content', type: 'text', label: 'Heading Text', defaultValue: '' },
            { name: 'level', type: 'select', label: 'Level', options: ['h1','h2','h3','h4','h5','h6'], defaultValue: 'h2' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right'], defaultValue: 'left' },
            { name: 'color', type: 'color', label: 'Color', defaultValue: '', tooltip: 'Leave empty to inherit from your theme.' },
            { name: 'fontSize', type: 'text', label: 'Font Size', defaultValue: '', tooltip: 'Overrides the default size for this heading level. Any CSS unit.' }
        ],
        preview: function(data) {
            var lvl = data.level || 'h2';
            var txt = data.content || 'Heading...';
            return '<' + lvl + '>' + txt + '</' + lvl + '>';
        }
    });

    // ── Image Block ──
    IDVE.Blocks.register('image', {
        label: 'Image',
        icon: 'dashicons-format-image',
        category: 'media',
        fields: [
            { name: 'imageId', type: 'hidden', label: 'Image ID', defaultValue: 0 },
            { name: 'imageUrl', type: 'image', label: 'Image', defaultValue: '' },
            { name: 'alt', type: 'text', label: 'Alt Text', defaultValue: '', tooltip: 'Describes the image for screen readers and SEO.' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right','full'], defaultValue: 'center' },
            { name: 'linkUrl', type: 'text', label: 'Link URL', defaultValue: '' },
            { name: 'linkTarget', type: 'select', label: 'Link Target', options: ['_self','_blank'], defaultValue: '_self', tooltip: '_self opens in same tab, _blank opens in a new tab.' },
            { name: 'maxWidth', type: 'text', label: 'Max Width', defaultValue: '', tooltip: 'Limits display width. Any CSS value, e.g. 400px or 50%.' },
            { name: 'imageSize', type: 'select', label: 'Image Size', options: ['full','large','medium_large','medium','thumbnail'], defaultValue: 'full' }
        ],
        preview: function(data) {
            if (data.imageUrl) {
                return '<img src="' + data.imageUrl + '" alt="' + (data.alt || '') + '" style="max-width:100%;height:auto">';
            }
            return '<div class="idve-image-empty">Click to select image</div>';
        }
    });

    // ── Button Block ──
    IDVE.Blocks.register('button', {
        label: 'Button',
        icon: 'dashicons-button',
        category: 'content',
        fields: [
            { name: 'label', type: 'text', label: 'Button Text', defaultValue: 'Click Here' },
            { name: 'url', type: 'text', label: 'URL', defaultValue: '#' },
            { name: 'target', type: 'select', label: 'Open In', options: ['_self','_blank'], defaultValue: '_self' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right'], defaultValue: 'center' },
            { name: 'backgroundColor', type: 'color', label: 'Background Color', defaultValue: '#0073aa' },
            { name: 'textColor', type: 'color', label: 'Text Color', defaultValue: '#ffffff' },
            { name: 'size', type: 'select', label: 'Size', options: ['small','medium','large'], defaultValue: 'medium' },
            { name: 'fullWidth', type: 'toggle', label: 'Full Width', defaultValue: false, tooltip: 'Makes the button stretch to fill its container width.' }
        ],
        preview: function(data) {
            var bg = data.backgroundColor || '#0073aa';
            var color = data.textColor || '#fff';
            var label = data.label || 'Click Here';
            return '<span class="idve-preview-button" style="background:' + bg + ';color:' + color + '">' + label + '</span>';
        }
    });

    // ── Spacer Block ──
    IDVE.Blocks.register('spacer', {
        label: 'Spacer',
        icon: 'dashicons-arrow-down',
        category: 'layout',
        fields: [
            { name: 'height', type: 'range', label: 'Height (px)', defaultValue: 40, min: 10, max: 300, step: 5 }
        ],
        preview: function(data) {
            var h = data.height || 40;
            return '<div class="idve-spacer-preview" style="height:' + h + 'px">' + h + 'px</div>';
        }
    });

    // ── Video Block ──
    IDVE.Blocks.register('video', {
        label: 'Video',
        icon: 'dashicons-video-alt3',
        category: 'media',
        fields: [
            { name: 'url', type: 'text', label: 'Video URL', defaultValue: '', tooltip: 'YouTube, Vimeo, or self-hosted video URL.' },
            { name: 'aspectRatio', type: 'select', label: 'Aspect Ratio', options: ['16:9','4:3','1:1'], defaultValue: '16:9', tooltip: 'Controls the height-to-width ratio of the video embed.' }
        ],
        preview: function(data) {
            if (data.url) {
                return '<div style="padding:15px;background:#f5f5f5;border-radius:3px;text-align:center"><span class="dashicons dashicons-video-alt3" style="font-size:32px;color:#0073aa"></span><br><small style="color:#666">' + data.url + '</small></div>';
            }
            return '<div style="padding:15px;background:#f5f5f5;border-radius:3px;text-align:center;color:#999">Enter a video URL</div>';
        }
    });

    // ── Custom HTML Block ──
    IDVE.Blocks.register('html', {
        label: 'Custom HTML',
        icon: 'dashicons-editor-code',
        category: 'content',
        fields: [
            { name: 'content', type: 'textarea', label: 'HTML Code', defaultValue: '' }
        ],
        preview: function(data) {
            if (data.content) {
                var preview = data.content.length > 200 ? data.content.substring(0, 200) + '...' : data.content;
                return '<pre class="idve-preview-code">' + preview.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</pre>';
            }
            return '<pre class="idve-preview-code" style="color:#999">Custom HTML...</pre>';
        }
    });

    // ── Divider Block ──
    IDVE.Blocks.register('divider', {
        label: 'Divider',
        icon: 'dashicons-minus',
        category: 'layout',
        fields: [
            { name: 'thickness', type: 'range', label: 'Thickness (px)', defaultValue: 2, min: 1, max: 10, step: 1 },
            { name: 'color', type: 'color', label: 'Color', defaultValue: '#cccccc' },
            { name: 'width', type: 'select', label: 'Width', options: ['25%','50%','75%','100%'], defaultValue: '100%' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right'], defaultValue: 'center' }
        ],
        preview: function(data) {
            var t = data.thickness || 2;
            var c = data.color || '#cccccc';
            var w = data.width || '100%';
            var a = data.alignment || 'center';
            var margin = '0 auto';
            if (a === 'left') margin = '0 auto 0 0';
            else if (a === 'right') margin = '0 0 0 auto';
            return '<hr style="border-width:0;height:' + t + 'px;background-color:' + c + ';color:' + c + ';width:' + w + ';margin:' + margin + '">';
        }
    });

    // ── Audio Block ──
    IDVE.Blocks.register('audio', {
        label: 'Audio',
        icon: 'dashicons-format-audio',
        category: 'media',
        fields: [
            { name: 'audioUrl', type: 'audio', label: 'Audio File', defaultValue: '' },
            { name: 'controls', type: 'toggle', label: 'Show Controls', defaultValue: true },
            { name: 'loop', type: 'toggle', label: 'Loop', defaultValue: false },
            { name: 'autoplay', type: 'toggle', label: 'Autoplay', defaultValue: false },
            { name: 'preload', type: 'select', label: 'Preload', options: ['none','metadata','auto'], defaultValue: 'metadata' },
            { name: 'caption', type: 'text', label: 'Caption', defaultValue: '' }
        ],
        preview: function(data) {
            if (data.audioUrl) {
                var filename = data.audioUrl.split('/').pop();
                return '<div class="idve-audio-preview"><span class="dashicons dashicons-media-audio" style="font-size:20px;color:#0073aa;vertical-align:middle;margin-right:6px"></span><span style="color:#23282d">' + filename + '</span></div>';
            }
            return '<div class="idve-audio-preview" style="color:#999;text-align:center"><span class="dashicons dashicons-media-audio" style="font-size:20px;vertical-align:middle;margin-right:6px"></span>No audio file selected</div>';
        }
    });

    // ── Icon Block ──
    IDVE.Blocks.register('icon', {
        label: 'Icon',
        icon: 'dashicons-flag',
        category: 'content',
        fields: [
            { name: 'iconClass', type: 'icon', label: 'Icon', defaultValue: 'fa-solid fa-star' },
            { name: 'iconSize', type: 'text', label: 'Size', defaultValue: '40px', tooltip: 'Any CSS size value, e.g. 40px, 2em, 3rem' },
            { name: 'iconColor', type: 'color', label: 'Color', defaultValue: '#333333' },
            { name: 'alignment', type: 'select', label: 'Alignment', options: ['left','center','right'], defaultValue: 'center' },
            { name: 'link', type: 'text', label: 'Link URL', defaultValue: '' },
            { name: 'linkTarget', type: 'select', label: 'Link Target', options: ['_self','_blank'], defaultValue: '_self', tooltip: '_blank opens in a new tab' }
        ],
        preview: function(data) {
            var icon = data.iconClass || 'fa-solid fa-star';
            var size = data.iconSize || '40px';
            var color = data.iconColor || '#333333';
            var align = data.alignment || 'center';
            return '<div style="text-align:' + align + '"><i class="' + icon + '" style="font-size:' + size + ';color:' + color + '"></i></div>';
        }
    });

    // ── Group Block ──
    IDVE.Blocks.register('group', {
        label: 'Group',
        icon: 'dashicons-screenoptions',
        category: 'layout',
        fields: [
            { name: 'minHeight', type: 'text', label: 'Min Height', defaultValue: '', tooltip: 'Any CSS value, e.g. 200px or 50vh.' }
        ],
        preview: function(data) {
            return '<p style="color:#999;font-style:italic">(Group \u2014 open settings to manage)</p>';
        }
    });

    // ── Auto-register blocks defined via PHP but not in JS ──
    (function autoRegisterFromPHP() {
        if (typeof idveData === 'undefined' || !idveData.blocks) return;
        for (var type in idveData.blocks) {
            if (!idveData.blocks.hasOwnProperty(type)) continue;
            if (IDVE.Blocks.types[type]) continue;
            var cfg = idveData.blocks[type];
            IDVE.Blocks.register(type, {
                label: cfg.label || type,
                icon: cfg.icon || 'dashicons-admin-generic',
                category: cfg.category || 'content',
                fields: cfg.fields || [],
                preview: (function(lbl) {
                    return function(data) {
                        var html = '<div style="padding:10px;background:#f9f9f9;border-radius:3px;text-align:center">';
                        html += '<strong style="color:#0073aa">' + lbl + '</strong>';
                        for (var k in data) {
                            if (data[k] && typeof data[k] === 'string' && data[k].length > 0 && data[k].length < 100) {
                                html += '<br><small style="color:#666">' + data[k] + '</small>';
                                break;
                            }
                        }
                        html += '</div>';
                        return html;
                    };
                })(cfg.label || type)
            });
        }
    })();
})();
