function getPostItemName(key) {
    let returnval = key;
    switch (key) {
        case "text":
            returnval = 'پاراگراف O';
            break;
        case "text2":
            returnval = 'پاراگراف';
            break;
        case "title":
            returnval = 'تیتر';
            break;
        case "image":
            returnval = 'تصویر';
            break;
        case "image_dual":
            returnval = 'تصویر دوتایی';
            break;
        case "image_raw":
            returnval = 'تصویر خام (منسوخ)';
            break;
        case "gif"://depraceted
            returnval = 'گیف';
            break;
        case "image_zoom":
            returnval = 'تصویر قابل زوم';
            break;
        case "gif_dual": //depraceted
            returnval = 'گیف دوتایی';
            break;
        case "image_slider":
            returnval = 'اسلایدر تصویر';
            break;
        case "audio":
            returnval = 'صوت';
            break;
        case "button":
            returnval = 'دکمه';
            break;
        case "button_dual":
            returnval = 'دکمه دوتایی';
            break;
        case "table":
            returnval = 'جدول';
            break;
        case "space":
            returnval = 'فاصله خالی';
            break;
        case "pollloader":
            returnval = 'نظرسنجی';
            break;
        case "formloader":
            returnval = 'فرم';
            break;
        case "video":
            returnval = 'ویدیو';
            break;
        case "video_aparat":
            returnval = 'ویدیو آپارات';
            break;
        case "line_posts_byids":
            returnval = 'ردیف پست';
            break;
        case "line_posts_bycat":
            returnval = 'ردیف پست';
            break;
        case "line_posts_bytype":
            returnval = 'ردیف پست';
            break;
        case "line_cats_bycat":
            returnval = 'ردیف دسته‌ها';
            break;
        case "post_slider":
            returnval = 'اسلایدر پست';
            break;
        case "html":
            returnval = 'اچ‌تی‌ام‌ال';
            break;
        case "timer":
            returnval = 'شمارنده';
            break;
        case "notif":
            returnval = 'اطلاعیه';
            break;
        case "img_quad":
            returnval = 'تصویر چهارتایی';
            break;
        case "image_quad":
            returnval = 'تصویر چهارتایی';
            break;
        case "date":
            returnval = 'باکس تاریخ';
            break;
        case "account":
            returnval = 'حساب کاربری';
            break;
        case "grid":
            returnval = 'جدول آیکون';
            break;
        case "text_button":
            returnval = 'متن با دکمه';
            break;
        case "text_image":
            returnval = 'متن با تصویر';
            break;
        case "map":
            returnval = 'نقشه';
            break;
        case "group":
            returnval = 'گروه';
            break;
    }
    return returnval;
}

function getLinePostTypeName(code) {

    returnval = code;

    switch (code) {
        case "amazing_discount":
            returnval = 'تخفیف شگفت‌انگیز';
            break;
        case "amazing_discount_no_time_limit":
            returnval = 'تخفیف شگفت‌انگیز بدون زمان';
            break;
        case "amazing_discount_time_limit":
            returnval = 'تخفیف شگفت‌انگیز زماندار';
            break;
          
    }
    return returnval;
}

function getVisibleForTitle(key) {
    let returnval = key;
    switch (key) {
        case "all":
            returnval = 'نمایش به همه';
            break;
        case "loggedin":
            returnval = 'نمایش فقط به کاربران لاگین شده';
            break;
        case "guest":
            returnval = 'نمایش فقط به کاربران مهمان';
            break;
        case "users_with_no_purchase":
            returnval = 'نمایش به کاربران بدون خرید';
            break;
        case "users_with_some_purchase":
            returnval = 'نمایش به کاربران دارای خرید فعال';
            break;
        case "only_for_cafebazaar_users":
            returnval = 'نمایش تنها به کاربران کافه بازار';
            break;
        case "only_for_myket_users":
            returnval = 'نمایش تنها به کاربران مایکت';
            break;
        case "only_for_googleplay_users":
            returnval = 'نمایش تنها به کاربران گوگل پلی';
            break;
        case "only_for_private_users":
            returnval = 'نمایش تنها به کاربران انتشار خصوصی';
            break;
        case "except_cafebazaar_users":
            returnval = 'نمایش به جز برای کاربران کافه‌بازار';
            break;
        case "except_myket_users":
            returnval = 'نمایش به جز برای کاربران مایکت';
            break;
        case "except_googleplay_users":
            returnval = 'نمایش به جز برای کاربران گوگل‌پلی';
            break;
        case "except_private_users":
            returnval = 'نمایش به جز برای کاربران انتشار خصوصی';
            break;
        case "no_one":
            returnval = 'غیرفعال برای همه';
            break;
        case "only_for_web_users":
            returnval = "نمایش تنها به کاربران وب";
            break;
        case "except_web_users":
            returnval = "نمایش به جز برای کاربران وب";
            break;
        case "mobile_only":
            returnval = "نمایش تنها به کاربران موبایل";
            break;
        case "desktop_only":
            returnval = "نمایش تنها به کاربران دسکتاپ";
            break;
    }
    return returnval;
}

function getEmptyPageIconNoteHtml() {

    emptyIconHtml = '';
    emptyIconHtml += '<div class="bnpb-card-item-empty">';
    emptyIconHtml += '<img class="bcie-img" src="'+mpPanelBaseUrl+'/core/_dist/img/empty_page_icon.png">';
    emptyIconHtml += '<span class="bcie-title">این صفحه خالی است</span>';
    emptyIconHtml += '<span class="bcie-desc-wrapper">';
    emptyIconHtml += '<span>با کلیک بروی + افزودن بلاک جدید</span>';
    emptyIconHtml += '<span>اولین بلاک محتوای خود را خلق کنید</span>';
    emptyIconHtml += '</span>';
    emptyIconHtml += '</div>';

    return emptyIconHtml;
}

function WriteJsonListToDataBase(message){

    let BigJson = [];
    let index = 0;

    let page_tag = $('#page_tag').val();

    $("#big-data-blocks-array-sortable-list").children('div').each(function () {

        //update href by new json positions:
        let bnpbItem = $(this);
        bnpbItem.attr('data-index',index);
        bnpbItem.find('.delete-post-block').attr('data-index',index);
        bnpbItem.find('.duplicate-post-block').attr('data-index',index);
        bnpbItem.find('.add-post-block-after').attr('data-index',index);
        bnpbItem.find('.edit-post-block').attr('data-index',index);

        let a_tag = bnpbItem.find(".edit-post-block");
        const page = a_tag.data("page"); //sheets eg.
        //const pageUrl = a_tag.data("pageurl"); //sheets eg.
        let postid = a_tag.data("postid");
        if (page == "mainui" || page == "mainuiweb") postid = "0";
        const pagetag = a_tag.data("pagetag"); //sheet eg.
        const bodyorpreview = a_tag.data("bodyorpreview");

        //group mode datas:
        const upperPage = a_tag.data("upper-page");
        const groupJsonPos = a_tag.data("group-json-pos");
        const groupColNum = a_tag.data("group-col-num");

        const itemkey = a_tag.data("itemkey"); //audio eg.
        let new_link = mpPanelBaseUrl + "/block-editor/" + page + "/" + postid + "/" + bodyorpreview + "/" + index + "/" + upperPage + "/" + groupJsonPos+ "/" + groupColNum + "/" + itemkey + '_editor';
        a_tag.attr("data-url", new_link);

        let val = bnpbItem.find(".json_text_area").val();
        BigJson[index] = JSON.parse(val);
        index++;

    });
    

    let toSaveOnNormalBigJsonString = "";
    // --- group column handling ---
    if (page_tag === "group") {

        toSaveOnNormalBigJsonString = JSON.stringify(BigJson);
        let upperFullJsonStringForGroups = $('#upper-big-data-blocks-array-text-area-for-groups').val();
        let groupJsonPos = parseInt($('#group_json_pos').val());
        let groupColNum = parseInt($('#group_col_num').val());

        let UpperBigJson = JSON.parse(upperFullJsonStringForGroups);

        // Safety: check if the index exists
        if (groupJsonPos < 0 || groupJsonPos >= UpperBigJson.length) {
            notyf.error("Invalid group JSON position");
            return;
        }

        let groupEntry = UpperBigJson[groupJsonPos];
        let keyName = Object.keys(groupEntry)[0];

        if (keyName !== "group") {
            notyf.error("group item not found on groupJsonPos");
            return;
        }

        // Access the 'group' object
        let groupData = groupEntry[keyName];

        if (groupColNum == "1") {
            groupData['group_col1_data'] = BigJson;
        } else if (groupColNum == "2") {
            groupData['group_col2_data'] = BigJson;
        }else{
            notyf.error("Invalid group column number");
            return;
        }

        // Replace in parent structure
        UpperBigJson[groupJsonPos][keyName] = groupData;

        // Finally, replace BigJson with the updated upper group JSON
        BigJson = UpperBigJson;

    }

    let finalRes = JSON.stringify(BigJson);

    //update big json text area:
    if (page_tag === "group") {
        $('#upper-big-data-blocks-array-text-area-for-groups').val(finalRes);
        $('#big-data-blocks-array-text-area').val(toSaveOnNormalBigJsonString);
    }else{
        $('#big-data-blocks-array-text-area').val(finalRes);
    }
    
    let _id = $.trim($('#id').val());
    let _body_or_preview = $.trim($('#body_or_preview').val());
    let _content_type = $.trim($('#content_type').val());

    let _toSave = {
        id             : _id,
        body_or_preview: _body_or_preview,
        content_type   : _content_type,
        data           : finalRes
    }

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_big_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success(message);
                //actionsListeners();
                $('.pbp-iframe').attr('src', $('.pbp-iframe').attr('src'));
            } else {
                notyf.error(data);
            }
        },
        error: function(xhr, status, error) {
            notyf.error('Error: ' + xhr.status + ' ' + xhr.statusText);
        }
    });

    if($("#big-data-blocks-array-sortable-list").children().length === 0){
        $("#big-data-blocks-array-sortable-list").append(getEmptyPageIconNoteHtml());
    }

}

function openBlockEditor(editUrl,itemkey) {

    let dialogSize = "large3";
    if(itemkey == "group") dialogSize = "large2";
    //console.log("itemkey = " + itemkey + " | dialogSize = " + dialogSize);
    $('#dialog-holder').append(dialogHtmlGenerator(dialogSize,"post_block_editor_dialog"));

    let dialog = $("#post_block_editor_dialog");
    let dialog_id = "#post_block_editor_dialog";
    let contentBox = dialog.find(".majorisbox-final-content");
    let closeBtn = dialog.find(".majorisbox-close");
    let closeLayout = $(dialog_id+" .majorisbox-close-layout");
    let loadingOverlay = dialog.find('.majorisbox-loading');

    contentBox.hide();

    dialog.fadeIn('fast');
    $("html").css("overflow", "hidden");
    
    closeBtn.add(closeLayout).click(function () {
        Swal.fire({
            title: 'محتوای این بلاک ذخیره نشده است!',
            text: 'تغییرات شما در این بلاک محتوا هنوز ذخیره نشده است، مطمئن هستید که از این بخش خارج می‌شوید؟',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'خروج از ویرایشگر بلاک',
            cancelButtonText: 'ادامه تغییرات'
        }).then((result) => {
            if (result.isConfirmed) {
                selectImageID = null;
                contentBox.html("");
                dialog.fadeOut('fast');
                $("html").css("overflow", "auto");
                $('#dialog-holder').find(dialog_id).remove();
            }
            
        })
    });

    loadingOverlay.show();

    contentBox.show();
    contentBox.html("");

    setTimeout(function() {

        loadingOverlay.hide();
        let iframeHtml = '<iframe id="post-block-editor-iframe" scrolling="no" style="width:100%;height:100%" src="'+editUrl+'" title="description"></iframe>';
        contentBox.html(iframeHtml);
        let iframe = $('#post-block-editor-iframe');
        iframe.on('load', function(){
            iframe.contents().find('#end-of-block-editor').click(function(event){
                let newData = iframe.contents().find('#big_json_area').val();
                $('#big-data-blocks-array-text-area').val(newData);
                dialog.fadeOut('fast');
                $('#dialog-holder').find(dialog_id).remove();
                $("html").css("overflow", "auto");
                contentBox.html("");
                PostPreviewMotherAction();
                //actionsListeners();
                scrollAndEmphasisAnimation("edit");
            });
        });
        
    }, 200);

}

function reportPostSortableChange() {
    WriteJsonListToDataBase('تغییرات ذخیره شد');
}

function paragraphPreview(data,spansJsonString) {

    let regex = new RegExp('\\[span\\]\\[\\[\\*([\\s\\S]+?)\\*\\]\\]' , 'g'); //g for global search
    if(spansJsonString.trim() == ""){spansJsonString = '[]';}
    let spans = JSON.parse(spansJsonString);
    let count = ((data || '').match(regex) || []).length;

    //build html for preview
    for (let i = 0; i < count; i++) {
        data = data.replace("\[span\]\[\[\*", '<span style="preview_style_part_' + i + '">');
        data = data.replace("\*\]\]", '</span>');
    }

    //build css for html preview
    for (let i = 0; i < spans.length; i++) {

        let underline = "none";
        if (spans[i]['underline'] == 1) underline = "underline";

        let weight = "400";
        if (spans[i]['bold'] == 1) weight = "600";

        let size = "15px";
        if (spans[i]['size'] == 1) size = "18px";

        let css_style = 'color:' + spans[i]['color'] + ';text-decoration:' + underline + ';font-weight:' + weight + ';font-size:' + size;

        data = data.replace("preview_style_part_" + i, css_style);


    }


    data = '<span style="color:'+ $('#color').val() +'">' + data + '</span>';
    
    data = data.replace(/\n/g, "<br/>");
    return data;

}

function paragraph2Preview(quill_delta) {

    let html = "";

    let quill_delta_obj;
    try{
        quill_delta_obj = JSON.parse(quill_delta);
    }catch(e){
        quill_delta_obj = { ops: [ { insert: "خطا در بارگذاری متن" } ] };
    }

    if(quill_delta_obj.ops === undefined){
        return '';
    }

    quill_delta_obj.ops.forEach(op => {
        let text = op.insert;
        const attrs = op.attributes || {};
        
        // Escape HTML characters
        text = $('<div>').text(text).html();

        text = text.replace(/\n/g, '<br>');
        
        // Build inline styles
        let styles = [];
        if (attrs.color) {
            styles.push(`color: ${attrs.color}`);
        }
        
        // Build the HTML with proper nesting
        let wrappedText = text;
        
        // Apply link first (outermost)
        if (attrs.link) {
            //const href = decodeLink(attrs.link);
            wrappedText = `<span class="p2-fake-link" title="has link" style="${styles.join('; ')}">${wrappedText}</span>`;
            styles = []; // Clear styles as they're applied to the link
        }
        
        // Apply bold
        if (attrs.bold) {
            wrappedText = `<strong>${wrappedText}</strong>`;
        }
        
        // Apply underline
        if (attrs.underline) {
            wrappedText = `<u>${wrappedText}</u>`;
        }
        
        // Apply remaining styles (for non-link text with color)
        if (styles.length > 0 && !attrs.link) {
            wrappedText = `<span style="${styles.join('; ')}">${wrappedText}</span>`;
        }
        
        html += wrappedText;
    });

    return html;

}

function IBJE_DelegatedActionsListeners(){

    // IBJE: Integrated Big Json Editor
    // This function attaches all click handlers using the delegated event model.
    // Delegated events are bound once (to document) and remain active for dynamically
    // added, cloned, or reordered elements (e.g. via Sortable.js).
    // This avoids duplicate bindings and ensures stable behavior across DOM changes.
    // Call this function only once after jQuery is loaded.

    // Delete block
    $(document).on('click', '.delete-post-block', function () {
        Swal.fire({
            title: 'از حذف این بلاک محتوا مطمئن هستید؟',
            text: 'این فرایند غیر قابل بازگشت است',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'حذف بلاک',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {
                let index = $(this).attr('data-index');
                let el = $('.bnpb-card-item[data-index="'+index+'"]');
                el.hide('slow', function(){ 
                    el.remove();
                    WriteJsonListToDataBase('حذف انجام شد');
                });
            }
        });
    });

    // Duplicate block
    $(document).on('click', '.duplicate-post-block', function () {
        Swal.fire({
            title: 'از دوبل کردن این بلاک مطمئن هستید؟',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#007bff',
            cancelButtonColor: '#9da5aac4',
            confirmButtonText: 'دوبل کردن',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {
                let index = $(this).attr('data-index');
                let el = $('.bnpb-card-item[data-index="'+index+'"]');
                let copiedElement = el.clone();
                el.before(copiedElement).hide().show('slow', function(){ 
                    WriteJsonListToDataBase('بلاک مورد نظر دوبل شد');
                });
            }
        });
    });

    // Edit block
    $(document).on('click', '.edit-post-block', function () {
        let index = $(this).attr('data-index');
        let itemkey = $(this).attr('data-itemkey');
        $('#block-add-or-modify-position').attr('data-pos', index);
        let url = $(this).attr('data-url');
        openBlockEditor(url, itemkey);
    });

    //Copy Block Json String
    $(document).on('click', '.copy-block-to-clipboard', function () {
        let index = $(this).attr('data-index');
        let el = $('.bnpb-card-item[data-index="'+index+'"]');
        let jsonEl = el.find('.bci-header').find('.block-item-json');
        let raw = jsonEl.val();
        let pretty = raw;
        // try {
        //     let obj = JSON.parse(raw);
        //     pretty = JSON.stringify(obj, null, 2);
        //     //console.log(pretty);
        // } catch (e) {
        //     // If parsing fails, do nothing and copy raw value
        // }
        copyToClipboard(pretty, "کپی جیسون بلاک انجام شد");
    });

    // Add block after
    $(document).on('click', '.add-post-block-after', function () {
        let hideGroupItem = $(this).attr('data-hide-group-item');
        let index = $(this).attr('data-index');
        $('#block-add-or-modify-position').attr('data-pos', index);
        openBlockAdderDialog(hideGroupItem);
    });


}

let htmlCodes = [];

function previewBuilder(jsonString){

    let json = JSON.parse(jsonString);
    let key = Object.keys(json)
    key = key[0];
    let array_data = json[key];
    let margin = array_data['margin'];
    if (margin > 0) margin = Math.round(margin / 3);
    if (margin > 40) margin = 40;
    let marginStyle =  'padding:0 '+margin+'px;';
    let html = '';
    switch(key){
        case "text":
            let boxStyle = 'style="';
            let box_background_color = array_data['box']['background_color'];
            let box_active = array_data['box_active'];
            if(box_background_color!="" && box_active =="1"){
                boxStyle += 'padding:10px;background-color:'+box_background_color+';border-radius:'+array_data['box']['radius']+'px;padding:'+array_data['box']['padding']+'px';
            }
            boxStyle += 'color:'+array_data['color']+';"';
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="paragraph" '+boxStyle+'>';
            html+= '<span class="p_to_show"></span>';//we fill this with js
            html+= '<span style="display:none" class="p_text">'+array_data['text_data']+'</span>';
            html+= '<div style="display:none" class="p_spanJs">'+JSON.stringify(array_data['spans'])+'</div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "text2":

            let box2Style = 'style="';
            let box2_background_color = array_data['box']['background_color'];
            let box2_active = array_data['box_active'];
            if(box2_background_color!="" && box2_active =="1"){
                box2Style += 'background-color:'+box2_background_color+';border-radius:'+array_data['box']['radius']+'px;padding:'+array_data['box']['padding']+'px;';
            }
            box2Style += 'direction: '+array_data['text_direction'] + ';';
            box2Style += 'text-align: '+array_data['align']+';';
            box2Style += 'color: '+array_data['color']+';"';
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="paragraph2" '+box2Style+'>';
            html+= '<span class="p_to_show2"></span>';//we fill this with js
            html+= '<span style="display:none" class="p2_quill_delta">'+JSON.stringify(array_data['quill_delta'])+'</span>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "title":

            let titleStyle = 'style="';
            titleStyle += 'justify-content: '+array_data['align']+';';
            titleStyle += 'color: '+array_data['color']+';"';

            let titleIc = "";
            if(array_data['icon_code']!="") titleIc = '<i class="triw-ic-p '+modifyIcon(array_data['icon_code'])+'"></i>';

            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="pbi-triw" '+titleStyle+'>'+titleIc+'<h6>'+array_data['title_data']+'</h6></div>';
            html+= '</div>'
            html+= '</div>'
            break;
        case "image":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let imgUrl = array_data['image_url'];
            if (imgUrl == "") imgUrl = mpPanelBaseUrl + "/core/_dist/img/image_placeholder.jpg";
            html+= '<span class="pbi-image-wrap"><img class="piw-img" src="'+imgUrl+'"></span>';
            html+= '</div>'
            html+= '</div>'
            break;
        case "image_raw":
            html+= '<span class="pbi-image-wrap"><img class="piw-img" src="'+array_data['image_url']+'"></span>';
            break;
        case "image_zoom":
            html+= '<div class="pbi-max-limiter">'
            html+= '<span class="pbi-image-wrap"><img class="piw-img" src="'+array_data['image_zoom_url']+'"></span>';
            html+= '</div>'
            break;
        case "image_dual":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';

            let h = parseInt(array_data['height']);
            if (!h || h <= 0) h = 230;
            let hMobile = parseInt(array_data['height_mobile']);
            if (!hMobile || hMobile <= 0) hMobile = h;

            let shareStart = parseInt(array_data['start_image_share']);
            if (isNaN(shareStart)) shareStart = 50;
            let shareEnd = 100 - shareStart;
            let img1Url = array_data['image1_url'];
            let img2Url = array_data['image2_url'];
            if (img1Url == "") img1Url = mpPanelBaseUrl + "/core/_dist/img/image_placeholder.jpg";
            if (img2Url == "") img2Url = mpPanelBaseUrl + "/core/_dist/img/image_placeholder.jpg";
            html+= '<div class="pbi-imagedual-wrap" style="--diHeight:' + h + 'px;--diHeightMobile:' + hMobile + 'px;">';
            html+= '<div class="pidw-iip" style="flex:'+shareStart+';"><img class="piw-img" src="'+img1Url+'"></div>';
            html+= '<div class="pidw-iip" style="flex:'+shareEnd+';"><img class="piw-img" src="'+img2Url+'"></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "image_slider":
            let slider_data = array_data['slider_data'];
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let hslider = parseInt(array_data['height']);
            if (!hslider || hslider <= 0) hslider = 230;
            let hslidermobile = parseInt(array_data['height_mobile']);
            if (!hslidermobile || hslidermobile <= 0) hslidermobile = hslider;
            html+= '<div class="swiper-pb-preview-box" style="--sliderHeight:' + hslider + 'px;--sliderHeightMobile:' + hslidermobile + 'px;">';
            html+= '<div class="swiper-pbp">';
            html+= '<div class="swiper-wrapper">';
            slider_data.forEach(function(slide) {
                html+= '<div class="swiper-slide"><img src="'+slide['img']+'"/></div>';
            });
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            html+= '<div class="intent-preview-datas">';
            slider_data.forEach(function(slide) {
                html+= '<span class="ipds-item">'+getIntentName(slide['intent_type'])+'</span>';
            });
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "button":
            let btnText = array_data['button_data'];
            if (!btnText) btnText = "...";
            let btnColor = array_data['background_color'];
            if (!btnColor) btnColor = "#b7c5d5";

            //btn text and icon and color:
            let btnIcon = "";
            if(array_data['icon_code']!="") btnIcon = '<i class="'+modifyIcon(array_data['icon_code'])+'"></i>';
            let btnTextHtml = '<span class="inner-btnp-span" style="color:'+array_data['color']+'">'+btnIcon+btnText+'</span>';

            // new options with safe defaults
            let btnFullWidth = array_data['btn_full_width'] == 1;  // default false
            let gravity = array_data['gravity'] || "center";        // default center
            let padding = array_data['padding'] || "10";      // default padding

            let paddingStyle = 'padding:'+padding+'px '+(padding*2)+'px;';

            // determine styles
            let gravityStyle = "";
            if (gravity === "start") gravityStyle = "justify-content:flex-start;";
            else if (gravity === "end") gravityStyle = "justify-content:flex-end;";
            else gravityStyle = "justify-content:center;";

            let widthStyle = btnFullWidth ? "width:100%;" : "width:auto;";
            
            html += '<div class="pbi-max-limiter">';
            html += '<div class="pbi-inner-container" style="' + marginStyle + '">';
            html += '<div class="pbi-button-p-wrapper" style="display:flex;' + gravityStyle + '">';
            html += '<button class="btn btn-primary" style="' + widthStyle + 'background-color:' + btnColor + ';' + paddingStyle + '">' + btnTextHtml + '</button>';
            html += '</div>';
            html += '<div class="pbi-ipds-p-wrapper" style="display:flex;' + gravityStyle + '">';
            html += '<span class="ipds-item">' + getIntentName(array_data['intent_type']) + '</span>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
        break;
        case "button_dual":
            let btn1Text = array_data['button1_data'];
            if(btn1Text=="") btn1Text = "...";
            let btn2Text = array_data['button2_data'];
            if(btn2Text=="") btn2Text = "...";
            let btn1Color = array_data['background1_color'];
            if(btn1Color=="") btn1Color = "#b7c5d5";
            let btn2Color = array_data['background2_color'];
            if(btn2Color=="") btn2Color = "#b7c5d5";

            let btnDualFullWidth = array_data['btn_full_width'] == 1;  // default false
            let btnDualgravity = array_data['gravity'] || "center";        // default center
            let btnDualPadding = array_data['padding'] || "10"; // default padding
            
            let btnDualPaddingStyle = 'padding:'+btnDualPadding+'px '+(btnDualPadding*2)+'px;';

            //btn1 and btn2 text and icon and color:
            let btn1Icon = "";
            if(array_data['icon1_code']!="") btn1Icon = '<i class="'+modifyIcon(array_data['icon1_code'])+'"></i>';
            let btn1TextHtml = '<span class="inner-btnp-span" style="color:'+array_data['color1']+'">'+btn1Icon+btn1Text+'</span>';
            let btn2Icon = "";
            if(array_data['icon2_code']!="") btn2Icon = '<i class="'+modifyIcon(array_data['icon2_code'])+'"></i>';
            let btn2TextHtml = '<span class="inner-btnp-span" style="color:'+array_data['color2']+'">'+btn2Icon+btn2Text+'</span>';

            // determine styles
            let btnDualGravityStyle = "";
            if (btnDualgravity === "start") btnDualGravityStyle = "justify-content:flex-start;";
            else if (btnDualgravity === "end") btnDualGravityStyle = "justify-content:flex-end;";
            else btnDualGravityStyle = "justify-content:center;";

            let btnDualWidthClass = btnDualFullWidth ? "btn-dual-p-fullwidth" : "";

            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="bdp-mw '+btnDualWidthClass+'" style="'+btnDualGravityStyle+'">';
            html+= '<button class="btn btn-primary" style="background-color: '+btn1Color+';' + btnDualPaddingStyle + '">'+btn1TextHtml+'</button>';
            html+= '<button class="btn btn-primary" style="background-color: '+btn2Color+';' + btnDualPaddingStyle + '">'+btn2TextHtml+'</button>';
            html+= '</div>';
            html+= '<div class="bdp-iw" style="'+btnDualGravityStyle+'">';
            html+= '<span class="ipds-item">'+getIntentName(array_data['intent1_type'])+'</span>';
            html+= '<span class="ipds-item">'+getIntentName(array_data['intent2_type'])+'</span>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "audio":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div style="background-color:'+array_data['background_color']+';" class="pbi-audio-box">'
            html+= '<audio class="audios" src="'+array_data['audio_url']+'" controls></audio>';
            if(array_data['title'] != ""){
                html+= '<span class="minitext">'+array_data['title']+'</span>';
            }
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "table":
            let full_table = array_data['table_data'];
            let headerBold = array_data['header_bold'] == 1;
            let oddLine = array_data['oddline'] == 1;

            html += '<div class="pbi-max-limiter">';
            html += '<div class="pbi-inner-container" style="' + marginStyle + '">';
            html += '<table class="table table-bordered"><tbody>';

            full_table.forEach(function (table_row, rowIndex) {

                // Determine row style
                let rowStyle = '';
                if (oddLine && rowIndex % 2 === 1) {
                    rowStyle = 'background-color:#dddddd24;';
                }

                html += '<tr style="' + rowStyle + '">';

                table_row.forEach(function (th) {
                    // Determine font weight
                    let fontWeight = (headerBold && rowIndex === 0) ? '700' : '400';
                    html += '<th><span style="font-weight:' + fontWeight + ';" class="minitext">' + th + '</span></th>';
                });

                html += '</tr>';
            });

            html += '</tbody></table>';
            html += '</div>';
            html += '</div>';
            break;
        case "space":
            let height = array_data['height'];
            html+= '<span class="minitext"></span>';
            break;
        case "pollloader":
            let pollid = array_data['id'];
            let poll_link = '<span class="hlpf-nodata">شناسه تعیین نشده</span>';
            if(pollid != 0){
                poll_link = '<span>شناسه نظرسنجی: </span><a class="hlpf-urldata" href="'+mpPanelBaseUrl+'/manage-poll/'+pollid+'" target="_blank">'+pollid+'</a>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';
            html+= '<div class="pbi-poll-mockup-wrapper">';
            html+= '<img class="bfmw-img" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_poll2.png">';
            html+= '</div>';
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">نمایش نظرسنجی</span><span>'+poll_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "formloader":
            let formid = array_data['id'];
            let form_link = '<span class="hlpf-nodata">شناسه تعیین نشده</span>';
            if(formid != 0){
                form_link = '<span>شناسه فرم: </span><a class="hlpf-urldata" href="'+mpPanelBaseUrl+'/f/'+formid+'" target="_blank">'+formid+'</a>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';
            html+= '<div class="pbi-form-mockup-wrapper">';
            html+= '<img class="bfmw-img" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_form2.png">';
            html+= '</div>';
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">نمایش فرم</span><span>'+form_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "video":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<span><video class="videos" src="'+array_data['video_url']+'" controls></video></span>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "video_aparat":
            const aparatHtmlId = htmlCodes.length; // Use the current array length as ID
            htmlCodes.push(array_data['video_script']);
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="html-block-preview-wrapper">';
            html+= '<div class="html-aparat-prev-iframeContainer" data-html-id="'+aparatHtmlId+'"></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "line_posts_byids":
            let theme_lpbi = array_data['theme'];
            let plm_theme = "";
            if (theme_lpbi == 1) plm_theme = "plm-vertical";
            let post_ids = array_data['ids'];
            let lpbi_link = '<span class="hlpf-nodata">شناسه پست‌ها تعیین نشده</span>';
            if(post_ids != ""){
                let isValidFormat = /^\d+(,\d+)*$/.test(post_ids);
                if(isValidFormat){
                    let postIdsHtml = '';
                    let numbers = post_ids.split(",");
                    numbers.forEach(number => {
                        postIdsHtml += '<a class="hul-id-item" href="'+mpPanelBaseUrl+'/p/'+number+'" target="_blank">'+number+'</a>';
                    });
                    lpbi_link = '<span>شناسه پست‌ها: </span><span class="hul-idsbox">'+postIdsHtml+'</span>';
                }else{
                    lpbi_link = '<span class="hlpf-nodata">شناسه‌های وارد شده اشتباه است</span>';
                }
                
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';

            let itemsbg = 'background:'+array_data['background_color']+';';
            let roundCornerAmount = 'border-radius:'+array_data['round_corners']+'px;';
            html+= '<div class="pbi-linepost-mockup-wrapper '+plm_theme+'" style="padding:'+array_data['inner_root_padding']+'px;background:'+array_data['root_background_color']+';'+roundCornerAmount+'">';
            html+= '<div class="pbi-linepost-mockup-inner" style="gap:'+array_data['space_between']+'px;">';
            if(array_data['line_post_first_item_as_image'] != "" && theme_lpbi == 0){
                html+= '<div class="plm-linebox plm-first-item-img" style="'+itemsbg+roundCornerAmount+'"><img src="'+array_data['line_post_first_item_as_image']+'"></div>';
            }
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg+roundCornerAmount+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
        
            html+= '</div>';
            html+= '</div>';


            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">ردیف پست‌ها با شناسه</span><span class="hlpf-desc">'+lpbi_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "line_posts_bycat":
            let theme_lpbc = array_data['theme'];
            let plm_theme2 = "";
            if (theme_lpbc == 1) plm_theme2 = "plm-vertical";
            let cat_id = array_data['cat_id'];
            let lpbc_link = '<span class="hlpf-nodata">شناسه تعیین نشده</span>';
            if(cat_id != 0){
                lpbc_link = '<span>شناسه دسته‌بندی مادر: </span><a class="hlpf-urldata" href="'+mpPanelBaseUrl+'/c/'+cat_id+'" target="_blank">'+cat_id+'</a>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';


            let itemsbg2 = 'background:'+array_data['background_color']+';';
            let roundCornerAmount2 = 'border-radius:'+array_data['round_corners']+'px;';
            html+= '<div class="pbi-linepost-mockup-wrapper '+plm_theme2+'" style="padding:'+array_data['inner_root_padding']+'px;background:'+array_data['root_background_color']+';'+roundCornerAmount2+'">';
            html+= '<div class="pbi-linepost-mockup-inner" style="gap:'+array_data['space_between']+'px;">';
            if(array_data['line_post_first_item_as_image'] != "" && theme_lpbc == 0){
                html+= '<div class="plm-linebox plm-first-item-img" style="'+itemsbg2+roundCornerAmount2+'"><img src="'+array_data['line_post_first_item_as_image']+'"></div>';
            }
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg2+roundCornerAmount2+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount2+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
        
            html+= '</div>';
            html+= '</div>';

            
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">ردیف پست‌ها با دسته‌بندی</span><span>'+lpbc_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "line_posts_bytype":
            let theme_lpbt = array_data['theme'];
            let plm_theme3 = "";
            if (theme_lpbt == 1) plm_theme3 = "plm-vertical";
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';


            let itemsbg3 = 'background:'+array_data['background_color']+';';
            let roundCornerAmount3 = 'border-radius:'+array_data['round_corners']+'px;';
            html+= '<div class="pbi-linepost-mockup-wrapper '+plm_theme3+'" style="padding:'+array_data['inner_root_padding']+'px;background:'+array_data['root_background_color']+';'+roundCornerAmount3+'">';
            html+= '<div class="pbi-linepost-mockup-inner" style="gap:'+array_data['space_between']+'px;">';
            if(array_data['line_post_first_item_as_image'] != "" && theme_lpbt == 0){
                html+= '<div class="plm-linebox plm-first-item-img" style="'+itemsbg3+roundCornerAmount3+'"><img src="'+array_data['line_post_first_item_as_image']+'"></div>';
            }
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg3+roundCornerAmount3+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount3+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
        
            html+= '</div>';
            html+= '</div>';

            
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">ردیف پست‌ها با نوع</span><span>با نوع خاص: '+getLinePostTypeName(array_data['type'])+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "line_cats_bycat":
            let cbc_cat_id = array_data['cat_id'];
            let lcbc_link = '<span class="hlpf-nodata">شناسه تعیین نشده</span>';
            if(cbc_cat_id != 0){
                lcbc_link = '<span>شناسه دسته‌بندی مادر: </span><a class="hlpf-urldata" href="'+mpPanelBaseUrl+'/c/'+cbc_cat_id+'" target="_blank">'+cbc_cat_id+'</a>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';


            let itemsbg4 = 'background:'+array_data['background_color']+';';
            let roundCornerAmount4 = 'border-radius:'+array_data['round_corners']+'px;';
            html+= '<div class="pbi-linepost-mockup-wrapper" style="padding:'+array_data['inner_root_padding']+'px;background:'+array_data['root_background_color']+';'+roundCornerAmount4+'">';
            html+= '<div class="pbi-linepost-mockup-inner" style="gap:'+array_data['space_between']+'px;">';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
            html+= '<div class="plm-linebox" style="'+itemsbg4+roundCornerAmount4+'"><div class="plml-top"><img class="plml-img" style="'+roundCornerAmount4+'" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_linepost_g2.png"></div><div class="plml-bottom"><div class="plmlb-txt1"></div><div class="plmlb-txt2"></div></div></div>';
        
            html+= '</div>';
            html+= '</div>';

            
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">ردیف دسته‌بندی‌ها</span><span>'+lcbc_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "post_slider":
            let ps_cat_id = array_data['cat_id'];
            let psc_link = '<span class="hlpf-nodata">شناسه تعیین نشده</span>';
            if(ps_cat_id != 0){
                psc_link = '<span>شناسه دسته‌بندی مادر: </span><a class="hlpf-urldata" href="'+mpPanelBaseUrl+'/c/'+ps_cat_id+'" target="_blank">'+ps_cat_id+'</a>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';

            html+= '<div class="pbi-post-slider-mockup-wrapper">';
            html+= '<div class="ppsmw-part1">';
            html+= '<div class="ppsmw-im-wrapper"><img class="ppsmw-img-mini" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_post_slider2.png"></div>';
            html+= '<div class="ppsmw-im-wrapper"><img class="ppsmw-img-mini" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_post_slider2.png"></div>';
            html+= '</div>';
            html+= '<div class="ppsmw-part2">';
            html+= '<div class="ppsmw-im-main-wrapper"><img class="ppsmw-img" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_post_slider2.png"></div>';
            html+= '<img class="ppsmw-dots-img" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/ps_dots.png">';
            html+= '</div>';
            html+= '</div>';

            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span class="hlpf-title">اسلایدر پست</span><span>'+psc_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "html":
            const htmlId = htmlCodes.length; // Use the current array length as ID
            htmlCodes.push(array_data['code']);
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="html-block-preview-wrapper">';
            html+= '<div class="html-prev-iframeContainer" data-html-id="'+htmlId+'"></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "timer":
            let ending_date = array_data['ending_date'];
            let ed_link = '<span class="hlpf-nodata">ساعت و تاریخ پایان تعیین نشده</span>';
            if(ending_date != ""){
                ed_link = '<span>تا تاریخ و ساعت: '+ending_date+'</span>';
            }
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-line-posts-wrapper">';

            html += '<div class="pbi-mockup-main-wrapper pmmw-center" style="background-color:'+array_data['background_color']+';">';
            html += '<div class="pbi-mockup-timer-data">';
            let timer_text_color = array_data['text_color'];
            let timer_icon = '<i style="color:'+timer_text_color+';" class="pho phosphor-icons ph-clock"></i>';
            if (array_data['icon_code'] && array_data['icon_code'] !== '') timer_icon = '<i style="color:'+timer_text_color+';" class="'+modifyIcon(array_data['icon_code'])+'"></i>';
            html += timer_icon;
            html += '<div style="color:'+timer_text_color+';" class="pbi-mockup-timer-txt">99 : 12 : 12</div>';
            html += '</div>';
            html += '</div>';
           
            html+= '<div class="hpp-lpfdata"><div class="hlpinner"><span>شمارنده معکوس</span><span>'+ed_link+'</span></div></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "notif":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let s1 = "";
            let text = array_data['text'];
            if(text == "") text = "...";

            //btn text and icon and color:
            let notifIcon = "";
            if(array_data['icon_code']!="") notifIcon = '<i class="'+modifyIcon(array_data['icon_code'])+'"></i>';
            let notifTextHtml = '<span class="inner-notifp-span">'+notifIcon+text+'</span>';

            if(array_data['text_color'] != "") s1 += "color:"+array_data['text_color']+";";
            if(array_data['background_color'] != "") s1 += "background-color:"+array_data['background_color']+";";
            html+= '<div class="hpp-notif-box" style="'+s1+'">'+notifTextHtml+'</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "account":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html += '<div class="pbi-mockup-main-wrapper" style="color:'+array_data['text_color']+';background-color:'+array_data['background_color']+';">';
            html += '<div class="pbi-mockup-start">';
            let account_text_color = array_data['text_color'];
            let account_icon = '<i style="color:'+account_text_color+';" class="pho phosphor-icons ph-user"></i>';
            if (array_data['icon_code'] && array_data['icon_code'] !== '') account_icon = '<i style="color:'+account_text_color+';" class="'+modifyIcon(array_data['icon_code'])+'"></i>';
            html += account_icon;
            html += '<div style="background:'+account_text_color+';" class="pbi-mockup-text"></div>';
            html += '</div>';
            html += '<div class="pbi-mockup-end">';
            html += '<span class="btn pbi-mockup-btn"><span class="pbi-mockup-btn-txt"></span></span>';
            html += '</div>';
            html += '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "date":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html += '<div class="pbi-mockup-main-wrapper" style="color:'+array_data['text_color']+';background-color:'+array_data['background_color']+';">';
            html += '<div class="pbi-mockup-start">';
            let date_text_color = array_data['text_color'];
            let date_icon = '<i style="color:'+date_text_color+';" class="pho phosphor-icons ph-calendar"></i>';
            if (array_data['icon_code'] && array_data['icon_code'] !== '') date_icon = '<i style="color:'+date_text_color+';" class="'+modifyIcon(array_data['icon_code'])+'"></i>';
            html += date_icon;
            html += '<div class="dual-txt-mockup-wrapper">';
            html += '<div style="background:'+date_text_color+';" class="pbi-mockup-text"></div>';
            html += '<div style="background:'+date_text_color+';" class="pbi-mockup-text-mini"></div>';
            html += '</div>';
            html += '</div>';
            html += '<div class="pbi-mockup-end">';
            html += '<div class="dual-txt-mockup-wrapper">';
            html += '<div style="background:'+date_text_color+';" class="pbi-mockup-text-tiny"></div>';
            html += '<div style="background:'+date_text_color+';" class="pbi-mockup-text-tiny"></div>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "text_button":
            let textbtnBtxt = array_data['button_text'];
            if(textbtnBtxt == "") textbtnBtxt = "...";
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="hpp-text-button">';
            html+= '<span class="hpp-ictxt"><span>'+array_data['text']+'</span></span>';
            html+= '<span><span style="background:'+array_data['button_color']+';" class="hpp-btn">'+textbtnBtxt+'</span></span>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "text_image":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let tih = parseInt(array_data['height']);
            if (!tih || tih <= 0) tih = 220;
            let tihMobile = parseInt(array_data['height_mobile']);
            if (!tihMobile || tihMobile <= 0) tihMobile = tih;
            let tiShareStart = parseInt(array_data['start_image_share']);
            let tiShareEnd = 100 - tiShareStart;
            let tiImgUrl = array_data['image_url'];
            let tiRowRev = '';
            if(array_data['image_pos'] == "end") tiRowRev = 'flex-direction: row-reverse;';
            if (tiImgUrl == "") tiImgUrl = mpPanelBaseUrl + "/core/_dist/img/image_placeholder.jpg";
            html+= '<div class="pbi-text-image-wrap" style="--tiHeight:' + tih + 'px;--tiHeightMobile:' + tihMobile + 'px;'+tiRowRev+'">';
            html+= '<div class="pidw-iip" style="flex:'+tiShareStart+';"><img class="piw-img" src="'+tiImgUrl+'"></div>';
            html+= '<div class="pidw-iip" style="flex:'+tiShareEnd+';"><p class="piw-p">'+array_data['text']+'</p></div>';
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "map":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            html+= '<div class="pbi-map-wrapper">';
            html+= '<img class="hpp-map" src="'+mpPanelBaseUrl+'/core/_dist/img/block_items_img/pr/preview_map.png"/>'
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "grid":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let grid_data = array_data['grid_data'];
            let theme = array_data['theme'];
            let aspect_ratio = array_data['aspect_ratio'];
            if(aspect_ratio == undefined || aspect_ratio == "") aspect_ratio = "1:1";
            aspect_ratio = aspect_ratio.replace(':', '/');
            let grid_width = array_data['grid_width'];
            if(grid_width > 285) grid_width = 285;
            html+= '<div class="hpp-grid-wrapper hpp-grid-theme'+theme+'">';
            if(grid_data){
                grid_data.forEach(function(gridItem) {
                    html+= '<div class="hpp-gwi-wrapper">';
                    html+= '<img style="width:'+grid_width+'px;aspect-ratio:'+aspect_ratio+'" class="hpp-grid-item" src="'+gridItem['img']+'"/>';
                    html+= '<span class="hpp-grid-text-item">'+gridItem['text']+'</span>';
                    html+= '</div>';
                });
            }
            html+= '</div>';
            html+= '</div>';
            html+= '</div>';
            break;
        case "image_quad":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let img_quad_data = array_data['img_quad_data'];
            if(img_quad_data && img_quad_data.length == 4){
                let h = parseInt(array_data['img_height']);
                if (!h || h <= 0) h = 190;
                let hMobile = parseInt(array_data['img_height_mobile']);
                if (!hMobile || hMobile <= 0) hMobile = h;
                html+= '<div class="hpp-img-quad" style="--qiHeight:' + h + 'px;--qiHeightMobile:' + hMobile + 'px;">';
                html+= '<div class="hppidi1" style="width:25%"><img src="'+img_quad_data[0]['img']+'"/></div>';
                html+= '<div class="hppidi2" style="width:25%"><img src="'+img_quad_data[1]['img']+'"/></div>';
                html+= '<div class="hppidi3" style="width:25%"><img src="'+img_quad_data[2]['img']+'"/></div>';
                html+= '<div class="hppidi4" style="width:25%"><img src="'+img_quad_data[3]['img']+'"/></div>';
                html+= '</div>';
            }else if (img_quad_data && img_quad_data.length == 0){
                let emptyImg = mpPanelBaseUrl + "/core/_dist/img/image_placeholder.jpg";
                html+= '<div class="hpp-img-quad" style="height:100px">';
                html+= '<div class="hppidi1" style="width:25%"><img src="'+emptyImg+'"/></div>';
                html+= '<div class="hppidi2" style="width:25%"><img src="'+emptyImg+'"/></div>';
                html+= '<div class="hppidi3" style="width:25%"><img src="'+emptyImg+'"/></div>';
                html+= '<div class="hppidi4" style="width:25%"><img src="'+emptyImg+'"/></div>';
                html+= '</div>';
            }
            html+= '</div>';
            html+= '</div>';
            break;
        case "group":
            html+= '<div class="pbi-max-limiter">';
            html+= '<div class="pbi-inner-container" style="'+marginStyle+'">';
            let group_col1_data = array_data['group_col1_data'];
            let group_col2_data = array_data['group_col2_data'];

            let start_col_share = parseInt(array_data['start_col_share']);
            let end_col_share = 100 - start_col_share ;

            let groupBoxStyle = 'style="';
            let groupBox_background_color = array_data['background_color'];
            if(groupBox_background_color!=""){
                groupBoxStyle += 'background-color:'+groupBox_background_color+';border-radius:'+array_data['radius']+'px;padding:'+array_data['inner_root_padding']+'px;';
            }
            groupBoxStyle += 'gap:'+(array_data['space_between']/2)+'px;';
            groupBoxStyle += '"';

            let ver_arrange_on_mobile = "";
            if(array_data['ver_arrange_on_mobile'] == "1") ver_arrange_on_mobile = "ver_arrange_on_mobile";

            let divierStyle = "";
            if(array_data['divider'] == "1"){
                divierStyle = 'style="opacity:1;background-color:'+array_data['divider_color']+';"';
            }

            let col_gravity_class = "col-gravity-top";
            if(array_data['gravity'] == "center") col_gravity_class = "col-gravity-center";
            if(array_data['gravity'] == "bottom") col_gravity_class = "col-gravity-bottom";

            if(array_data['ver_arrange_on_mobile'] == "1") ver_arrange_on_mobile = "ver_arrange_on_mobile";

            html+= '<div class="hpp-group-wrapper '+ver_arrange_on_mobile+'" '+groupBoxStyle+'>';
            
            //col 1
            html+= '<div class="hpp-group-col1 '+col_gravity_class+'" style="flex:0 0 '+start_col_share+'%;">';
            if(group_col1_data){
                group_col1_data.forEach(function(col1Item) {
                    //call previewBuilder recursivly to build inner items preview
                    let key = Object.keys(col1Item)[0];
                    let innerJson = JSON.stringify(col1Item);
                    let innerHtml = '<div class="bci-body bci-body-'+key+'">'+previewBuilder(innerJson)+'</div>';
                    html+= '<div class="inner-group-block">'+innerHtml+'</div>';
                });
            }
            html+= '</div>';
            //end col 1
            html+= '<div class="hpp-group-cols-divider" '+divierStyle+'></div>';
            //col 2
            html+= '<div class="hpp-group-col2 '+col_gravity_class+'" style="flex:0 0 '+end_col_share+'%;">';
            if(group_col2_data){
                group_col2_data.forEach(function(col2Item) {
                    //call previewBuilder recursivly to build inner items preview
                    let key = Object.keys(col2Item)[0];
                    let innerJson = JSON.stringify(col2Item);
                    let innerHtml = '<div class="bci-body bci-body-'+key+'">'+previewBuilder(innerJson)+'</div>';
                    html+= '<div class="inner-group-block">'+innerHtml+'</div>';
                });
            }
            html+= '</div>';
            //end col 2

            html+= '</div>';
            
            html+= '</div>';
            html+= '</div>';
            break;
    }

    
    if(html=='') html+= '<span>فاقد پیش‌نمایش</span>';
    return html;

}

function ParagraphPreviewBuilder() {
    if($('.paragraph')[0]){
        $('.paragraph').each(function(i, obj) {
            let text = $(this).find('.p_text').text();
            let spanJs = $(this).find('.p_spanJs').text();
            $(this).find('.p_to_show').html(paragraphPreview(text,spanJs));
        });
    }
}

function Paragraph2PreviewBuilder() {
    if($('.paragraph2')[0]){
        $('.paragraph2').each(function(i, obj) {
            let quill_delta = $(this).find('.p2_quill_delta').text();
            $(this).find('.p_to_show2').html(paragraph2Preview(quill_delta));
        });
    }
}

function SliderPreviewInit() {
    //Post Block Editor slider preview
    new Swiper('.swiper-pbp', {
        loop: true,
        spaceBetween: 10,
        centeredSlides: true,
        autoplay: {
            delay: 2500,
            disableOnInteraction: false
        }
    });
}

function HtmlsBlocksWithAutoHeightInit() {

    $('.html-prev-iframeContainer').each(function () {
        const $container = $(this);
        const htmlId = $container.data('html-id'); // Get the HTML ID

        // Create the iframe
        const $iframe = $('<iframe>', {
            srcdoc: htmlCodes[htmlId], // Load the stored HTML into the iframe
            frameborder: 0,
            scrolling: 'no',
            css: {
                width: '100%', // Make iframe responsive
            }
        });

        // Append the iframe to the container
        $container.append($iframe);

        // Set iframe height automatically after it loads
        $iframe.on('load', function () {
            const iframeDocument = this.contentDocument || this.contentWindow.document;
            const contentHeight = $(iframeDocument).height();
            $(this).height(contentHeight);
        });
    });

    $('.html-aparat-prev-iframeContainer').each(function () {
        const $container = $(this);
        const htmlId = $container.data('html-id'); // Get the HTML ID

        // Create the iframe
        const $iframe = $('<iframe>', {
            srcdoc: htmlCodes[htmlId], // Load the stored HTML into the iframe
            frameborder: 0,
            scrolling: 'no',
            css: {
                width: '100%',
                height: '300px', //aparat views can calc height even after iframe load (it has 2 step load system!)
            }
        });
        // Append the iframe to the container
        $container.append($iframe);
    });
    

}

function AddBlocksBottomFadeWhenBlockOverflow() {

    $('.bci-body-text2').each(function() {
        var $el = $(this);
        var $inner = $el.find('.p_to_show2');
        let textHeight = $inner.outerHeight();
        let maxBlockHeight = $el.outerHeight() + 5;
        //console.log("textHeight = " + textHeight);
        //console.log("maxBlockHeight = " + maxBlockHeight);
        if ($inner.length && textHeight > maxBlockHeight) {
            $el.addClass('block-bottom-fade');
        } else {
            $el.removeClass('block-bottom-fade');
        }
    });

    $('.bci-body-group').each(function() {
        var $el = $(this);
        var $inner = $el.find('.hpp-group-wrapper');
        let innerHeight = $inner.outerHeight();
        let maxBlockHeight = $el.outerHeight() + 5;
        //console.log("innerHeight = " + innerHeight);
        //console.log("maxBlockHeight = " + maxBlockHeight);
        if ($inner.length && innerHeight > maxBlockHeight) {
            $el.addClass('block-bottom-fade');
        } else {
            $el.removeClass('block-bottom-fade');
        }
    });

}

function PostPreviewMotherAction(){

    if($('#big-data-blocks-array-text-area')[0]){

        let bigJson = $('#big-data-blocks-array-text-area').val();

        if((!bigJson) || (bigJson.trim() == '') || (bigJson.trim() == "") ||
            (bigJson.trim() == "null") || (bigJson.trim() == "undefined") ||
            (bigJson.trim() == null)){
                bigJson = "[]";
            }
    
        let BigJson = JSON.parse(bigJson);
        let item_index = 0;
        let html = '';

        let page = $('#additional-data').attr('data-page');
        let postid = $('#additional-data').attr('data-postid');
        if (page == "mainui" || page == "mainuiweb") postid = "0";
        let page_tag = $('#additional-data').attr('data-pagetag');
        let bodyorpreview = $('#additional-data').attr('data-bodyorpreview');
        //let pageUrl = $('#additional-data').attr('data-pageUrl');
        //in group editor we cant add new group item. so hide it when in group editor:
        let hideGroupItemInAdder = $('#additional-data').attr('data-hide-group-item-in-adder');
        //group_mode data:
        let upperPage = $('#additional-data').attr('data-upper-page');
        let groupJsonPos = $('#additional-data').attr('data-group-json-pos');
        let groupColNum = $('#additional-data').attr('data-group-col-num');

        $('#big-data-blocks-array-sortable-list').empty();

        if (Array.isArray(BigJson) && BigJson.length === 0) {

            html+= getEmptyPageIconNoteHtml();
        
        } else {

            BigJson.forEach(function(item) {

                html+= '<div class="bnpb-card-item" data-index="'+item_index+'">';
                html+= '<div class="bnpb-item-main">';
                html+= '<div class="bci-header">';
                html+= '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
                let key = Object.keys(item)[0];
                let value = Object.values(item)[0];
                html+= '<span style="display:none" class="row_code">'+key+'</span>';
                let jsonOfItem = JSON.stringify(item);
                html+= '<textarea style="display:none" class="form-control json_text_area block-item-json" rows="4">'+jsonOfItem+'</textarea>';
                html+= '</div>'; // end of bci-header
                html+= '<div class="bci-body bci-body-'+key+'">'+previewBuilder(jsonOfItem)+'</div>';
                html+= '<div class="row_post_code_text-c"><span class="row_post_code_text">' + getPostItemName(key) + '</span></div>';
                html+= '</div>'; // end of bnpb-item-main
                if(typeof value['visible_for'] !== 'undefined' && value['visible_for'] != "all") {
                    html+= '<div class="bci-visible-for-box">'+getVisibleForTitle(value['visible_for'])+'</div>';
                }
                html+= '<div class="li-toolsbox-v"><div class="ltv-line"></div>';
                html+= '<div class="ltv-data">';
                html+= '<span class="delete-post-block btn-danger-light2 edit-small-btn3 tooltip3" data-index="'+item_index+'"><i class="ph ph-trash"></i><span class="tt3">حذف بلاک</span></span>';
                html+= '<span class="edit-post-block btn-primary-light2 edit-small-btn3 tooltip3" data-index="'+item_index+'" data-page="'+page+'" data-postid="'+postid+'" data-pagetag="'+page_tag +'" data-bodyorpreview="'+bodyorpreview+'" data-upper-page="'+upperPage+'" data-group-json-pos="'+groupJsonPos+'" data-group-col-num="'+groupColNum+'" data-itemkey="'+key+'" data-url="'+mpPanelBaseUrl+'/block-editor/'+page+'/'+postid+'/'+bodyorpreview+'/'+item_index+'/'+upperPage+'/'+groupJsonPos+'/'+groupColNum+'/'+key+'_editor"><i class="ph ph-pencil"></i><span class="tt3">ویرایش بلاک</span></span>';
                html+= '<span class="duplicate-post-block btn-primary-light2 edit-small-btn3 tooltip3" data-index="'+item_index+'"><i class="ph ph-copy"></i><span class="tt3">دوبل کردن بلاک</span></span>';
                html+= '<span class="copy-block-to-clipboard btn-primary-light2 edit-small-btn3 tooltip3" data-index="'+item_index+'"><i class="ph ph-clipboard-text"></i><span class="tt3">کپی بلاک در کلیپ‌بورد</span></span>';
                html+= '<span class="add-post-block-after btn-primary-light2 edit-small-btn3 tooltip3" data-index="'+item_index+'" data-hide-group-item="'+hideGroupItemInAdder+'"><i class="ph ph-plus"></i><span class="tt3">افزودن بلاک جدید در اینجا</span></span>';
                html+= '</div>'; //end of ltv-data
                html+= '<div class="ltv-line"></div></div>'; //end of li-toolsbox-v
                html+= '</div>'; //end of bnpb-card-item
    
                item_index = item_index+1;
                
            });

        }

        $('#big-data-blocks-array-sortable-list').append(html);

        ParagraphPreviewBuilder();
        Paragraph2PreviewBuilder();
        SliderPreviewInit();
        HtmlsBlocksWithAutoHeightInit();
        AddBlocksBottomFadeWhenBlockOverflow();//only in main preview

        $('.pbp-iframe').attr('src', $('.pbp-iframe').attr('src'));

        //editSectionReSizeHappened();

    }
}

function GroupColsPreviewMotherAction(){
    if($('.show-group-col-preview')[0]){
        $('.show-group-col-preview').each(function(index, element) {
            let bigJson = $(element).find('.group-col-json').val();
            let containerElement = $(element).find('.group-col-preview-container');
            RawPreviewGenerator(bigJson, containerElement);
        });
    }
}

function PostMobileDesktopPreviewMotherAction(){
    if($('#content-preview-textarea')[0]){
        let bigJson = $('#content-preview-textarea').val();
        let containerElement = $('#content-preview-container');
        RawPreviewGenerator(bigJson, containerElement);
    }
}

function RawPreviewGenerator(bigJson, containerElement){

    if((!bigJson) || (bigJson.trim() == '') || (bigJson.trim() == "") ||
        (bigJson.trim() == "null") || (bigJson.trim() == "undefined") ||
        (bigJson.trim() == null)){
            bigJson = "[]";
        }

    let BigJson = JSON.parse(bigJson);
    let html = '';
    containerElement.empty();
    let item_index = 0;

    BigJson.forEach(function(item) {
        let key = Object.keys(item)[0];
        let jsonOfItem = JSON.stringify(item);
        html+= '<div class="bnpb-card-item" data-index-preview="'+item_index+'">';
        html+= '<div class="bnpb-item-main">';
        html+= '<textarea style="display:none" class="form-control json_text_area block-item-json" rows="4">'+jsonOfItem+'</textarea>';
        html+= '<div class="bci-body bci-body-'+key+'">'+previewBuilder(jsonOfItem)+'</div>';
        html+= '</div>'; // end of bnpb-item-main
        html+= '</div>'; //end of bnpb-card-item   
        item_index = item_index+1; 
    });

    containerElement.append(html);

    ParagraphPreviewBuilder();
    Paragraph2PreviewBuilder();
    SliderPreviewInit();
    HtmlsBlocksWithAutoHeightInit();

}

function scrollAndEmphasisAnimation(addOrEdit) {

    let index = $('#block-add-or-modify-position').attr('data-pos');

    let elToScroll;
    let elToEmphesis;
    let fakeIndex = 0;
    let realIndex = 0;

    setTimeout(function() {

        if(index == "-1"){
            elToScroll = $('#big-data-blocks-array-sortable-list').children().last();
            elToEmphesis = elToScroll;
        }else{
            index = parseInt(index);
            fakeIndex = index;
            if(addOrEdit == "edit") fakeIndex = index-1;
            if(fakeIndex < 0) fakeIndex = 0;
            realIndex = index+1; //add
            if(addOrEdit == "edit") realIndex = index;
            
            elToScroll = $('.bnpb-card-item[data-index="'+fakeIndex+'"]');
            elToEmphesis = $('.bnpb-card-item[data-index="'+realIndex+'"]');
        }
        //scroll
        elToScroll.get(0).scrollIntoView({behavior: 'smooth'});

        setTimeout(function() {

            elToEmphesis.animate({
                backgroundColor: "#70e8ce59"
            }, 800).delay(300).queue(function() {
            elToEmphesis.animate({
                backgroundColor: "#fff0"
            }, 800).dequeue();
            });

            if(addOrEdit == "add"){
                setTimeout(function() {
                    let currentIndex = elToEmphesis.attr('data-index');
                    $('.bnpb-card-item[data-index="'+currentIndex+'"]').find('.edit-post-block').trigger('click');
                }, 1000);
            }
            
        }, 200);

    }, 100);

}

function scrollAndEmphasisAnimationForPaster(from) {
    let elToScroll;
    let elToEmphesis;
    setTimeout(function() {
        elToScroll = $('#big-data-blocks-array-sortable-list').children().last();
        elToEmphesis = elToScroll;
        if(from == "big-json-paster") elToEmphesis = $('#big-data-blocks-array-sortable-list');
        //scroll
        elToScroll.get(0).scrollIntoView({behavior: 'smooth'});
        setTimeout(function() {
            elToEmphesis.animate({
                backgroundColor: "#70e8ce59"
            }, 800).delay(300).queue(function() {
            elToEmphesis.animate({
                backgroundColor: "#fff0"
            }, 800).dequeue();
            });
        }, 200)
    }, 100);
}

function openBlockAdderDialog(hideGroupItem){

    $('#dialog-holder').append(dialogHtmlGenerator("dialog","post_block_item_adder_dialog"));

    let dialog_id = "#post_block_item_adder_dialog";
    let dialog = $("#post_block_item_adder_dialog");
    let contentBox = $(dialog_id+" .majorisbox-final-content");
    let closeBtn = $(dialog_id+" .majorisbox-close");
    let closeLayout = $(dialog_id+" .majorisbox-close-layout");
    let loadingOverlay = $(dialog_id).find('.majorisbox-loading');
    loadingOverlay.show();
    
    $(dialog_id).fadeIn('fast');
    $("html").css("overflow", "hidden");

    closeBtn.add(closeLayout).click(function () {
        $(dialog_id).fadeOut('fast');
        $('#dialog-holder').find(dialog_id).remove();
        $("html").css("overflow", "auto");
        contentBox.html("");
    });

    contentBox.html("");

    setTimeout(function() {
        $.ajax({
            type: "POST",
            url: mpPanelBaseUrl + "/dialog-html-loader/post_block_item_adder_dialog?hideGroupItem="+hideGroupItem,
            cache: true,
            timeout: 25000,
            success: function (data) {
                contentBox.html(data);
                contentBox.show();
                loadingOverlay.hide();
                
                //https://stackoverflow.com/a/14991189/4565796
                $('#end-of-post-block-add').off().click(function (event) {
                    //https://stackoverflow.com/a/29152483/4565796
                    event.stopImmediatePropagation();
                    let dialog = $("#post_block_item_adder_dialog");
                    dialog.fadeOut('fast');
                    contentBox.html("");
                    $('#dialog-holder').find(dialog_id).remove();
                    $("html").css("overflow", "auto");
                    PostPreviewMotherAction();
                    //actionsListeners();
                    scrollAndEmphasisAnimation("add");
                    
                });

                //new empty block adder
                $('.post-block-add-button').click(function () {
                    let type = $(this).attr('data-type');
                    buildNewEmptyBlockJsonAndSave(type);
                });

            },
            error: function (e) {
                notyf.error("error:" + e.responseText);
                $(dialog_id).fadeOut('fast');
                $('#dialog-holder').find(dialog_id).remove();
                $("html").css("overflow", "auto");
                contentBox.html("");
            }
        });  
    }, 200);

}


function openJsonPasterDialog(isGroupColEditor){

    $('#dialog-holder').append(dialogHtmlGenerator("dialog","post_json_paster_dialog"));

    let dialog_id = "#post_json_paster_dialog";
    let dialog = $("#post_json_paster_dialog");
    let contentBox = $(dialog_id+" .majorisbox-final-content");
    let closeBtn = $(dialog_id+" .majorisbox-close");
    let closeLayout = $(dialog_id+" .majorisbox-close-layout");
    let loadingOverlay = $(dialog_id).find('.majorisbox-loading');
    loadingOverlay.show();
    
    $(dialog_id).fadeIn('fast');
    $("html").css("overflow", "hidden");

    closeBtn.add(closeLayout).click(function () {
        $(dialog_id).fadeOut('fast');
        $('#dialog-holder').find(dialog_id).remove();
        $("html").css("overflow", "auto");
        contentBox.html("");
    });

    contentBox.html("");

    setTimeout(function() {
        $.ajax({
            type: "POST",
            url: mpPanelBaseUrl + "/dialog-html-loader/post_json_paster_dialog?isGroupColEditor="+isGroupColEditor,
            cache: true,
            timeout: 25000,
            success: function (data) {
                contentBox.html(data);
                contentBox.show();
                loadingOverlay.hide();
                
                //https://stackoverflow.com/a/14991189/4565796
                $('#end-of-post-json-paster').off().click(function (event) {
                    //https://stackoverflow.com/a/29152483/4565796
                    event.stopImmediatePropagation();
                    let dialog = $("#post_json_paster_dialog");
                    dialog.fadeOut('fast');
                    contentBox.html("");
                    $('#dialog-holder').find(dialog_id).remove();
                    $("html").css("overflow", "auto");
                    PostPreviewMotherAction();
                    let from = $(this).attr('data-from');
                    scrollAndEmphasisAnimationForPaster(from);
                });

            },
            error: function (e) {
                notyf.error("error:" + e.responseText);
                $(dialog_id).fadeOut('fast');
                $('#dialog-holder').find(dialog_id).remove();
                $("html").css("overflow", "auto");
                contentBox.html("");
            }
        });  
    }, 200);

}


function validateInputJSONInJsonPaster(inputJson,isGroupColEditor) {
    //function of json content paster verify the blocks content json
    function validatePostBlockJson(block,isGroupColEditor) {
        if (typeof block !== "object" || Array.isArray(block) || block === null)
            return false;
        const keys = Object.keys(block);
        if (keys.length !== 1) return false; // Must have exactly one root key
        const rootKey = keys[0];
        if(isGroupColEditor == "1"){
            //in group cols editor we can not have any group block:
            if (rootKey == "group"){
                notyf.error("در ویرایشگر ستون‌های گروه، امکان درج بلاک گروه وجود ندارد.");
                return false;
            }
        }

        let blockName = getPostItemName(rootKey);
        console.log("blockName = " + blockName);
        if( !(/[\u0600-\u06FF]/.test(blockName)) ){ // if !containsPersian
            //if block show name is not farsi, then it is unknown block:
            notyf.error("بلاک محتوایی ناشناخته: " + blockName);
            return false;
        }
        
        return true;
    }
    try {
        const data = JSON.parse(inputJson);
        if (Array.isArray(data)) {
            for (let block of data) {
                if (!validatePostBlockJson(block,isGroupColEditor)) return false;
            }
            return true;
        } else {
            return validatePostBlockJson(data,isGroupColEditor);
        }
    } catch (e) {
        return false;
    }
}


$(function () { // start of document ready:
    
    PostPreviewMotherAction();
    PostMobileDesktopPreviewMotherAction();
    GroupColsPreviewMotherAction();
    //actionsListeners();
    IBJE_DelegatedActionsListeners();
        
    $('#big-data-blocks-array-sortable-list').sortable({
        group: 'list',
        animation: 200,
        delay: 100, // time in milliseconds to define when the sorting should start
        delayOnTouchOnly: true, // only delay if user is using touch
        handle: ".my-handle", // Drag handle selector within list items
        ghostClass: 'ghost',
        onSort: reportPostSortableChange
    });
    
    $('#expand-view-mode').click(function () {
        $(this).addClass('switem-active');
        $('#compress-view-mode').removeClass('switem-active');
        $('.bnpb-list-group').children('div').each(function () {
            $(this).removeClass('bnpb-item-main-compress-view');
        });
    });

    $('#compress-view-mode').click(function () {
        $(this).addClass('switem-active');
        $('#expand-view-mode').removeClass('switem-active');
        $('.bnpb-list-group').children().each(function () {
            $(this).addClass('bnpb-item-main-compress-view');
        });
    });


    $('.invpsb').click(function () {//inner view preview switch btn

        $('.invpsb').removeClass('switem-active');
        $(this).addClass('switem-active');
        let previewType = $(this).attr('id');
        $('.preview-section').css('display','flex');
        $('.preview-inner-view').removeClass('preview-type-inner-view-desktop').removeClass('preview-type-inner-view-mobile').removeClass('preview-type-inner-view-tablet');
        $('.preview-inner-view').addClass('preview-type-'+previewType);
        
        let insidePreviewIframeDiv = $('.pbp-iframe').contents().find('#live-preview-inside-wrapper');
        insidePreviewIframeDiv.removeClass('lpiw-mobile').removeClass('lpiw-tablet').removeClass('lpiw-desktop');

        if(previewType == "inner-view-desktop"){
            $('.pbp-iframe').css('zoom','0.55');
            insidePreviewIframeDiv.addClass('lpiw-desktop');
        } else if(previewType == "inner-view-tablet"){
            $('.pbp-iframe').css('zoom','0.65');
            insidePreviewIframeDiv.addClass('lpiw-tablet');
        } else if(previewType == "inner-view-mobile"){
            $('.pbp-iframe').css('zoom','0.7');
            insidePreviewIframeDiv.addClass('lpiw-mobile');
        }

        //editSectionReSizeHappened();
    });


    // if ($(window).width() < 1440) {
    //     let prView = $('.maje-preview-switcher-box .switem-active');
    //     if (prView.attr('id') == "inner-view-desktop"){
    //         prView.removeClass('switem-active');
    //         $('#inner-view-fullscreen').addClass('switem-active');
    //         $('.preview-section').css('display','none');
    //     }
    // }


    $('#majoris-editor-add-block').click(function() {

        let hideGroupItem = $(this).attr('data-hide-group-item');

        //reset block adder position:
        $('#block-add-or-modify-position').attr('data-pos','-1');
        openBlockAdderDialog(hideGroupItem);

        PostPreviewMotherAction();
        //actionsListeners();

    });  


    //Copy Full Page Json String
    $('.copy-json-block-btn').click(function() {
        let raw = $('#big-data-blocks-array-text-area').val();
        let pretty = raw;
        // try {
        //     let obj = JSON.parse(raw);
        //     pretty = JSON.stringify(obj, null, 2);
        //     //console.log(pretty);
        // } catch (e) {
        //     // If parsing fails, do nothing and copy raw value
        // }
        copyToClipboard(pretty, "کپی تمام محتوای این صفحه در قالب جیسون انجام شد");
    });

    
    $('.paste-json-block-btn').click(function() {
        let isGroupColEditor = $(this).attr('data-is-group-col-editor');
        $('#block-add-or-modify-position').attr('data-pos','-1');
        openJsonPasterDialog(isGroupColEditor);
    }); 

    
    $('.goto-group-col-editor-btn').click(function() {

        //reset block adder position:
        let groupColEditorUrl = $(this).attr('data-url');

        $('#dialog-holder').append(dialogHtmlGenerator("fullscreen","group_col_majoris_editor_dialog"));

        let dialog = $("#group_col_majoris_editor_dialog");
        let dialog_id = "#group_col_majoris_editor_dialog";
        let contentBox = dialog.find(".majorisbox-final-content");
        let closeBtn = dialog.find(".majorisbox-close");
        let closeLayout = $(dialog_id+" .majorisbox-close-layout");
        let loadingOverlay = dialog.find('.majorisbox-loading');

        //hide close options because content editor has auto save and its own back btn
        closeBtn.hide();

        contentBox.hide();

        dialog.fadeIn('fast');
        $("html").css("overflow", "hidden");

        loadingOverlay.show();

        contentBox.show();
        contentBox.html("");

        setTimeout(function() {

            loadingOverlay.hide();
            let iframeHtml = '<iframe id="group-col-majoris-editor-iframe" scrolling="no" style="width:100%;height:100%" src="'+groupColEditorUrl+'" title="description"></iframe>';
            contentBox.html(iframeHtml);
            let iframe = $('#group-col-majoris-editor-iframe');
            iframe.on('load', function(){
                iframe.contents().find('#group-col-majoris-editor-back-btn').click(function(event){
                    
                    //refresh parent block editor content:
                    let colNum = $(this).attr('data-col-num');
                    let groupBigJson = iframe.contents().find('#big-data-blocks-array-text-area').val();
                    console.log("groupBigJson = " + groupBigJson);
                    $('#group_col'+colNum+'_data').val(groupBigJson);
                    GroupColsPreviewMotherAction();

                    setTimeout(function() {
                        $(dialog_id).fadeOut('fast');
                        $('#dialog-holder').find(dialog_id).remove();
                        $("html").css("overflow", "auto");
                        contentBox.html("");
                    }, 200);

                });
            });
            
        }, 200);

    }); 


    //json pretty in json paster textarea
    $(document).on('paste', '.json-paster-textarea', function (e) {
        let textarea = $(this);
        setTimeout(function () {
            let raw = textarea.val().trim();
            try {
                let obj = JSON.parse(raw);
                let pretty = JSON.stringify(obj, null, 2);
                //console.log(pretty);
                textarea.val(pretty);
            } catch (err) {
                // Invalid JSON, do nothing
            }
        }, 100);
    });

    
    $(document).on('click', '#post-json-paster-final-btn', function (e) {
        
        let isGroupColEditor = $(this).attr('data-is-group-col-editor');

        let raw = $('#json-paster-textarea').val().trim();
        if (!raw) {
            notyf.error("هیچ دیتایی وارد نشده");
            return;
        }

        //check if json valid and structure is correct (have a key even check the key type!)
        if(raw != "[]"){
            if (!validateInputJSONInJsonPaster(raw,isGroupColEditor)) {
                notyf.error("فرمت JSON صحیح نیست یا بلاک‌های محتوایی نامعتبر دارد");
                return;
            }
        }

        //if json is array check if big_json_is_empty
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) {
            let bigJson = $('#big-data-blocks-array-text-area').val().trim();
            if(bigJson.length > 10){
                notyf.error("برای درج تمام محتوا یک صفحه بصورت یکجا، این صفحه باید خالی باشد");
                return;
            }
        }

        //add to big_data and save to db with group consideration
        if (Array.isArray(parsed)) {
            //full json paster
            saveBigJsonToDatabaseWithGroupHandling(parsed,"big-json-paster");
        }else{
            //add item to end of big-data
            saveBlockJsonToBigDataAndDatabase(parsed,"single-block-paster");
        }

    });
    
}); //end of jqury doc ready