(function() {
    'use strict';

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

    IDVE.Importer = {
        init: function() {},

        showDialog: function() {
            var overlay = document.createElement('div');
            overlay.className = 'idve-modal-overlay';
            overlay.innerHTML =
                '<div class="idve-modal">' +
                    '<div class="idve-modal-header">' +
                        '<h3>Import HTML</h3>' +
                        '<button type="button" class="idve-modal-close">&times;</button>' +
                    '</div>' +
                    '<div class="idve-modal-body">' +
                        '<p>Paste your HTML below. The editor will attempt to parse it into editable sections and blocks.</p>' +
                        '<textarea id="idve-import-textarea" rows="15" style="width:100%;font-family:monospace;font-size:13px" placeholder="Paste HTML here..."></textarea>' +
                    '</div>' +
                    '<div class="idve-modal-footer">' +
                        '<button type="button" class="idve-btn" id="idve-import-cancel">Cancel</button>' +
                        '<button type="button" class="idve-btn idve-btn-primary" id="idve-import-confirm">Import</button>' +
                    '</div>' +
                '</div>';

            document.body.appendChild(overlay);

            overlay.querySelector('.idve-modal-close').addEventListener('click', function() {
                document.body.removeChild(overlay);
            });
            document.getElementById('idve-import-cancel').addEventListener('click', function() {
                document.body.removeChild(overlay);
            });
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) document.body.removeChild(overlay);
            });

            document.getElementById('idve-import-confirm').addEventListener('click', function() {
                var html = document.getElementById('idve-import-textarea').value.trim();
                if (!html) return;
                IDVE.History.push();
                var sections = IDVE.Importer.parse(html);
                for (var i = 0; i < sections.length; i++) {
                    IDVE.state.tree.sections.push(sections[i]);
                }
                IDVE.Editor.renderCanvas();
                IDVE.Editor.markDirty();
                document.body.removeChild(overlay);
            });
        },

        parse: function(html) {
            var temp = document.createElement('div');
            temp.innerHTML = html;

            var sections = temp.querySelectorAll('.idve-section');
            if (sections.length > 0) {
                return this.parseIDVEStructure(temp);
            }
            return this.parseGenericHTML(temp);
        },

        parseIDVEStructure: function(container) {
            var result = [];
            var sections = container.querySelectorAll('.idve-section');

            for (var s = 0; s < sections.length; s++) {
                var sec = {
                    id: IDVE.Editor.generateId('idve_sec'),
                    settings: this.defaultSectionSettings(),
                    rows: []
                };

                var rows = sections[s].querySelectorAll('.idve-row');
                for (var r = 0; r < rows.length; r++) {
                    var row = { id: IDVE.Editor.generateId('idve_row'), settings: this.defaultRowSettings(), columns: [] };
                    var cols = rows[r].querySelectorAll('.idve-col');

                    for (var c = 0; c < cols.length; c++) {
                        var width = this.parseColumnWidth(cols[c].className);
                        var col = {
                            id: IDVE.Editor.generateId('idve_col'),
                            width: width,
                            settings: this.defaultColumnSettings(),
                            blocks: []
                        };

                        var blocks = cols[c].querySelectorAll('.idve-block');
                        for (var b = 0; b < blocks.length; b++) {
                            var type = this.parseBlockType(blocks[b].className);
                            col.blocks.push({
                                id: IDVE.Editor.generateId('idve_blk'),
                                type: type,
                                data: this.parseBlockData(blocks[b], type),
                                settings: IDVE.Blocks.getDefaultSettings()
                            });
                        }

                        row.columns.push(col);
                    }
                    sec.rows.push(row);
                }
                result.push(sec);
            }
            return result;
        },

        parseGenericHTML: function(container) {
            return [{
                id: IDVE.Editor.generateId('idve_sec'),
                settings: this.defaultSectionSettings(),
                rows: [{
                    id: IDVE.Editor.generateId('idve_row'),
                    settings: this.defaultRowSettings(),
                    columns: [{
                        id: IDVE.Editor.generateId('idve_col'),
                        width: '1/1',
                        settings: this.defaultColumnSettings(),
                        blocks: [{
                            id: IDVE.Editor.generateId('idve_blk'),
                            type: 'html',
                            data: { content: container.innerHTML },
                            settings: IDVE.Blocks.getDefaultSettings()
                        }]
                    }]
                }]
            }];
        },

        parseColumnWidth: function(cls) {
            var map = {
                'idve-col-1-1': '1/1', 'idve-col-1-2': '1/2',
                'idve-col-1-3': '1/3', 'idve-col-2-3': '2/3',
                'idve-col-1-4': '1/4', 'idve-col-3-4': '3/4',
                'idve-col-1-5': '1/5', 'idve-col-2-5': '2/5',
                'idve-col-3-5': '3/5', 'idve-col-4-5': '4/5'
            };
            for (var key in map) {
                if (cls.indexOf(key) !== -1) return map[key];
            }
            return '1/1';
        },

        parseBlockType: function(cls) {
            var types = ['text','heading','image','button','spacer','video','html'];
            for (var i = 0; i < types.length; i++) {
                if (cls.indexOf('idve-block-' + types[i]) !== -1) return types[i];
            }
            return 'html';
        },

        parseBlockData: function(el, type) {
            var inner = el.innerHTML;
            switch (type) {
                case 'text':
                    return { content: inner, alignment: 'left', textColor: '', fontSize: '' };
                case 'heading':
                    var m = inner.match(/<(h[1-6])[^>]*>([\s\S]*?)<\/\1>/i);
                    return {
                        content: m ? m[2] : inner,
                        level: m ? m[1] : 'h2',
                        alignment: 'left', color: '', fontSize: ''
                    };
                case 'image':
                    var src = '', alt = '';
                    var imgM = inner.match(/<img[^>]+src=["']([^"']+)["']/);
                    if (imgM) src = imgM[1];
                    var altM = inner.match(/<img[^>]+alt=["']([^"']*)["']/);
                    if (altM) alt = altM[1];
                    return { imageId: 0, imageUrl: src, alt: alt, alignment: 'center', linkUrl: '', linkTarget: '_self', maxWidth: '', borderRadius: '' };
                case 'button':
                    var href = '#', label = '';
                    var hrefM = inner.match(/<a[^>]+href=["']([^"']+)["']/);
                    if (hrefM) href = hrefM[1];
                    var labelM = inner.match(/<a[^>]*>([\s\S]*?)<\/a>/i);
                    if (labelM) label = labelM[1].replace(/<[^>]+>/g, '');
                    return { label: label, url: href, target: '_self', alignment: 'center', backgroundColor: '#0073aa', textColor: '#ffffff', borderRadius: '4', size: 'medium', fullWidth: false };
                case 'spacer':
                    return { height: 40 };
                case 'video':
                    var vUrl = '';
                    var vM = inner.match(/src=["']([^"']+)["']/);
                    if (vM) vUrl = vM[1];
                    return { url: vUrl, aspectRatio: '16:9' };
                default:
                    return { content: inner };
            }
        },

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

        defaultRowSettings: function() {
            return {
                backgroundColor: '',
                padding: { top: 0, right: 0, bottom: 0, left: 0 },
                margin: { top: 0, right: 0, bottom: 0, left: 0 },
                border: { width: {top:0,right:0,bottom:0,left:0}, color: '#000000', style: 'solid', radius: {topLeft:0,topRight:0,bottomRight:0,bottomLeft:0} },
                equalHeight: false,
                stretch: 'default',
                contentMaxWidth: '',
                gap: ''
            };
        },

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