/*!
 * Yatoon admin — Settings screen.
 *
 * 4.6.1 V2: extracted from admin/views/settings.php. It ran as 341 lines of
 * inline <script>, which meant it could not be linted, minified or cached, and
 * it was invisible to any tool that only looks at .js files.
 *
 * PHP-interpolated values now arrive through wp_localize_script as `yatoonSettingsData`.
 */
jQuery(function($) {
    const nonce = yatoonSettingsData.adminNonce;
    const ajaxUrl = yatoonSettingsData.ajaxUrl;

    // Color picker hex input sync
    $('input[type="color"]').on('input', function() {
        $(this).siblings('.color-hex-input, .code').val($(this).val());
        updatePreview();
    });
    $(document).on('input', '.color-hex-input', function() {
        const hex = $(this).val();
        if (/^#[0-9a-fA-F]{6}$/.test(hex)) {
            $('input[type="color"]#' + $(this).data('target')).val(hex);
            updatePreview();
        }
    });

    function updatePreview() {
        const primary = $('#yatoon_primary_color').val() || '#ec4899';
        const secondary = $('#yatoon_secondary_color').val() || '#f9a8d4';
        const text = $('#yatoon_text_color').val() || '#1a1a1a';
        const radius = $('#sbs_button_radius').val() || 8;
        $('#preview-btn-primary').css({background: primary, 'border-radius': radius + 'px', 'border': 'none'});
        $('#preview-btn-outline').css({'border': '2px solid ' + primary, color: primary, 'border-radius': radius + 'px'});
        $('#preview-tag').css({background: secondary, color: primary});
        $('#preview-text').css('color', text);
    }
    updatePreview();

    $('#yatoon-webhook-test').on('click', function() {
        const $button = $(this);
        const $status = $('#yatoon-webhook-test-status');
        $button.prop('disabled', true).text('Sending...');
        $status.css('color', '#64748b').text('Validating and delivering...');
        $.post(ajaxUrl, { action: 'yatoon_webhook_test', nonce: nonce })
            .done(function(response) {
                const message = response && response.data && response.data.message ? response.data.message : (response.success ? 'Test webhook accepted.' : 'Test webhook failed.');
                $status.css('color', response.success ? '#15803d' : '#b91c1c').text(message);
            })
            .fail(function(xhr) {
                const response = xhr.responseJSON;
                const message = response && response.data && response.data.message ? response.data.message : 'Test request failed.';
                $status.css('color', '#b91c1c').text(message);
            })
            .always(function() {
                $button.prop('disabled', false).text('Send test webhook');
            });
    });

    // Logo uploader
    $('#sbs-upload-logo').on('click', function(e) {
        e.preventDefault();
        if (typeof wp === 'undefined' || !wp.media) return;
        const frame = wp.media({title:'Select Logo', button:{text:'Use this logo'}, multiple:false});
        frame.on('select', function() {
            const att = frame.state().get('selection').first().toJSON();
            $('#sbs_business_logo').val(att.url);
            $('#sbs_business_logo_id').val(att.id);
            const $preview = $('#sbs_business_logo').closest('td').find('img');
            if ($preview.length) {
                $preview.attr('src', att.url);
            } else {
                $('#sbs_business_logo').before('<img src="' + att.url + '" style="max-height:80px;max-width:200px;display:block;margin-bottom:8px;border:1px solid #ddd;border-radius:4px;">');
            }
            $('#sbs-upload-logo').text('Change Logo');
            if ($('#sbs-remove-logo').length === 0) {
                $('#sbs-upload-logo').after(' <button type="button" id="sbs-remove-logo" class="button" style="margin-left:6px;color:#dc2626;">Remove</button>');
            }
        });
        frame.open();
    });
    $('#sbs-remove-logo').on('click', function() {
        $('#sbs_business_logo,#sbs_business_logo_id').val('');
        $(this).closest('td').find('img').remove();
        $(this).remove();
    });

    // Test Connection handled by admin.js (with token validation)
    // Twilio test
    $('#sbs-twilio-test-btn').on('click', function() {
        const phone = $('#sbs-twilio-test-phone').val().trim();
        if (!phone) { alert('Enter a phone number.'); return; }
        const $btn = $(this).prop('disabled', true).text('Sending...');
        const $res = $('#sbs-twilio-test-result');
        $.post(ajaxUrl, {action: 'yatoon_twilio_test', nonce: nonce, test_phone: phone}, function(resp) {
            $btn.prop('disabled', false).text('Send Test SMS');
            if (resp.success) {
                $res.html('<span style="color:#10b981;font-weight:600;">' + resp.data.message + '</span>');
            } else {
                $res.html('<span style="color:#dc2626;">' + (resp.data && resp.data.message ? resp.data.message : 'Error') + '</span>');
            }
        }).fail(function() { $btn.prop('disabled', false).text('Send Test SMS'); $res.html('<span style="color:#dc2626;">Network error</span>'); });
    });

    $('#yatoon-whatsapp-test-btn').on('click', function() {
        const phone = $('#yatoon-whatsapp-test-phone').val().trim();
        if (!phone) { alert('Enter a WhatsApp phone number with country code.'); return; }
        const $btn = $(this).prop('disabled', true).text('Sending...');
        const $res = $('#yatoon-whatsapp-test-result');
        $.post(ajaxUrl, {action: 'yatoon_whatsapp_test', nonce: nonce, test_phone: phone}, function(resp) {
            $btn.prop('disabled', false).text('Send Test WhatsApp');
            if (resp.success) {
                $res.html('<span style="color:#10b981;font-weight:600;"></span>').find('span').text(resp.data.message);
            } else {
                $res.html('<span style="color:#dc2626;"></span>').find('span').text(resp.data && resp.data.message ? resp.data.message : 'Error');
            }
        }).fail(function() { $btn.prop('disabled', false).text('Send Test WhatsApp'); $res.html('<span style="color:#dc2626;">Network error</span>'); });
    });

    // Staff CRUD Modal
    function openModal(id, name, email, bio, active, bookable) {
        $('#sbs-staff-id').val(id || 0);
        $('#sbs-staff-name').val(name || '');
        $('#sbs-staff-email').val(email || '');
        $('#sbs-staff-bio').val(bio || '');
        $('#sbs-staff-active').prop('checked', parseInt(active) !== 0);
        $('#sbs-staff-bookable').prop('checked', parseInt(bookable) !== 0);
        $('#sbs-staff-modal-title').text(id ? 'Edit Staff Member' : 'Add Staff Member');
        $('#sbs-staff-save-status').text('');
        $('#sbs-staff-modal').fadeIn(150);
    }

    $('#sbs-add-staff-btn').on('click', function() { openModal(0); });
    $(document).on('click', '.sbs-edit-staff-btn', function() {
        const d = $(this).data();
        openModal(d.id, d.name, d.email, d.bio, d.active, d.bookable);
    });
    $('#sbs-staff-modal-close,#sbs-staff-modal-cancel').on('click', function() { $('#sbs-staff-modal').fadeOut(150); });
    $('#sbs-staff-modal').on('click', function(e) { if (e.target === this) $(this).fadeOut(150); });

    $('#sbs-staff-modal-save').on('click', function() {
        const $btn = $(this).prop('disabled', true).text('Saving...');
        $.post(ajaxUrl, {
            action:      'yatoon_save_staff',
            nonce:       nonce,
            staff_id:    $('#sbs-staff-id').val(),
            name:        $('#sbs-staff-name').val().trim(),
            email:       $('#sbs-staff-email').val().trim(),
            bio:         $('#sbs-staff-bio').val().trim(),
            is_active:   $('#sbs-staff-active').is(':checked') ? 1 : 0,
            is_bookable: $('#sbs-staff-bookable').is(':checked') ? 1 : 0,
        }, function(resp) {
            $btn.prop('disabled', false).text('Save');
            if (resp.success) {
                $('#sbs-staff-save-status').html('<span style="color:#10b981;font-weight:600;">Saved!</span>');
                setTimeout(function() { location.reload(); }, 800);
            } else {
                $('#sbs-staff-save-status').html('<span style="color:#dc2626;">' + (resp.data && resp.data.message ? resp.data.message : 'Error') + '</span>');
            }
        }).fail(function() { $btn.prop('disabled', false).text('Save'); alert('Network error.'); });
    });

    $(document).on('click', '.sbs-delete-staff-btn', function() {
        if (!confirm('Delete this staff member? This cannot be undone.')) return;
        const id = $(this).data('id');
        $.post(ajaxUrl, {action: 'yatoon_delete_staff', nonce: nonce, staff_id: id}, function(resp) {
            if (resp.success) { $('#sbs-staff-row-' + id).fadeOut(200, function() { $(this).remove(); }); }
            else { alert('Delete failed: ' + (resp.data && resp.data.message ? resp.data.message : 'Error')); }
        });
    });

    // Toggle sync interval row based on auto sync checkbox
    function toggleSyncInterval() {
        const enabled = $('input[name="yatoon_auto_sync_enabled"]').is(':checked');
        $('#sbs-sync-interval-row').css({
            'opacity': enabled ? '1' : '0.4',
            'pointer-events': enabled ? '' : 'none'
        });
    }
    $('input[name="yatoon_auto_sync_enabled"]').on('change', toggleSyncInterval);
    toggleSyncInterval();

    function getSettingsForm($el) {
        var $form = $el.closest('form');
        return $form.length ? $form : $('form[action="options.php"]').first();
    }

    function collectSettingsData($form) {
        var data = { action: 'yatoon_save_general_settings', nonce: nonce };
        $.each($form.serializeArray(), function(i, field) {
            data[field.name] = field.value;
        });
        $form.find('input[type="checkbox"]').each(function() {
            if (!this.checked) {
                data[this.name] = '';
            }
        });
        return data;
    }

    function submitSettingsFallback($form, $msg, detail) {
        $msg.html('<span style="color:#6b7280;">' + (detail || 'Saving with WordPress fallback...') + '</span>');
        if ($form.length && $form[0]) {
            $form[0].submit();
        }
    }

    // AJAX helper 
    function sbsAjaxSave($btn, $msg, extraData, onSuccess) {
        $btn.prop('disabled', true).text('Saving...');
        $msg.html('<span style="color:#6b7280;">Saving...</span>');

        var $form = getSettingsForm($btn);
        var data = collectSettingsData($form);
        $.extend(data, extraData || {});

        $.post(ajaxUrl, data, function(resp) {
            if (resp.success) {
                $msg.html('<span style="color:#10b981;font-weight:600;">Saved!</span>');
                if (onSuccess) onSuccess();
                setTimeout(function() { $msg.html(''); }, 3000);
            } else {
                $msg.html('<span style="color:#ef4444;">' + (resp.data && resp.data.message ? resp.data.message : 'Save failed') + '</span>');
            }
        }).fail(function() {
            submitSettingsFallback($form, $msg, 'Network error. Saving with WordPress fallback...');
        }).always(function() {
            $btn.prop('disabled', false);
        });
    }

    // Save Settings (General tab) - AJAX, same handler as Save Square API area button
    function doSaveGeneralSettings() {
        var $btn = $('#sbs-save-settings-btn, #sbs-save-settings-btn-api').prop('disabled', true).text('Saving...');
        var $msg = $('#sbs-settings-save-msg');
        $msg.html('<span style="color:#6b7280;">Saving...</span>');

        var $form = $('form[action*="admin-post.php"]').first();
        var data = { action: 'yatoon_save_general_settings', nonce: nonce };
        $.each($form.serializeArray(), function(i, field) {
            data[field.name] = field.value;
        });
        // Unchecked checkboxes are not serialized - send empty string explicitly
        $form.find('input[type="checkbox"]').each(function() {
            if (!this.checked) {
                data[this.name] = '';
            }
        });

        $.post(ajaxUrl, data, function(resp) {
            if (resp.success) {
                $msg.html('<span class="yatoon-inline-status"><span aria-hidden="true">&#10003;</span> Saved</span>');
                setTimeout(function() { $msg.html(''); }, 3000);
            } else {
                $msg.html('<span style="color:#ef4444;">' + (resp.data && resp.data.message ? resp.data.message : 'Save failed') + '</span>');
            }
        }).fail(function() {
            $msg.html('<span style="color:#ef4444;">Network error - please try again.</span>');
        }).always(function() {
            $('#sbs-save-settings-btn, #sbs-save-settings-btn-api').prop('disabled', false).text('Save Settings');
        });
    }
    $('#sbs-save-settings-btn, #sbs-save-settings-btn-api').on('click', doSaveGeneralSettings);

    // Save Platform button (AJAX)
    $('#sbs-save-platform-btn').on('click', function() {
        var platform = $('input[name="yatoon_active_platform"]:checked').val();
        var $btn = $(this);
        var $msg = $('#sbs-platform-save-msg');
        if (!platform) {
            $msg.html('<span style="color:#ef4444;">Please select a platform first.</span>');
            return;
        }
        $btn.prop('disabled', true).text('Saving...');
        $msg.html('<span style="color:#6b7280;">Saving...</span>');
        $.post(ajaxUrl, {
            action: 'yatoon_save_general_settings',
            nonce: nonce,
            yatoon_active_platform: platform
        }, function(resp) {
            if (resp.success) {
                $msg.html('<span style="color:#10b981;font-weight:600;">Platform saved!</span>');
                setTimeout(function() { location.reload(); }, 800);
            } else {
                $msg.html('<span style="color:#ef4444;">Save failed</span>');
                $btn.prop('disabled', false).text('Save Platform');
            }
        }).fail(function() {
            $msg.html('<span style="color:#ef4444;">Network error</span>');
            $btn.prop('disabled', false).text('Save Platform');
        });
    });

    // Save Square API settings directly via AJAX (bypass options.php)
    $('#sbs-save-square-api').on('click', function() {
        const $btn = $(this).prop('disabled', true).text('Saving...');
        const token = $('#yatoon_square_access_token').val();
        const locId = $('#yatoon_square_location_id').val();
        const env   = $('select[name="sbs_square_environment"]').val();
        $.post(ajaxurl, {
            action: 'yatoon_save_square_api_settings',
            nonce:  yatoonSettingsData.squareNonce,
            access_token: token,
            location_id:  locId,
            environment:  env,
        }, function(resp) {
            $btn.prop('disabled', false).text('Save Square API');
            if (resp.success) {
                $('#sbs-connection-status').html('<span class="yatoon-inline-status"><span aria-hidden="true">&#10003;</span> Saved</span>');
                setTimeout(() => $('#sbs-connection-status').html(''), 3000);
            } else {
                $('#sbs-connection-status').html('<span style="color:#dc2626;">Save failed: ' + (resp.data?.message || 'Unknown error') + '</span>');
            }
        }).fail(function() {
            $btn.prop('disabled', false).text('Save Square API');
            $('#sbs-connection-status').html('<span style="color:#dc2626;">Network error</span>');
        });
    });


    // Restore default templates
    $('#sbs-restore-defaults-btn').on('click', function() {
        if (!confirm('This will restore all email/SMS templates to their defaults. Your customizations will be lost. Continue?')) return;
        var $btn = $(this).prop('disabled', true).text('Restoring...');
        $.post(ajaxurl, {
            action: 'yatoon_restore_default_templates',
            nonce: yatoonSettingsData.restoreNonce,
        }, function(resp) {
            $btn.prop('disabled', false).text('\u21BB Restore Default Templates');
            if (resp.success) {
                location.reload();
            }
        });
    });

    // Form submit indicator for hours/email/sms/calendar/colors tabs
    // (general tab Save Settings is handled via AJAX above)
    $('form[action*="admin-post.php"]').on('submit', function() {
        var $btns = $(this).find('[type="submit"]');
        setTimeout(function() {
            $btns.prop('disabled', true).each(function() {
                if ($(this).is('button')) {
                    $(this).text('Saving...');
                } else {
                    $(this).val('Saving...');
                }
            });
        }, 0);
    });

});

/* ------------------------------------------------------------------
 * 4.6.1 V4: the remaining eight inline <script> blocks from
 * admin/views/settings.php. They were conditional fragments printed next to
 * the sections they drive, which is why the first extraction pass left them
 * behind; none of them interpolate PHP, so they move across unchanged.
 * ------------------------------------------------------------------ */

(function() {
    var STORAGE_KEY = 'yatoon_settings_general_subtab';
    var ADVANCED_KEY = 'yatoon_settings_show_advanced';
    var advancedPattern = /webhook|signature key|api secret|client secret|access token|location id|business id|sync interval|debug|oauth|cron|environment/i;
    function markAdvancedSettings() {
        document.querySelectorAll('.yatoon-subtab-panel .form-table tr').forEach(function(row) {
            var heading = row.querySelector('th');
            if (heading && advancedPattern.test(heading.textContent || '')) {
                row.classList.add('yatoon-advanced-setting');
            }
        });
    }
    function setAdvanced(show) {
        document.querySelectorAll('.yatoon-advanced-setting').forEach(function(row) { row.hidden = !show; });
        var toggle = document.getElementById('yatoon-toggle-advanced');
        if (toggle) {
            toggle.setAttribute('aria-pressed', show ? 'true' : 'false');
            toggle.textContent = show ? 'Hide advanced' : 'Show advanced';
        }
        try { localStorage.setItem(ADVANCED_KEY, show ? '1' : '0'); } catch (e) {}
    }
    function activate(slug) {
        document.querySelectorAll('[data-yatoon-subtab-panel]').forEach(function(panel) {
            panel.style.display = (panel.getAttribute('data-yatoon-subtab-panel') === slug) ? '' : 'none';
        });
        document.querySelectorAll('.yatoon-subtab-btn').forEach(function(btn) {
            btn.classList.toggle('is-active', btn.getAttribute('data-yatoon-subtab') === slug);
        });
        try { localStorage.setItem(STORAGE_KEY, slug); } catch (e) {}
    }
    document.querySelectorAll('.yatoon-subtab-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            activate(btn.getAttribute('data-yatoon-subtab'));
            btn.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
        });
    });
    // Restore the last section the user was on (e.g. after clicking Save Settings).
    var requested = null;
    try { requested = new URLSearchParams(window.location.search).get('section'); } catch (e) {}
    var saved = null;
    try { saved = localStorage.getItem(STORAGE_KEY); } catch (e) {}
    if (requested && document.querySelector('[data-yatoon-subtab-panel="' + requested + '"]')) {
        activate(requested);
    } else if (saved && document.querySelector('[data-yatoon-subtab-panel="' + saved + '"]')) {
        activate(saved);
    }
    markAdvancedSettings();
    var showAdvanced = false;
    try { showAdvanced = localStorage.getItem(ADVANCED_KEY) === '1'; } catch (e) {}
    setAdvanced(showAdvanced);
    if (window.location.hash) {
        setTimeout(function() {
            var target = document.getElementById(window.location.hash.slice(1));
            if (target) target.scrollIntoView({ block: 'start' });
        }, 0);
    }
    var advancedToggle = document.getElementById('yatoon-toggle-advanced');
    if (advancedToggle) {
        advancedToggle.addEventListener('click', function() {
            setAdvanced(advancedToggle.getAttribute('aria-pressed') !== 'true');
        });
    }
})();

jQuery(function($){
    $('#yatoon-create-staff-portal-page').on('click', function(){
        const $btn = $(this);
        const $msg = $('#yatoon-create-staff-portal-msg');
        $btn.prop('disabled', true);
        $msg.css('color', '#64748b').text('Creating Staff Portal page...');
        $.post(ajaxurl, {
            action: 'yatoon_create_staff_portal_page',
            nonce: $btn.data('nonce')
        }).done(function(resp){
            if (resp && resp.success && resp.data) {
                const viewUrl = resp.data.view_url || '#';
                const editUrl = resp.data.edit_url || '#';
                $msg.css('color', '#166534').html(
                    resp.data.message + ' <a href="' + viewUrl + '" target="_blank" rel="noopener noreferrer">Open</a>' +
                    ' &middot; <a href="' + editUrl + '" target="_blank" rel="noopener noreferrer">Edit</a>'
                );
                $btn.text('Check Staff Portal Page');
            } else {
                $msg.css('color', '#b91c1c').text((resp && resp.data && resp.data.message) ? resp.data.message : 'Could not create Staff Portal page.');
            }
        }).fail(function(){
            $msg.css('color', '#b91c1c').text('Network error while creating Staff Portal page.');
        }).always(function(){
            $btn.prop('disabled', false);
        });
    });
});

jQuery(function($){
    $('#yatoon_phone_mode').on('change',function(){
        $('#yatoon_phone_preset_row').toggle($(this).val()==='intl_preset');
    });
});

jQuery(function($) {
    const platforms = ['square','vagaro','local'];

    function switchPlatform(p) {
        // Update radio
        $('#plat-' + p).prop('checked', true);
        // Update card visuals
        platforms.forEach(function(pl) {
            const active = pl === p;
            $('#plat-card-' + pl).css({
                'border-color': active ? '#ec4899' : '#e5e7eb',
                'background':   active ? '#fff5f9' : '#fafafa'
            });
            // Show/hide active badge
            $('#plat-card-' + pl).find('.plat-active-badge').remove();
            if (active) {
                $('#plat-card-' + pl).append('<div class="plat-active-badge" style="margin-top:8px;background:#d1fae5;color:#059669;border-radius:20px;font-size:11px;font-weight:700;padding:2px 8px;display:inline-block;">ACTIVE</div>');
            }
            // Show/hide config section
            $('#platform-config-' + pl).toggle(active);
        });
    }

    // Card click
    platforms.forEach(function(p) {
        $('#plat-card-' + p).on('click', function() { switchPlatform(p); });
    });

    // On load: ensure correct state
    const current = $('input[name="yatoon_active_platform"]:checked').val() || 'local';
    switchPlatform(current);

    // Vagaro test
    $('#sbs-test-vagaro-connection').on('click', function() {
        const $btn = $(this).prop('disabled', true).text('Testing...');
        const $st  = $('#sbs-vagaro-connection-status').html('<span style="color:#6b7280;">Connecting...</span>');
        $.post(ajaxUrl, {action:'yatoon_test_vagaro_connection', nonce:nonce}, function(r) {
            $st.html(r.success
                ? '<span style="color:#10b981;font-weight:600;">' + (r.data.message||'Connected!') + '</span>'
                : '<span style="color:#ef4444;">' + ((r.data&&r.data.message)||'Connection failed') + '</span>');
        }).fail(function() {
            $st.html('<span style="color:#ef4444;">Request failed</span>');
        }).always(function() {
            $btn.prop('disabled', false).text('Test Vagaro Connection');
        });
    });
});

(function(){
    var $enable = document.getElementById('yatoon_deposit_enabled');
    var $squareEnable = document.getElementById('yatoon_square_payments_enabled');
    var $ruleRows = document.querySelectorAll('.yatoon-payment-rule-row');
    var $stripeRows = document.querySelectorAll('.yatoon-stripe-gateway-row');
    var $paypalRows = document.querySelectorAll('.yatoon-paypal-gateway-row');
    var $squareRows = document.querySelectorAll('.yatoon-square-payment-row');
    var $gateway = document.getElementById('yatoon_deposit_gateway');
    var $type   = document.getElementById('yatoon_deposit_type');
    var $unit   = document.getElementById('yatoon-deposit-unit');
    function toggleRows(){
        // $enable only exists on the Settings > General tab (where this
        // whole "Deposit / Prepay Rules" section lives), but this script
        // is loaded on every settings tab and on the locked "-pro" preview
        // pages -- guard every read the same way $squareEnable/$gateway/
        // $type already are, so this doesn't throw everywhere else.
        var enabledOn = !!( $enable && $enable.checked );
        var squareOn = $squareEnable && $squareEnable.checked;
        $ruleRows.forEach(function(r){ r.style.display = (enabledOn || squareOn) ? '' : 'none'; });
        var gateway = $gateway ? $gateway.value : 'stripe';
        $stripeRows.forEach(function(r){ r.style.display = (enabledOn && !squareOn && gateway === 'stripe') ? '' : 'none'; });
        $paypalRows.forEach(function(r){ r.style.display = (enabledOn && !squareOn && gateway === 'paypal') ? '' : 'none'; });
        $squareRows.forEach(function(r){ r.style.display = squareOn ? '' : 'none'; });
    }
    function updateUnit(){
        if ($unit) $unit.textContent = ($type && $type.value === 'percent') ? '%' : '$';
    }
    toggleRows();
    if ($enable) $enable.addEventListener('change', toggleRows);
    if ($squareEnable) $squareEnable.addEventListener('change', toggleRows);
    if ($gateway) $gateway.addEventListener('change', toggleRows);
    if ($type) $type.addEventListener('change', updateUnit);
})();

(function(){
    var cb = document.getElementById('yatoon_multi_appointment_toggle');
    var slider = document.getElementById('sbs-multi-appt-slider');
    var knob = document.getElementById('sbs-multi-appt-knob');
    var label = document.getElementById('sbs-multi-appt-label');
    if (!cb) return;
    cb.addEventListener('change', function(){
        if (cb.checked) {
            slider.style.background = '#16a34a';
            knob.style.left = '25px';
            label.textContent = 'Multiple appointments enabled';
        } else {
            slider.style.background = '#d1d5db';
            knob.style.left = '3px';
            label.textContent = 'Single appointment only';
        }
    });
    slider.addEventListener('click', function(){ cb.click(); });
})();

(function(){
    var cb    = document.getElementById('yatoon_auto_confirm_toggle');
    var track = document.getElementById('yatoon_auto_confirm_track');
    var thumb = document.getElementById('yatoon_auto_confirm_thumb');
    var lbl   = document.getElementById('yatoon_auto_confirm_label');
    if (!cb) return;
    cb.addEventListener('change', function(){
        if (this.checked) {
            track.style.background = '#ec4899';
            thumb.style.left = '23px';
            lbl.textContent = 'Auto-Confirm: ON';
        } else {
            track.style.background = '#d1d5db';
            thumb.style.left = '3px';
            lbl.textContent = 'Auto-Confirm: OFF';
        }
    });
})();

jQuery(function($) {
    // Toggle day open/closed
    $('.sbs-day-toggle').on('change', function() {
        var day    = $(this).data('day');
        var $times = $('.sbs-day-times-' + day);
        if ($(this).is(':checked')) {
            $times.css({ opacity: '', 'pointer-events': '' });
            $(this).closest('.sbs-hours-row').find('.closed-label').remove();
        } else {
            $times.css({ opacity: '.35', 'pointer-events': 'none' });
        }
    });
});
