document.addEventListener( "DOMContentLoaded", function( event ) {

    const entity_sec = document.querySelector( "#entity" );
    if ( ! entity_sec ) return;

    const main = entity_sec.querySelector( ":scope > .main" );
    const entitys_el = main.querySelector( ":scope > .entitys" );

    const search_options = {
        widget: entity_sec.querySelector( ":scope > .header .search.widget" ),
        api_fn: "get_entity_list",
        answer_fn: set_entity_list,
    }

    const search = search_widget_controls( search_options ); //: { widget, search_run_fn }

    const pager_options = {
        footer: entity_sec.querySelector( ":scope > .footer" ),
        cookie: "entity_pager",
        api_fn: "get_entity_list",
        answer_fn: set_entity_list,
        search: search,
    }

    function __( str ) {
        return _( str, "entity.mod.php" );
    }

    api( { fn: "get_entity_list" }, set_entity_list, function( answer ) {
        console.log( "mod ecs: get_entity_list error" );
    } );

    function set_entity_list( answer ) {
        if ( answer.error ) {
            console.error( answer.error );
        }

        if ( ! answer.result ) {
            return;
        }

        entitys_el.innerHTML = "";
        const loaded_el = pager_options.footer.querySelector( ".loaded" );
        loaded_el.value = "0";

        // Всего страниц в БД
        const count_el  = pager_options.footer.querySelector( ".count" );
        count_el.innerText = answer.result.count;

        for ( let i = 0; i < answer.result.entitys.length; i++ ) {
            entitys_el.insertAdjacentHTML( "beforeend", answer.result.entitys[i].html );
            loaded_el.value = +loaded_el.value + 1;
        }

        create_pager( pager_options );
    }

    const add_entity_btn = entity_sec.querySelector( ".header .add.button" );
    add_entity_btn.addEventListener( "click", function( event ) {
        api( { fn: "create_entity" }, function( answer ) {
            set_entity_list( answer );
            if ( answer.result ) {

            }
        } );
    } );

} );