let updateContentTableTimeout;

function jsonTableRowHtmlMacker(printDeletesRow, json, colCount) {

    let htmlRow = "";
    let deleteRowId = randomUID(21);
    htmlRow += '<div class="json_content_table_card ng-card-json-item global-json-handler-card drid-'+deleteRowId+'">';
    htmlRow += '<div class="json_content_table_box ng-spec-card">';

    if (printDeletesRow){

        //add a hidden div width 30px to only align delete btns on top
        htmlRow += '<div style="width:30px;min-width:30px;"></div>';
        htmlRow += '<div class="deletebtnsbox">';
        for (let i = 0; i < colCount; i++) {
            let deleteColId = randomUID(21);
            htmlRow += '<div class="jct-delete-btn-wrapper"><button type="button" data-dcid="'+deleteColId+'" class="content-table-delete-col-btn btn btn-danger btn-sm tooltip3"><i class="ph ph-trash"></i><span class="tt3">حذف ستون</span></button></div>';
        }
        htmlRow += '</div>';
        //add a hidden btn to only align delete btns on top
        htmlRow += '<button type="button" disabled style="opacity:0;cursor: default;" class="btn btn-sm"><i class="ph ph-trash"></i></button>';
        
    }else{

        htmlRow += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
        htmlRow += '<div class="ct-textareabox">';
        
        for (let i = 0; i < colCount; i++) {
            let element = "";
            if(json != null) element = json[i];
            let delColId = $('.deletebtnsbox').children().eq(i).find('.content-table-delete-col-btn').attr('data-dcid');
            htmlRow += '<textarea name="jtt" rows="2" class="js_content_table_text form-control dcid-'+delColId+'">'+ element +'</textarea>';
        }
        
        htmlRow += '</div>';
        htmlRow += '<button type="button" data-drid="'+deleteRowId+'" class="content-table-delete-row-btn btn btn-danger btn-sm tooltip3"><i class="ph ph-trash"></i><span class="tt3">حذف ردیف</span></button>';
    
    }
    
    htmlRow += '</div>';
    htmlRow += '</div>';

    return htmlRow;
}

const jsonTableRowDeleteBtn = function () {
    
    let rowCount = $('#add_json_table_row_array_item').attr('data-row-count');
    let newRowCount = parseInt(rowCount) - 1;
    if(newRowCount <= 0){
        notyf.error("تعداد ردیف‌ها نمی‌تواند کمتر از 1 باشد");
    }else{
        let drid = $(this).attr('data-drid');
        $('.drid-'+drid).remove();
        $('#add_json_table_col_array_item').attr('data-row-count',newRowCount);
        $('#add_json_table_row_array_item').attr('data-row-count',newRowCount);
        jsonContentTableUpdate();
    }
    
};

const jsonTableColDeleteBtn = function () {

    let colCount = $('#add_json_table_col_array_item').attr('data-col-count');
    let newColCount = parseInt(colCount) - 1;

    if(newColCount <= 0){
        notyf.error("تعداد ستون‌ها نمی‌تواند کمتر از 1 باشد");
    }else{
        let dcid = $(this).attr('data-dcid');
        $('.dcid-'+dcid).remove();
        $(this).closest('.jct-delete-btn-wrapper').remove();
        $('#add_json_table_col_array_item').attr('data-col-count',newColCount);
        $('#add_json_table_row_array_item').attr('data-col-count',newColCount);
        jsonContentTableUpdate();
    }
    
};

const tableTextAreaUserInputUpdaterWithDelay = function () {
    //make sure user typing is ended and after that save the table
    clearTimeout(updateContentTableTimeout);
    updateContentTableTimeout = setTimeout(() => {
        jsonContentTableUpdate();
    }, 800);
};

function jsonContentTableUpdate() {

    let textarea = $('.json_handler_table_array').find('.json_text_area');

    let tableJson = [];

    $("#sorable_list .json_content_table_card").each(function() {
        let row = [];
        $(this).find("textarea.js_content_table_text").each(function() {
            row.push($(this).val().trim());
        });
        if (row.length > 0) {
            tableJson.push(row);
        }
    });

    let stringjs = JSON.stringify(tableJson);
    textarea.val(stringjs);

};

$(function () { // start of document ready:

    if ($(".json_handler_table_array")[0]) { //there is json type 1 array list:

        const jsonString = $.trim($('.json_handler_table_array > textarea').val());
        let jsonTableArrayObj;

        if (jsonString == '') {
            jsonTableArrayObj = [];

        } else {
            jsonTableArrayObj = JSON.parse(jsonString);
        }

        if (jsonTableArrayObj.length == 0) {
            jsonTableArrayObj = JSON.parse('[["",""],["",""]]');
        }

        $('#add_json_table_col_array_item').attr('data-row-count',jsonTableArrayObj.length);
        $('#add_json_table_row_array_item').attr('data-row-count',jsonTableArrayObj.length);

        let colCount = jsonTableArrayObj[0].length;
        const htmlDeleteRow = jsonTableRowHtmlMacker(true,null,colCount);
        $(".json_handler_table_array").find(".showbox").find("#sorable_list").append(htmlDeleteRow);

        let pos = 0;
        $.each(jsonTableArrayObj, function (key, value) {
            //console.log("value.length: " + value.length);
            $('#add_json_table_col_array_item').attr('data-col-count',value.length);
            $('#add_json_table_row_array_item').attr('data-col-count',value.length);
            const htmlrow = jsonTableRowHtmlMacker(false,value,value.length);
            $(".json_handler_table_array").find(".showbox").find("#sorable_list").append(htmlrow);
            pos++;
        });
        

    }

    $('#add_json_table_row_array_item').click(function () {

        let colCount = $(this).attr('data-col-count');
        let rowCount = $(this).attr('data-row-count');
        //console.log("colCount: " + colCount);
        //console.log("rowCount: " + rowCount);
        const root = $(this).closest('.json_handler_table_array');

        if (root.find('.no-item-found').length > 0) {
            root.find('.no-item-found').remove();
            const htmlDeleteRow = jsonTableRowHtmlMacker(true,null,colCount);
            root.find(".showbox").find("#sorable_list").append(htmlDeleteRow);
        }

        const htmlrow = jsonTableRowHtmlMacker(false,null,colCount);
        root.find(".showbox").find("#sorable_list").append(htmlrow);

        let count = root.find(".showbox").find("#sorable_list").children().length - 1; // first row is delete rows btn row is dont count it
        $('#add_json_table_col_array_item').attr('data-row-count',count);
        $('#add_json_table_row_array_item').attr('data-row-count',count);

        //$('.content-table-delete-row-btn').off('click').on('click', jsonTableRowDeleteBtn);

        jsonContentTableUpdate();

    });


    $('#add_json_table_col_array_item').click(function () {

        let rowCount = $(this).attr('data-row-count') || 0;
        let colCount = $(this).attr("data-col-count") || 0;        

        let deleteColId = randomUID(21);
        // add one empty textarea to every row
        $("#sorable_list .ct-textareabox").each(function () {
            $(this).append('<textarea name="jtt" rows="2" class="js_content_table_text form-control dcid-'+deleteColId+'"></textarea>');
        });

        $(".deletebtnsbox").append('<div class="jct-delete-btn-wrapper"><button type="button" data-dcid="'+deleteColId+'" class="content-table-delete-col-btn btn btn-danger btn-sm tooltip3"><i class="ph ph-trash"></i><span class="tt3">حذف ستون</span></button></div>');

        let newColCount = parseInt(colCount) + 1;
        $('#add_json_table_col_array_item').attr('data-col-count',newColCount);
        $('#add_json_table_row_array_item').attr('data-col-count',newColCount);

        //$('.content-table-delete-col-btn').off('click').on('click', jsonTableColDeleteBtn);

        jsonContentTableUpdate();

    });

    // update 2025: we now use delegate input binding
    // $('.content-table-delete-row-btn').off('click').on('click', jsonTableRowDeleteBtn);
    // $('.content-table-delete-col-btn').off('click').on('click', jsonTableColDeleteBtn);

    // delegate input binding (covers new and existing textareas)
    // https://chatgpt.com/share/68adc4fb-4160-8004-8f17-196780a224b4
    $(document).on("input", ".js_content_table_text", tableTextAreaUserInputUpdaterWithDelay);
    $(document).on("click", ".content-table-delete-col-btn", jsonTableColDeleteBtn);
    $(document).on("click", ".content-table-delete-row-btn", jsonTableRowDeleteBtn);

    
}); //end of jqury doc ready
