<style>
.vm-tabs { display:flex; gap:4px; background:#1a1a1a; border-radius:6px; padding:3px; margin-bottom:14px; border:1px solid #2a2a2a; }
.vm-tab { flex:1; padding:6px 0; border:none; border-radius:4px; font-size:.8rem; font-weight:600; letter-spacing:.04em; cursor:pointer; transition:all .15s; background:transparent; color:#666; }
.vm-tab.active { background:#dc3545; color:#fff; }
.vm-tab:hover:not(.active) { color:#ccc; background:#222; }

.bulk-range-row { display:grid; grid-template-columns:1fr 24px 1fr; gap:6px; align-items:end; margin-bottom:10px; }
.bulk-range-sep { text-align:center; color:#555; padding-bottom:8px; font-size:.85rem; }

#bulk-preview {
    background:#0d0d0d; border:1px solid #2a2a2a; border-radius:5px;
    padding:8px 10px; min-height:40px; max-height:80px; overflow-y:auto;
    font-size:.75rem; color:#666; line-height:1.8;
    scrollbar-width:thin; scrollbar-color:#333 transparent;
}
#bulk-preview .vm-chip {
    display:inline-block; background:#1c1c1c; border:1px solid #2e2e2e;
    border-radius:3px; padding:0 6px; margin:2px 2px 2px 0;
    font-family:monospace; color:#e07b7b; font-size:.72rem;
}
.bulk-count { font-size:.72rem; background:rgba(220,53,69,.12); border:1px solid rgba(220,53,69,.3); color:#dc3545; border-radius:3px; padding:1px 7px; margin-left:6px; font-weight:600; vertical-align:middle; }

#bulk-progress-wrap { display:none; margin-top:10px; }
.bulk-progress { background:#1a1a1a; height:5px; border-radius:3px; margin-bottom:4px; }
.bulk-progress-bar { height:5px; border-radius:3px; background:linear-gradient(90deg,#dc3545,#ff6b6b); transition:width .25s; }
#bulk-status-txt { font-size:.72rem; color:#666; }
</style>

<div id="modal-vm" class="modal">
  <div class="modal-content bg-dark text-white p-4 border-danger" style="max-width:450px">
    <div class="modal-header border-secondary border-0 p-0 mb-3">
        <h4 class="m-0">New VM</h4>
        <button class="btn-close btn-close-white" onclick="app.closeModal()"></button>
    </div>

    <div class="vm-tabs">
        <button class="vm-tab active" id="vm-tab-single" onclick="vmSwitchTab('single')">Single</button>
        <button class="vm-tab" id="vm-tab-bulk" onclick="vmSwitchTab('bulk')">Bulk Range</button>
    </div>

    <label class="small text-muted">Group</label>
    <select id="vmGroupSelect" onchange="app.filterRdpList(this.value)" class="form-control bg-black text-white border-secondary mb-2">
        <option value="">-- Select Group --</option>
        <?php foreach($tree as $g): ?>
            <option value="<?= $g['id'] ?>"><?= $g['name'] ?></option>
        <?php endforeach; ?>
    </select>

    <label class="small text-muted">RDP</label>
    <select id="vmRdpSelect" class="form-control bg-black text-white border-secondary mb-2">
        <option value="">-- Select Group First --</option>
    </select>

    <div id="vm-pane-single">
        <label class="small text-muted">VM Name</label>
        <input id="vmInput" placeholder="VM Name" autocomplete="off"
               class="form-control bg-black text-white border-secondary mb-3">
        <button onclick="app.addVM()" class="btn btn-danger w-100">Add VM</button>
    </div>

    <div id="vm-pane-bulk" style="display:none">

        <label class="small text-muted">Prefix</label>
        <input id="bulk-prefix" placeholder="e.g. vm-prod-" autocomplete="off"
               oninput="vmBulkPreview()"
               class="form-control bg-black text-white border-secondary mb-2">

        <div class="bulk-range-row">
            <div>
                <label class="small text-muted">From</label>
                <input id="bulk-from" type="number" value="1" min="1"
                       oninput="vmBulkPreview()"
                       class="form-control bg-black text-white border-secondary">
            </div>
            <div class="bulk-range-sep">→</div>
            <div>
                <label class="small text-muted">To</label>
                <input id="bulk-to" type="number" value="10" min="1"
                       oninput="vmBulkPreview()"
                       class="form-control bg-black text-white border-secondary">
            </div>
        </div>

        <div class="d-flex gap-2 mb-2">
            <div style="flex:1">
                <label class="small text-muted">Padding</label>
                <select id="bulk-pad" onchange="vmBulkPreview()"
                        class="form-control bg-black text-white border-secondary">
                    <option value="0">None  (1, 2…)</option>
                    <option value="2">2 Digit  (01, 02…)</option>
                    <option value="3" selected>3 Digit  (001, 002…)</option>
                    <option value="4">4 Digit  (0001…)</option>
                </select>
            </div>
            <div style="flex:1">
                <label class="small text-muted">Suffix <span style="color:#444">(opt)</span></label>
                <input id="bulk-suffix" placeholder="-win10" autocomplete="off"
                       oninput="vmBulkPreview()"
                       class="form-control bg-black text-white border-secondary">
            </div>
        </div>

        <div class="mb-1">
            <span class="small text-muted">Preview</span>
            <span id="bulk-count-badge" class="bulk-count">0 VMs</span>
        </div>
        <div id="bulk-preview">Names will appear here…</div>

        <div id="bulk-progress-wrap">
            <div class="bulk-progress mt-2">
                <div id="bulk-pbar" class="bulk-progress-bar" style="width:0%"></div>
            </div>
            <div id="bulk-status-txt">Preparing…</div>
        </div>

        <button id="btn-bulk-add" onclick="app.addBulkVMs()" class="btn btn-danger w-100 mt-3">
            Create All VMs
        </button>
    </div>

  </div>
</div>

<script>
function vmSwitchTab(t) {
    document.getElementById('vm-pane-single').style.display = t === 'single' ? '' : 'none';
    document.getElementById('vm-pane-bulk').style.display   = t === 'bulk'   ? '' : 'none';
    document.getElementById('vm-tab-single').classList.toggle('active', t === 'single');
    document.getElementById('vm-tab-bulk').classList.toggle('active',   t === 'bulk');
}

function vmBulkNames() {
    const prefix = document.getElementById('bulk-prefix').value;
    const suffix = document.getElementById('bulk-suffix').value;
    const from   = parseInt(document.getElementById('bulk-from').value) || 1;
    const to     = parseInt(document.getElementById('bulk-to').value)   || 1;
    const pad    = parseInt(document.getElementById('bulk-pad').value)  || 0;
    if (from > to || (to - from) > 999) return [];
    const out = [];
    for (let i = from; i <= to; i++) {
        const n = pad ? String(i).padStart(pad, '0') : String(i);
        out.push(prefix + n + suffix);
    }
    return out;
}

function vmBulkPreview() {
    const names = vmBulkNames();
    const box   = document.getElementById('bulk-preview');
    document.getElementById('bulk-count-badge').textContent = names.length + ' VM' + (names.length !== 1 ? 's' : '');
    if (!names.length) {
        box.innerHTML = '<span style="color:#444">Range invalid or too large (max 1000)</span>';
        return;
    }
    const show = names.slice(0, 25);
    box.innerHTML = show.map(n => `<span class="vm-chip">${n}</span>`).join('') +
        (names.length > 25 ? `<span style="color:#555;font-size:.7rem"> +${names.length - 25} more</span>` : '');
}

document.addEventListener('DOMContentLoaded', function () {
    app.addBulkVMs = async function () {
        const rdpId = document.getElementById('vmRdpSelect').value;
        const grpId = document.getElementById('vmGroupSelect').value;

        if (!grpId || !rdpId) {
            alert('Please select a Group and RDP first.');
            return;
        }

        const names = vmBulkNames();
        if (!names.length) {
            alert('No VMs to create. Check your range.');
            return;
        }

        const btn  = document.getElementById('btn-bulk-add');
        const wrap = document.getElementById('bulk-progress-wrap');
        const bar  = document.getElementById('bulk-pbar');
        const txt  = document.getElementById('bulk-status-txt');

        btn.disabled = true;
        wrap.style.display = '';

        let failed = 0;

        for (let i = 0; i < names.length; i++) {
            bar.style.width = Math.round(((i + 1) / names.length) * 100) + '%';
            txt.textContent = `Creating ${names[i]}… (${i + 1}/${names.length})`;

            const res = await app.api('add_vm', {
                rdp_id:  parseInt(rdpId),
                unit_id: names[i]
            });

            if (!res || !res.success) failed++;
        }

        if (failed === 0) {
            txt.innerHTML = `<span style="color:#4caf50">✓ All ${names.length} VMs created.</span>`;
        } else {
            txt.innerHTML = `<span style="color:#ffc107">⚠ ${names.length - failed} created, ${failed} failed.</span>`;
        }

        setTimeout(() => location.reload(), 1500);
    };

    vmBulkPreview();
});
</script>