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

/*translate*/

    // Подсветить коммент если открыт по ссылке
    let hash = window.location.hash;
    if ( hash ) {
        let name = hash.substr( 1 );
        let anchor = document.querySelector( `a[name="${name}"]` );
        if ( anchor ) {
            let comment = anchor.parentElement;
            comment.classList.add( "highlight" );
        }
    }

    function __( str ) {
        if ( typeof translate === 'undefined' ) return str;
        if ( typeof translate[str] === 'undefined' ) return str;
        return translate[str];
    }

    function get_cookie( name ) {
        let cookies = document.cookie.split( ";" );
        for ( let line of cookies ) {
            let cookie = line.split( "=" );
            if ( name == cookie[ 0 ].trim() ) {
                return decodeURIComponent( cookie[ 1 ] );
            }
        }
        return "";
    }
    
    function set_cookie_expires( name, value ) {
        let expires = ( new Date( Date.now() + 365 * 86400 * 1000 ) ).toUTCString();
        document.cookie = encodeURIComponent( name ) + "=" + encodeURIComponent( value ) + ";SameSite=Lax;Path=/;expires=" + expires;
    }

    function api( data, rfn ) {
        const formData = new FormData();
        for ( let key in data ) {
            if ( ! data.hasOwnProperty( key ) ) continue;
            if ( Array.isArray( data[key] ) ) {
                for ( let key2 in data[key] ) {
                    formData.append( key + "[]", data[key][key2] );
                }
            } else {
                formData.append( key, data[key] );
            }
        }
        let ajax = new XMLHttpRequest();
        ajax.addEventListener( "load", function( event ) {
            let data = JSON.parse( event.target.responseText );
            if ( rfn ) {
                rfn( data );
            }
        } );
        ajax.open( "POST", base_path + "comments_api" );
        ajax.send( formData );
    }


    // Reply Buttons
    document.querySelectorAll( ".reply, .leave-comment-btn" ).forEach( function( button ) {

        if ( typeof limit_exceeded !== "undefined" ) {

            button.remove();

        } else {

            button.addEventListener( "click", reply );

        }

    } );

    function reply( e ) {

        const in_comment = this.closest( ".comment" );
        let rid = 0;
        let target = this;

        if ( in_comment ) {
            rid = in_comment.getAttribute( "data-id" );
            target = in_comment;
        }

        const exists = document.querySelector( `.leave-comment[data-rid="${rid}"]` );
        if ( exists ) {
            return;
        }

        let help = "";
        if ( moderation ) {
            help = __( "moderated" );
        }
        
        const html_form = `
        <div class=leave-comment data-rid=${rid}>
            <div class=header>
                <div class=answer>${help}</div>
                <div class=close><div class=x1></div><div class=x2></div></div>
            </div>
            <div class=input-group>
                <label>` + __( "name" ) + `</label>
                <input name=name>
                <input name=rid type=hidden value=${rid}>
            </div>
            <div class=input-group>
                <label>` + __( "email" ) + `</label>
                <input name=email>
            </div>
            <div class=input-group>
                <label>` + __( "comment" ) + `</label>
                <textarea name=text maxlength=10000></textarea>
            </div>
            <div class=send>` + __( "send" ) + `</div>
        </div>`;

        if ( rid ) {
            target.insertAdjacentHTML( "afterend", html_form );
        } else {
            target.insertAdjacentHTML( "beforebegin", html_form );
            let container = this.closest( ".comments" );
            container.scrollTo( 0, container.scrollHeight );
        }

        const form = document.querySelector( `.leave-comment[data-rid="${rid}"]` );

        form.querySelector( "textarea" ).addEventListener( "keyup", function( event ) {
            this.style.height = "";
            if ( this.offsetHeight < this.scrollHeight ) {
                this.style.height = (this.scrollHeight+2) + "px";
            }
        } );

        form.querySelector( ".close" ).addEventListener( "click", function( event ) {
            this.closest( ".leave-comment" ).remove();
        } );

        form.querySelector( ".send" ).addEventListener( "click", function( event ) {
            
            let uid = get_cookie( "cms_comments_uid" );
            if ( uid == "" ) {
                if ( window.location.protocol === "https:" ) {
                    uid = crypto.randomUUID();
                } else {
                    uid = uuidv4();
                }
                set_cookie_expires( "cms_comments_uid", uid );
                uid = get_cookie( "cms_comments_uid" ); // not bot
            }

            const data = {
                fn:    "post_comment",
                pid:   pid,
                name:  form.querySelector( `input[name="name"]` ).value,
                email: form.querySelector( `input[name="email"]` ).value,
                text:  form.querySelector( `textarea[name="text"]` ).value,
                rid:   form.querySelector( `input[name="rid"]` ).value,
            }

            if ( data.name.trim() == "" ) {
                alert( __( `no_name` ) );
                return;
            }
    
            if ( data.text.trim() == "" ) {
                alert( __( `no_comment` ) );
                return;
            }

            api( data, function( answer ) {

                const r = answer.result;
                
                if ( r.answer ) {
                    form.querySelector( `.answer` ).innerHTML = r.answer;
                }

                if ( r.collapse ) {
                    form.querySelectorAll( `.input-group` ).forEach( function( el ) {
                        el.remove();
                    } );
                    form.querySelector( `.send` ).remove();
                }

                if ( r.comment ) {
                    form.remove();
                    document.querySelector( `.leave-comment-btn` ).insertAdjacentHTML( "beforebegin", r.comment );
                    // add events
                    const comment = document.querySelector( `.comment[data-id="${r.id}"]` );
                    comment.querySelector( `.reply` ).addEventListener( "click", reply );
                    let cite_div = comment.querySelector( `.cite` );
                    if ( cite_div ) {
                        cite_div.addEventListener( "click", cite );
                    }
                }

            } );

        } );

        form.querySelector(  `input[name="name"]` ).focus();

    }


    // Cite click
    document.querySelectorAll( ".cite" ).forEach( function( cite_div ) {

        cite_div.addEventListener( "click", cite );

    } );

    function cite( e ) {
        let id = parseInt( e );
        if ( isNaN( id ) ) {
            id = this.getAttribute( "data-id" );
        }
        let comment = document.querySelector( `.comment[data-id="${id}"]` );
        if ( ! comment ) return;
        let comments = comment.closest( ".comments" );

        
        // Цель в том, чтобы коммент подъехал к курсору мыши
        // Определяем позицию комментария относительно окна браузера
        let comment_y = comment.getBoundingClientRect().top;
        // Определяем позицию курсора мыши относительно окна браузера
        let mouse_y = e.clientY;
        // На сколько нужно подкрутить
        let need_scroll = mouse_y - comment_y - 16;

        // Определяем на сколько можем подкрутить блок .comments
        let can_scroll_comments = comments.scrollTop;
        
        if ( can_scroll_comments >= need_scroll ) {
            let scroll = can_scroll_comments - need_scroll;
            comments.scrollTo( 0, scroll );
        } else {
            // Прокручиваем .comments до верху
            comments.scrollTo( 0, 0 );
            need_scroll -= can_scroll_comments;
            // Определяем на сколько откручена страница
            let page_scroll_y = window.scrollY;
            // Докручиваем страницу
            window.scrollTo( 0, page_scroll_y - need_scroll );
        }

        comment.classList.add( "highlight" );
        setTimeout( function() { comment.classList.remove( "highlight" ); }, 2000 );

    }

    function uuidv4() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
    }

    // Autoscroll
    document.querySelectorAll( ".comments" ).forEach( function( comments ) {

        comments.scrollTo( 0, comments.scrollHeight );

    } );

} );
