(function () {
    "use strict";

    var cfg = window.chitFormatPreview || {};
    var alphabet = cfg.alphabet || "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
    var maxLength = parseInt(cfg.maxLength, 10) || 20;

    var prefixEl = document.getElementById("chit-prefix");
    var groupsEl = document.getElementById("chit-groups");
    var sizeEl = document.getElementById("chit-group-size");
    var previewEl = document.getElementById("chit-format-preview");
    var warningEl = document.getElementById("chit-format-warning");

    if (!prefixEl || !groupsEl || !sizeEl || !previewEl) {
        return;
    }

    function sanitizePrefix(raw) {
        return String(raw)
            .toUpperCase()
            .replace(/[^A-Z0-9-]/g, "")
            .replace(/^-+|-+$/g, "");
    }

    function randomGroup(size) {
        var out = "";
        for (var i = 0; i < size; i++) {
            out += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        }
        return out;
    }

    function update() {
        var prefix = sanitizePrefix(prefixEl.value);
        var groups = parseInt(groupsEl.value, 10) || 2;
        var size = parseInt(sizeEl.value, 10) || 4;

        var parts = [];
        for (var i = 0; i < groups; i++) {
            parts.push(randomGroup(size));
        }
        var body = parts.join("-");
        var sample = prefix === "" ? body : prefix + "-" + body;
        previewEl.textContent = sample;

        if (warningEl) {
            if (sample.length > maxLength && cfg.tooLong) {
                warningEl.textContent = cfg.tooLong
                    .replace("%1$d", sample.length)
                    .replace("%2$d", maxLength);
                warningEl.style.display = "block";
            } else {
                warningEl.style.display = "none";
            }
        }
    }

    ["input", "change"].forEach(function (evt) {
        prefixEl.addEventListener(evt, update);
        groupsEl.addEventListener(evt, update);
        sizeEl.addEventListener(evt, update);
    });
})();
