<style>
    .ListRowCard {
        margin-bottom: 20px;
    }
</style>

<div id='ListMainContainer'>




</div>


<script>




    LoadDataPageFunc = {};

    LoadDataPageFunc.NewRow = function (objectdata, rownum) {

        let name = objectdata.name;
        let unit = objectdata.unit || '';
        let price = objectdata.price;
        let description = objectdata.description || '';
        let imgurl = objectdata.photo
        let imgwidthheight = 150;
        let hashkey = objectdata.hashkey;
        let ahreflink = "ButtonGo('BuyViewProductMarket','" + hashkey + "');";
        const maxDescriptionChars=80;
        

        //imgurl = LoadDataPageFunc.GetPhotoURL(imgurl, rownum);

        const columnsize = '6';
        let brdescbefore = '';
        if (description) {
            brdescbefore = '<br><br>';
        }

        if (description.length > maxDescriptionChars) {
        description = description.substring(0, maxDescriptionChars) + '...';
    }


        imagehtml = `<img id="marketplacelistproductphoto-${rownum}" src="/RequestData/File/${imgurl}" loading="lazy" class="" style="width: 60%;height: 60%;object-fit: contain;">`;

        const style = "width: 100%; height: 100%; object-fit: cover;";


        return `<div class="col-${columnsize}" style="overflow:hidden; padding-bottom:10px;">
    <a href="javascript:void(0);" onclick="${ahreflink}">
    <div class="card ListRowCard" id="ListRowCard-${rownum}" style="${style}">
<div id="cardheader-ListRowCard-${rownum}" class="card-header ui-sortable-handle" style="cursor: move;display:none;">
<h3 class="card-title" style="" id="card-title-ListRowCard-${rownum}"></h3>
<div class="card-tools" id="card-tools-ListRowCard-${rownum}">

</div>
</div>
<div class="card-body ListCardRow" id="card-body-ListRowCard-${rownum}">
<div style="text-align:center;">
${imagehtml}
</div>
<br>
<div class="row" style=""><div class="col"><h3>${name}</h3></div><div class="col">P${price} / ${unit}</div></div>
${brdescbefore}
<h5>${description}</h5>
<br>
</div>
</div>
</a>
</div>`;

    };

    LoadDataPageFunc.InitializeDynamicVariables = function () {
        LoadDataPageFunc.URLs.QueryListData = '/Market/Products/List';

        LoadDataPageFunc.Settings.ViewDetailsOnclick = function (data) {
            return `ButtonGo('ViewLeadDetails', '${data}')`;
        };

        LoadDataPageFunc.Settings.CurrentTargetRequired = false;

        LoadDataPageFunc.Settings.DefaultDatatoSend = null;

        LoadDataPageFunc.GetPhotoURL = function (imgurl, rownum) {
            if (!imgurl || !(typeof imgurl === 'string' && imgurl.length < 72)) { return '/assets/noproductphoto.png'; }

            imghash= imgurl.slice(-72);

           // photoblob = fileBlobURLList[imgurl] || false;

            photoblob = Preloaders.getfileBlobURL(imghash);

            if (photoblob){
                $('#marketplacelistproductphoto-' + rownum).attr('src', bloburl);
            }else{$('#marketplacelistproductphoto-' + rownum).attr('src', imgurl);}

       /*      imgurl = '/RequestData/File/' + imgurl;
            LoadAndCreateURLfromFileHash(imgurl).then(bloburl => {
                if (!bloburl) {
                    bloburl = '/assets/noproductphoto.png';
                    imgurl = '/assets/noproductphoto.png';
                }
                $('#marketplacelistproductphoto-' + rownum).attr('src', bloburl);

            }).catch((err) => {
                imgurl = '/assets/noproductphoto.png';
            }); */

            return imgurl;

        };




        LoadDataPageFunc.Settings.SortArray = function (arr) {
            return arr.sort((a, b) => new Date(b.created) - new Date(a.created));
        };
    };

    LoadDataPageFunc.Settings = {};
    LoadDataPageFunc.Settings.PageName = 'List';
    LoadDataPageFunc.Settings.DefaultCardNoDetailsMessage = 'No Data';
    LoadDataPageFunc.Settings.DefaultRequestType = 'POST';
    LoadDataPageFunc.Settings.fromVarCache = true;
    LoadDataPageFunc.Settings.SortArray = function (arr) {
        return arr.sort((a, b) => new Date(b.created) - new Date(a.created));
    };


    LoadDataPageFunc.ids = {};
    LoadDataPageFunc.ids.MainContainer = 'ListMainContainer';
    LoadDataPageFunc.ids.SearchInput = 'List_Search';
    LoadDataPageFunc.ids.ListContainer = 'ListRowCard';
    LoadDataPageFunc.ids.HashKeyContainer = 'ListRowCardHash';
    LoadDataPageFunc.ids.MainCardBody = 'MAINCARDBODY_LIST';

    LoadDataPageFunc.URLs = {};






    $$$ = {};
    $$$.UpdateMainContainer = function (html) {
        $('#' + LoadDataPageFunc.ids.MainContainer).html(html);
    };

    LoadDataPageFunc.Settings = {};
    LoadDataPageFunc.Settings.ViewDetailsOnclick = function (data) {
        return `ButtonGo('ViewDetails', '${data}')`;
    };


    LoadDataPageFunc.CheckCachefromURLandChangeURLToBlob = function (photourl) {
        if (!photourl) { return ''; }
        photoblob = reqcacheload(photourl);
        if (photoblob) {
            photourl = URL.createObjectURL(photoblob);
        }
        return photourl;
    }



    LoadDataPageFunc.ClearSearch = function () {
        $('#' + LoadDataPageFunc.ids.SearchInput).val('');
        $('#' + LoadDataPageFunc.ids.SearchInput).trigger('keyup');
    };

    LoadDataPageFunc.GenerateListfromResponse = function (response) {

        let newhtmlrows = ''; let htmlarrayrows = [];
        const count = response.length;
        let hashkey;
        let colsize = '6';
        htmlarrayrows.push('<div class="row">');
        for (let i = 0; i < count; i++) {
            htmlarrayrows.push(LoadDataPageFunc.NewRow(response[i], i));
        }
        htmlarrayrows.push('</div>');
        newhtmlrows = htmlarrayrows.join('');

        return newhtmlrows;

    };



    LoadDataPageFunc.MemoizeGenerateListResponse = memoize(LoadDataPageFunc.GenerateListfromResponse);




    LoadDataPageFunc.CardResultInterSectionPreloadDetails = function () {
        let hashkey = '';
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const cardId = $(entry.target).attr('id');
                    const variablePart = cardId.split('-')[1];
                    const hashKeyDivId = LoadDataPageFunc.ids.HashKeyContainer + '-' + variablePart;
                    hashkey = $('#' + hashKeyDivId).text();
                    if (hashkey) {
                        request.url('/ViewLead/Details/data').success((response) => {
                        }).data({ target: hashkey }).fromVarCache(true).type('POST').go();
                    }
                    hashkey = '';
                }
            });
        }, { threshold: 0.1 });


        $('#' + LoadDataPageFunc.ids.ListContainer + ' .card').each(function () {
            observer.observe(this);
        });
    };

    LoadDataPageFunc.populatelist = function () {

        let request = new RequestData(true);
        request
            .url(LoadDataPageFunc.URLs.QueryListData)
            .type(LoadDataPageFunc.Settings.DefaultRequestType)
            .data(null)
            .fromVarCache(true)
            .success((response) => {


                if (!response) {
                    $('#card-body-' + LoadDataPageFunc.ids.MainCardBody).html(LoadDataPageFunc.Settings.DefaultCardNoDetailsMessage);
                    return;
                }

                let List = response;

                //let newhtmlrows =LoadDataPageFunc.MemoizeGenerateListResponse(List);
                newhtmlrows = LoadDataPageFunc.GenerateListfromResponse(List);

                $('#' + LoadDataPageFunc.ids.ListContainer).html(newhtmlrows);
                
                iterateArray(List,(item,key)=>{
                    LoadDataPageFunc.GetPhotoURL(item['photourl'],key);
                });
                LoadDataPageFunc.CardResultInterSectionPreloadDetails();

                //Disabled IMG URL caching from varcache and BLob due to massive slowdown
                //now Relying on service worker
                //interceptImageSrcandChangetoBlob(fromvarcache = true, replacewithnologo = true);

            })
            .error((err) => {
                console.error(err);
            })
            .go();

    };




    LoadDataPageFunc.SearchKeyUPListPage = function () {
        $('#' + LoadDataPageFunc.ids.SearchInput).on('keyup', function () {

            let searchTerm = $(this).val().toLowerCase();

            $('#' + LoadDataPageFunc.ids.ListContainer + ' .card').each(function () {

                let title = $(this).find('.card-title').text().toLowerCase();
                let cols = $(this).find('.col').text().toLowerCase();
                let h4 = $(this).find('h4').text().toLowerCase();
                let h3 = $(this).find('h3').text().toLowerCase();
                let h2 = $(this).find('h2').text().toLowerCase();
                let h1 = $(this).find('h1').text().toLowerCase();
                let h5 = $(this).find('h5').text().toLowerCase();
                let h6 = $(this).find('h6').text().toLowerCase();

                if (title.includes(searchTerm) || cols.includes(searchTerm) ||
                    h1.includes(searchTerm) || h2.includes(searchTerm) || h3.includes(searchTerm)
                    || h4.includes(searchTerm) || h5.includes(searchTerm) || h6.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
    };

    LoadDataPageFunc.main = function () {
        if (LoadDataPageFunc.Settings.CurrentTargetRequired && (!currenttarget || currenttarget === '0')) {
            $$$.UpdateMainContainer('<center>No Target<br><br>' + buttonprimary('View All Leads', '', "ButtonGo('ListLeads', '')") +
                '<br><br>' + buttonprimary('Home', '', "ButtonGo('Home', '')") + '</center>'); return false;
        }
        const searchcard = UIInputGroup('Search', 'text', LoadDataPageFunc.ids.SearchInput, '', classs = '', span = '', '/assets/clear.png');
        let LeadsListContainer = UICardSimple('', 'Loading Please Wait...', LoadDataPageFunc.ids.ListContainer);
        LeadsListContainer = '<div id="' + LoadDataPageFunc.ids.ListContainer + '"><center>Loading Please Wait...</center></div>';
        const FinalInnerHTML = searchcard + LeadsListContainer;
        const MainCard = UICardSimple('', FinalInnerHTML, LoadDataPageFunc.ids.MainCardBody);

        $$$.UpdateMainContainer(MainCard);
        return true;

    };

    LoadDataPageFunc.LoadNow = function () {
        LoadDataPageFunc.InitializeDynamicVariables();
        LoadDataPageFunc.main();
        LoadDataPageFunc.populatelist();
        changeTopbarTitle(LoadDataPageFunc.Settings.PageName);
        LoadDataPageFunc.SearchKeyUPListPage();
        changeTopbarTitle('Products');
        $('#imgspan' + LoadDataPageFunc.ids.SearchInput).attr('onclick', 'LoadDataPageFunc.ClearSearch();');
    };

    LoadDataPageFunc.LoadNow();



</script>