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

    const comments_sec = document.querySelector( "#comments" );
    if ( ! comments_sec ) return;

    const main = comments_sec.querySelector( ":scope > .main" );
    const comments_el = main.querySelector( ":scope > .comments" );

    const settings_button = comments_sec.querySelector( ".settings.button" );
    const close_button = comments_sec.querySelector( ".close.button" );

    const settings_el = comments_sec.querySelector( ".settings.panel" );
    const banned_el = settings_el.querySelector( ".banned" );

    const search_options = {
        widget: comments_sec.querySelector( ":scope > .header .search.widget" ),
        api_fn: "get_comments_list",
        answer_fn: set_comments_list,
    }

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

    const pager_options = {
        footer: comments_sec.querySelector( ":scope > .footer" ),
        cookie: "comments_pager",
        api_fn: "get_comments_list",
        answer_fn: set_comments_list,
        search: search,
    }

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

    api( { fn: "get_comments_list" }, set_comments_list, function( answer ) {
        console.log( "mod comments: get_comments_list error" );
    } );
    api( { fn: "get_banned_list" }, set_banned_list, function( answer ) {
        console.log( "mod comments: get_banned_list error" );
    } );
    

    function set_comments_list( answer ) {
        const result = answer.result;

        if ( result.overload ) {
            notify_answer( answer );
        }

        comments_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;

        // insert comments
        let start = Date.now();
        for ( let i = 0; i < result.comments.length; i++ ) {
            comments_el.insertAdjacentHTML( "beforeend", result.comments[i].html );
            loaded_el.value = +loaded_el.value + 1;
            set_controls( result.comments[i].id );
            if ( Date.now() - start > 1000 ) {
                let message = __( "browser_overloaded_xxx" );
                message = message.replace( "xxx", i + 1 );
                message = message.replace( "nnn", result.comments.length );
                notify_answer( { "result": { "notify_html": message } } );
                break;
            }
        }

        create_pager( pager_options );

    }

    function set_controls( id ) {
        
        // Опубликовать комментарий
        comments_el.querySelectorAll( `[data-id="${id}"] .public.button` ).forEach( function( button ) {
            button.addEventListener( "click", function( event ) {
                api( { fn: "comment_publish", id: id }, function( answer ) {
                    notify_answer( answer );
                    const comment = comments_el.querySelector( `[data-id="${id}"]` );
                    if ( answer.result.date !== null ) {
                        comment.classList.remove( "unpublished" );
                        comment.classList.add( "published" );
                    } else {
                        comment.classList.remove( "published" );
                        comment.classList.add( "unpublished" );
                    }
                    button.innerText = answer.result.button_text;
                } );
            } );
        } );

        // Ban
        comments_el.querySelectorAll( `[data-id="${id}"] .ban.button` ).forEach( function( button ) {
            button.addEventListener( "click", function( event ) {
                const comment = button.closest( "[data-id]" );
                let uid  = comment.getAttribute( "data-uid" );
                let name = comment.querySelector( ".name" ).innerText;
                api( { fn: "comment_ban", id: id, uid: uid, name: name }, function( answer ) {
                    notify_answer( answer );
                    if ( answer.result ) {
                        api( { fn: "get_banned_list" }, set_banned_list );
                    }
                } );
            } );
        } );

    }

    // Delete comments
    comments_sec.querySelectorAll( ".header .trash.button" ).forEach( function( button ) {
        button.addEventListener( "click", function( e ) {
            let ids = [];
            comments_el.querySelectorAll( "input[type=checkbox]:checked" ).forEach( function( ch ) {
                let id = ch.closest( "[data-id]" ).getAttribute( "data-id" );
                ids.push( id );
            } );
            if ( ids.length === 0 || ! confirm( __( "confirm_delete_comments" ) ) ) {
                return;
            }
            let data = {
                fn: "del_comments",
                ids: ids
            };
            api( data, function( answer ) {
                notify_answer( answer );
                if ( answer.result ) {
                    pager_options.search.search_run_fn();
                }
            } );
        } );
    } );

    // Открыть настройки
    settings_button.addEventListener( "click", function( event ) {
        settings_el.classList.remove( "hidden" );
    } );

    // Закрыть настройки
    close_button.addEventListener( "click", function( event ) {
        settings_el.classList.add( "hidden" );
    } );

    function set_banned_list( answer ) {
        banned_el.innerHTML = "";
        const ban_list = answer.result.ban_list;
        for ( let i = 0; i < ban_list.length; i++ ) {
            banned_el.insertAdjacentHTML( "beforeend", ban_list[i].html );
            set_ban_controls( ban_list[i].id );
        }

    }

    function set_ban_controls( id ) {
        banned_el.querySelectorAll( `[data-id="${id}"] .delete` ).forEach( function( button ) {
            button.addEventListener( "click", function( event ) {
                let id = button.closest( "[data-id]" ).getAttribute( "data-id" );
                api( { fn: "comment_unban", id: id }, function( answer ) {
                    notify_answer( answer );
                    banned_el.querySelector( `[data-id="${id}"]` ).remove();
                } );
            } );
        } );
    }

    // Сохранить настройки
    settings_el.querySelector( ".button.save" ).addEventListener( "click", function( e ) {

        const data = {
            fn: "comments_save_settings",
            moderation:        settings_el.querySelector( "input[name='moderation']" ).checked,
            email:             settings_el.querySelector( "input[name='email']" ).value,
            smtp_host:         settings_el.querySelector( "input[name='smtp_host']" ).value,
            smtp_port:         settings_el.querySelector( "input[name='smtp_port']" ).value,
            smtp_login:        settings_el.querySelector( "input[name='smtp_login']" ).value,
            smtp_password:     settings_el.querySelector( "input[name='smtp_password']" ).value,
            comments_per_page: settings_el.querySelector( "input[name='comments_per_page']" ).value,
        };
        api( data, function( answer ) {
            notify_answer( answer );
        } );

    } );

} );
