(function() {
    'use strict';

    var fields  = ['mode', 'from', 'color', 'size', 'ms', 'sound', 'persist'];
    var output  = document.getElementById('ssetu-gen-output');
    var modeEl  = document.getElementById('ssetu-gen-mode');
    var fromRow = document.getElementById('ssetu-gen-from-row');
    var copyBtn = document.getElementById('ssetu-gen-copy');

    if (!output || !modeEl) return;

    function build() {
        var parts = [];
        var mode  = modeEl.value;
        if (mode === 'countdown') {
            parts.push('mode="countdown"');
            parts.push('from="' + document.getElementById('ssetu-gen-from').value.trim() + '"');
        }
        parts.push('color="' + document.getElementById('ssetu-gen-color').value + '"');
        parts.push('size="' + document.getElementById('ssetu-gen-size').value + '"');
        if (document.getElementById('ssetu-gen-ms').checked)      parts.push('ms="yes"');
        if (document.getElementById('ssetu-gen-sound').checked)   parts.push('sound="yes"');
        if (document.getElementById('ssetu-gen-persist').checked) parts.push('persist="yes"');
        output.value = '[simple_stopwatch ' + parts.join(' ') + ']';
    }

    modeEl.addEventListener('change', function() {
        fromRow.style.display = modeEl.value === 'countdown' ? '' : 'none';
        build();
    });
    fields.forEach(function(id) {
        var el = document.getElementById('ssetu-gen-' + id);
        if (el) el.addEventListener('input', build);
    });

    copyBtn?.addEventListener('click', function() {
        output.select();
        navigator.clipboard.writeText(output.value).then(function() {
            var copied = document.getElementById('ssetu-gen-copied');
            copied.style.display = '';
            setTimeout(function() { copied.style.display = 'none'; }, 2000);
        });
    });

    build();
})();
