/**
 * Settings page scripts for signwpdf PDF Sign & Fill
 *
 * Handles: email toggle panel, collapsible sections, copy-to-clipboard.
 *
 * @package SignWPDF
 * @since   1.1.0
 */
(function() {
    'use strict';

    function ready(fn) {
        if (document.readyState !== 'loading') { fn(); }
        else { document.addEventListener('DOMContentLoaded', fn); }
    }

    ready(function() {
        // Toggle email settings panel based on master toggle
        var emailToggle = document.getElementById('email_enabled');
        if (emailToggle) {
            emailToggle.addEventListener('change', function() {
                var panel = document.getElementById('email-settings-panel');
                if (panel) {
                    if (this.checked) { panel.classList.add('is-open'); }
                    else { panel.classList.remove('is-open'); }
                }
            });
        }

        // Collapsible triggers
        var triggers = document.querySelectorAll('.psf-collapsible-trigger');
        for (var i = 0; i < triggers.length; i++) {
            triggers[i].addEventListener('click', function(e) {
                e.preventDefault();
                var target = this.getAttribute('data-target');
                this.classList.toggle('is-open');
                var panel = document.getElementById(target);
                if (panel) { panel.classList.toggle('is-open'); }
            });
        }

        // Copy variable to clipboard on click
        var codes = document.querySelectorAll('.psf-variables-list code');
        for (var j = 0; j < codes.length; j++) {
            codes[j].addEventListener('click', function() {
                var text = this.textContent;
                var el = this;
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(text).then(function() {
                        el.style.background = '#c8e6c9';
                        setTimeout(function() { el.style.background = ''; }, 200);
                    });
                }
            });
        }
    });
})();
