/**
 * SiteStaffr Calls List Table Controls
 *
 * Injects mobile select-all checkboxes and date filter toggle
 * for the calls list table.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.2.3
 */

( function() {
    'use strict';

    var d = window.sitestaffrCallsListData || {};

    var injectMobileSelectAll = function() {
        document.querySelectorAll( '.sitestaffr-calls-list-page .bulkactions' ).forEach( function( ba ) {
            if ( ba.querySelector( '.sitestaffr-mobile-select-all' ) ) {
                return;
            }

            var form = ba.closest( 'form' );
            if ( ! form ) {
                return;
            }

            var wrap = document.createElement( 'label' );
            wrap.className = 'sitestaffr-mobile-select-all-wrap';

            var cb = document.createElement( 'input' );
            cb.type = 'checkbox';
            cb.className = 'sitestaffr-mobile-select-all';
            cb.title = d.i18n.selectAll;

            var cbText = document.createElement( 'span' );
            cbText.textContent = d.i18n.selectAll;

            cb.addEventListener( 'change', function() {
                var checked = cb.checked;

                form.querySelectorAll( 'input[name="call_ids[]"]' ).forEach( function( box ) {
                    box.checked = checked;
                } );

                form.querySelectorAll( '.sitestaffr-mobile-select-all' ).forEach( function( peer ) {
                    if ( peer !== cb ) {
                        peer.checked = checked;
                    }
                } );
            } );

            wrap.appendChild( cb );
            wrap.appendChild( cbText );
            ba.insertBefore( wrap, ba.firstChild );
        } );
    };

    var initCallsListControls = function() {
        var sel = document.getElementById( 'sitestaffr-filter-date' );
        var range = document.getElementById( 'sitestaffr-custom-date-range' );
        if ( sel && range && ! sel.dataset.sitestaffrBound ) {
            sel.addEventListener( 'change', function() {
                range.style.display = this.value === 'custom' ? '' : 'none';
            } );
            sel.dataset.sitestaffrBound = '1';
        }

        injectMobileSelectAll();
        window.setTimeout( injectMobileSelectAll, 0 );
        window.setTimeout( injectMobileSelectAll, 200 );
        window.setTimeout( injectMobileSelectAll, 600 );
    };

    if ( document.readyState === 'loading' ) {
        document.addEventListener( 'DOMContentLoaded', initCallsListControls );
    } else {
        initCallsListControls();
    }

    window.addEventListener( 'load', injectMobileSelectAll );
    window.addEventListener( 'resize', injectMobileSelectAll );
} )();
