<?php
$isEdit = !empty($storage);
$cfg = $isEdit ? $storage['config'] : [];
$driver = $isEdit ? $storage['driver'] : ($_GET['driver'] ?? 'ftp');
$ic = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none';
$nginxHost = htmlspecialchars(parse_url(Setting::get('site_url', 'yourdomain.com'), PHP_URL_HOST) ?: 'yourdomain.com');
?>

<div class="mb-4">
    <a href="/admin/settings?tab=storage" class="text-sm text-gray-500 hover:text-gray-700 transition-colors">
        <i class="fa-solid fa-arrow-left" style="font-size:11px"></i> Back to Storage
    </a>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    
    <div class="lg:col-span-2 space-y-5">

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-5 py-3.5 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">Connection</h3>
            </div>
            <div class="p-5 space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Name</label>
                        <input type="text" id="sfName" class="<?= $ic ?>" value="<?= $isEdit ? htmlspecialchars($storage['name']) : '' ?>" placeholder="CDN Europe">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Type</label>
                        <div class="flex gap-2">
                            <?php foreach ($driverLabels as $dk => $dl): ?>
                            <label class="cursor-pointer flex-1">
                                <input type="radio" name="sf_driver" value="<?= $dk ?>" class="sr-only peer" <?= $dk === $driver ? 'checked' : '' ?> onchange="sfToggleDriver()">
                                <div class="text-center px-2 py-2 border-2 rounded-lg text-[10px] font-medium transition-all peer-checked:border-primary-600 peer-checked:bg-primary-50 peer-checked:text-primary-700 border-gray-200 text-gray-500 hover:border-gray-300">
                                    <i class="fa-solid <?= $driverIcons[$dk] ?> block mb-0.5" style="font-size:12px"></i>
                                    <?= explode(' ', $dl)[0] ?>
                                </div>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div id="sfUrlWrap" class="<?= $driver === 'local' ? 'hidden' : '' ?>">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Media URL</label>
                    <input type="url" id="sfMediaUrl" class="<?= $ic ?>" value="<?= $isEdit ? htmlspecialchars($storage['media_url'] ?? '') : '' ?>" placeholder="https://cdn.yourserver.com">
                    <p class="mt-1 text-xs text-gray-400">The public HTTP URL visitors use to load files. Not the FTP/S3 address.</p>
                </div>

                
                <div id="sfFtp" class="<?= $driver !== 'ftp' ? 'hidden' : '' ?> space-y-3">
                    <div class="grid grid-cols-3 gap-3">
                        <div class="col-span-2"><label class="block text-xs font-medium text-gray-600 mb-1">Host</label><input type="text" id="sfFtpHost" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['host'] ?? '') ?>" placeholder="ftp.example.com"></div>
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Port</label><input type="number" id="sfFtpPort" class="<?= $ic ?>" value="<?= (int)($cfg['port'] ?? 21) ?>"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Username</label><input type="text" id="sfFtpUser" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['user'] ?? '') ?>"></div>
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Password</label><input type="password" id="sfFtpPass" class="<?= $ic ?>" placeholder="<?= $isEdit && !empty($cfg['pass']) ? '••••••••  (leave empty to keep)' : '' ?>"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Remote path</label><input type="text" id="sfFtpPath" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['path'] ?? '/') ?>"></div>
                        <div class="flex items-end gap-4 pb-2">
                            <label class="flex items-center gap-1.5 text-xs text-gray-600 cursor-pointer"><input type="checkbox" id="sfFtpSsl" class="rounded border-gray-300 text-primary-600" <?= !empty($cfg['ssl']) ? 'checked' : '' ?>> SSL/TLS</label>
                            <label class="flex items-center gap-1.5 text-xs text-gray-600 cursor-pointer"><input type="checkbox" id="sfFtpPassive" class="rounded border-gray-300 text-primary-600" <?= ($cfg['passive'] ?? true) !== false ? 'checked' : '' ?>> Passive</label>
                        </div>
                    </div>
                </div>

                
                <div id="sfS3" class="<?= $driver !== 's3' ? 'hidden' : '' ?> space-y-3">
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Access Key</label><input type="text" id="sfS3Key" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['key'] ?? '') ?>"></div>
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Secret Key</label><input type="password" id="sfS3Secret" class="<?= $ic ?>" placeholder="<?= $isEdit && !empty($cfg['secret']) ? '••••••••  (leave empty to keep)' : '' ?>"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Bucket</label><input type="text" id="sfS3Bucket" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['bucket'] ?? '') ?>"></div>
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Region</label><input type="text" id="sfS3Region" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['region'] ?? 'us-east-1') ?>"></div>
                    </div>
                    <div><label class="block text-xs font-medium text-gray-600 mb-1">Endpoint <span class="font-normal text-gray-400">(empty = AWS)</span></label><input type="text" id="sfS3Endpoint" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['endpoint'] ?? '') ?>" placeholder="https://nyc3.digitaloceanspaces.com"></div>
                    <div class="max-w-xs"><label class="block text-xs font-medium text-gray-600 mb-1">Prefix</label><input type="text" id="sfS3Prefix" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['prefix'] ?? '') ?>" placeholder="uploads/videos"></div>
                </div>

                
                <div id="sfDav" class="<?= $driver !== 'webdav' ? 'hidden' : '' ?> space-y-3">
                    <div><label class="block text-xs font-medium text-gray-600 mb-1">WebDAV URL</label><input type="url" id="sfDavUrl" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['url'] ?? '') ?>" placeholder="https://cloud.example.com/remote.php/dav/files/user/media"></div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Username</label><input type="text" id="sfDavUser" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['user'] ?? '') ?>"></div>
                        <div><label class="block text-xs font-medium text-gray-600 mb-1">Password</label><input type="password" id="sfDavPass" class="<?= $ic ?>" placeholder="<?= $isEdit && !empty($cfg['pass']) ? '••••••••  (leave empty to keep)' : '' ?>"></div>
                    </div>
                </div>

                
                <div id="sfTestResults" class="hidden"></div>
            </div>
        </div>

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-5 py-3.5 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">Settings</h3>
            </div>
            <div class="p-5 space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select id="sfStatus" class="<?= $ic ?>">
                            <option value="active" <?= ($storage['status'] ?? 'active') === 'active' ? 'selected' : '' ?>>Active — receives new videos</option>
                            <option value="readonly" <?= ($storage['status'] ?? '') === 'readonly' ? 'selected' : '' ?>>Read-only — serves existing only</option>
                            <option value="disabled" <?= ($storage['status'] ?? '') === 'disabled' ? 'selected' : '' ?>>Disabled — offline</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Max disk usage</label>
                        <div class="flex items-center gap-2">
                            <input type="number" id="sfMaxUsage" class="<?= $ic ?>" value="<?= (int)($storage['max_usage_pct'] ?? 90) ?>" min="50" max="99" style="width:80px">
                            <span class="text-sm text-gray-400">%</span>
                        </div>
                        <p class="mt-1 text-xs text-gray-400">Auto-switches to the next storage when reached.</p>
                    </div>
                </div>
                <div>
                    <label class="flex items-center gap-2.5 text-sm font-medium text-gray-700 cursor-pointer">
                        <input type="checkbox" id="sfSecure" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500" <?= !empty($storage['secure_urls']) ? 'checked' : '' ?>>
                        Secure URLs (anti-scraping)
                    </label>
                    <p class="text-xs text-gray-400 mt-1 pl-7">Video URLs are signed with a temporary token, tied to the visitor's IP, and expire automatically.</p>
                </div>
            </div>
        </div>

        
        <div id="sfMonitorSection" class="<?= $driver === 'local' ? 'hidden' : '' ?> bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-5 py-3.5 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">Disk Monitoring</h3>
                <p class="text-xs text-gray-500 mt-0.5">Upload a small PHP script to your remote server to track disk usage and health.</p>
            </div>
            <div class="p-5 space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Monitor script URL</label>
                    <input type="url" id="sfMonitorUrl" class="<?= $ic ?>" value="<?= htmlspecialchars($cfg['monitor_url'] ?? '') ?>" placeholder="https://cdn.example.com/tubepress-storage-monitor.php">
                </div>
                <div class="flex items-center gap-3">
                    <a href="/api/storage-monitor-download<?= $isEdit ? '?storage_id=' . (int)$storage['id'] : '' ?>" class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 border border-primary-200 transition-colors">
                        <i class="fa-solid fa-download" style="font-size:10px"></i> Download monitor script
                    </a>
                    <span class="text-[10px] text-gray-400">Upload it to your remote server, then paste the URL above.</span>
                </div>
                <?php if ($isEdit && !empty($storage['disk_total'])):
                    $diskTotal = (int)$storage['disk_total'];
                    $diskUsed = (int)$storage['disk_used'];
                    $diskPct = $diskTotal > 0 ? round($diskUsed / $diskTotal * 100) : 0;
                    $diskColor = $diskPct >= 90 ? 'bg-red-500' : ($diskPct >= 70 ? 'bg-amber-500' : 'bg-green-500');
                ?>
                <div class="p-3 bg-gray-50 rounded-lg">
                    <div class="flex items-center justify-between mb-1.5">
                        <span class="text-xs font-medium text-gray-700">Disk usage</span>
                        <span class="text-xs text-gray-500"><?= Format::fileSize($diskUsed) ?> / <?= Format::fileSize($diskTotal) ?></span>
                    </div>
                    <div class="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                        <div class="h-full <?= $diskColor ?> rounded-full" style="width:<?= $diskPct ?>%"></div>
                    </div>
                    <div class="flex justify-between mt-1">
                        <span class="text-[10px] text-gray-400"><?= $diskPct ?>% used</span>
                        <span class="text-[10px] text-gray-400">Last check: <?= $storage['disk_checked_at'] ? htmlspecialchars(substr($storage['disk_checked_at'], 0, 16)) : 'Never' ?></span>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    
    <div class="space-y-5">

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-5 space-y-3">
            <button type="button" id="sfSaveBtn" onclick="sfSave()" class="w-full px-4 py-2.5 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">
                <?= $isEdit ? 'Save Changes' : 'Add Storage' ?>
            </button>
            <?php if ($isEdit && !$storage['is_default']): ?>
            <button type="button" onclick="sfSetDefault()" class="w-full px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">Set as Default</button>
            <?php endif; ?>
            <?php if ($isEdit): ?>
            <div class="pt-2 border-t border-gray-100">
                <div class="text-xs text-gray-400 space-y-1">
                    <div><strong><?= number_format($vc) ?></strong> video<?= $vc !== 1 ? 's' : '' ?> on this storage</div>
                    <?php if ($storage['is_default']): ?><div class="text-green-600 font-medium">Default storage</div><?php endif; ?>
                    <?php $hs = $storage['health_status'] ?? 'unknown'; ?>
                    <div class="flex items-center gap-1">
                        Health:
                        <?php if ($hs === 'ok'): ?><span class="text-green-600">OK</span>
                        <?php elseif ($hs === 'warning'): ?><span class="text-amber-600"><?= htmlspecialchars($storage['health_message'] ?? 'Warning') ?></span>
                        <?php elseif ($hs === 'error'): ?><span class="text-red-600"><?= htmlspecialchars($storage['health_message'] ?? 'Error') ?></span>
                        <?php else: ?><span class="text-gray-400">Not checked yet</span><?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($isEdit && !$storage['is_default'] && $vc === 0): ?>
            <button type="button" onclick="sfDelete()" class="w-full px-4 py-2 text-xs text-red-500 hover:text-red-700 transition-colors">Delete this storage</button>
            <?php endif; ?>
        </div>

        
        <div id="sfNginxSection" class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-5 py-3.5 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-sm font-semibold text-gray-900">Nginx Config</h3>
                <button type="button" onclick="navigator.clipboard.writeText(document.getElementById('sfNginxCode').textContent)" class="text-[10px] text-primary-600 hover:text-primary-800 font-medium"><i class="fa-solid fa-copy" style="font-size:9px"></i> Copy</button>
            </div>
            <div class="p-4">
                <pre id="sfNginxCode" class="bg-gray-900 text-green-400 text-[10px] font-mono p-3 rounded-lg overflow-x-auto leading-relaxed select-all"></pre>
                <p id="sfNginxNote" class="mt-2 text-[10px] text-gray-400"></p>
            </div>
        </div>

    </div>
</div>

<script>
var _csrf = '<?= Router::csrfToken() ?>';
var _storageId = <?= $isEdit ? (int)$storage['id'] : 0 ?>;
var _appRoot = <?= json_encode(APP_ROOT) ?>;
var _monitorKey = <?= json_encode($cfg['monitor_key'] ?? '') ?>;

function _post(u,b){return fetch(u,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify(Object.assign({csrf_token:_csrf},b)),credentials:'same-origin'}).then(r=>r.json())}

function sfToggleDriver() {
    var d = document.querySelector('input[name=sf_driver]:checked').value;
    document.getElementById('sfUrlWrap').classList.toggle('hidden', d === 'local');
    document.getElementById('sfFtp').classList.toggle('hidden', d !== 'ftp');
    document.getElementById('sfS3').classList.toggle('hidden', d !== 's3');
    document.getElementById('sfDav').classList.toggle('hidden', d !== 'webdav');
    document.getElementById('sfMonitorSection').classList.toggle('hidden', d === 'local');
    sfUpdateNginx();
}

function sfBuildBody() {
    var d = document.querySelector('input[name=sf_driver]:checked').value;
    var body = {id: _storageId, name: document.getElementById('sfName').value, driver: d, media_url: document.getElementById('sfMediaUrl').value};
    if (d === 'ftp') { body.ftp_host = document.getElementById('sfFtpHost').value; body.ftp_port = parseInt(document.getElementById('sfFtpPort').value); body.ftp_user = document.getElementById('sfFtpUser').value; body.ftp_pass = document.getElementById('sfFtpPass').value; body.ftp_ssl = document.getElementById('sfFtpSsl').checked; body.ftp_passive = document.getElementById('sfFtpPassive').checked; body.ftp_path = document.getElementById('sfFtpPath').value; }
    if (d === 's3') { body.s3_key = document.getElementById('sfS3Key').value; body.s3_secret = document.getElementById('sfS3Secret').value; body.s3_bucket = document.getElementById('sfS3Bucket').value; body.s3_region = document.getElementById('sfS3Region').value; body.s3_endpoint = document.getElementById('sfS3Endpoint').value; body.s3_prefix = document.getElementById('sfS3Prefix').value; }
    if (d === 'webdav') { body.dav_url = document.getElementById('sfDavUrl').value; body.dav_user = document.getElementById('sfDavUser').value; body.dav_pass = document.getElementById('sfDavPass').value; }
    body.secure = document.getElementById('sfSecure').checked;
    body.status = document.getElementById('sfStatus').value;
    body.max_usage_pct = parseInt(document.getElementById('sfMaxUsage').value) || 90;
    body.monitor_url = document.getElementById('sfMonitorUrl').value;
    if (_storageId > 0) body.storage_id = _storageId;
    return body;
}

function sfSave() {
    var d = document.querySelector('input[name=sf_driver]:checked').value;
    var btn = document.getElementById('sfSaveBtn');
    var label = <?= json_encode($isEdit ? 'Save Changes' : 'Add Storage') ?>;
    btn.disabled = true;

    if (d === 'local') {
        btn.textContent = 'Saving...';
        sfDoSave();
        return;
    }

    
    btn.textContent = 'Testing connection...';
    _post('/admin/settings/storage/test', sfBuildBody()).then(function(r) {
        sfShowTestResults(r);
        if (!r.ok) { btn.disabled = false; btn.textContent = label; return; }

        
        var monitorUrl = document.getElementById('sfMonitorUrl').value.trim();
        if (monitorUrl !== '') {
            btn.textContent = 'Checking monitor script...';
            sfTestMonitor(monitorUrl, function(ok, msg) {
                if (!ok) {
                    sfAppendTestResult('Monitor script', false, msg);
                    btn.disabled = false; btn.textContent = label;
                    return;
                }
                sfAppendTestResult('Monitor script', true, 'Connected');
                btn.textContent = 'Saving...';
                sfDoSave();
            });
        } else {
            btn.textContent = 'Saving...';
            sfDoSave();
        }
    });
}

function sfTestMonitor(url, callback) {
    
    fetch(url + (url.indexOf('?') > -1 ? '&' : '?') + 'action=ping&key=test', {mode: 'no-cors'})
    .then(function() {
        
        
        _post('/admin/settings/storage/test-monitor', {url: url, storage_id: _storageId}).then(function(r) {
            callback(r.ok, r.error || '');
        });
    })
    .catch(function() { callback(false, 'Cannot reach the monitor script URL'); });
}

function sfAppendTestResult(name, ok, info) {
    var el = document.getElementById('sfTestResults');
    if (el.classList.contains('hidden')) return;
    var container = el.querySelector('.space-y-1');
    if (!container) return;
    var icon = ok ? '<i class="fa-solid fa-check text-green-500" style="font-size:8px;width:12px"></i>' : '<i class="fa-solid fa-xmark text-red-500" style="font-size:8px;width:12px"></i>';
    var cls = ok ? 'text-gray-600' : 'text-red-700 font-medium';
    var infoStr = info ? ' <span class="text-gray-400 font-normal">— ' + info + '</span>' : '';
    container.innerHTML += '<div class="flex items-center gap-1.5 text-[11px] ' + cls + '">' + icon + name + infoStr + '</div>';
}

function sfDoSave() {
    _post('/admin/settings/storage/save', sfBuildBody()).then(function(r) {
        if (r.success) {
            window.location.href = '/admin/settings?tab=storage';
        } else {
            alert(r.error);
            var btn = document.getElementById('sfSaveBtn');
            btn.disabled = false;
            btn.textContent = <?= json_encode($isEdit ? 'Save Changes' : 'Add Storage') ?>;
        }
    });
}

function sfShowTestResults(r) {
    var el = document.getElementById('sfTestResults');
    if (!r.checks || !r.checks.length) { el.classList.add('hidden'); return; }
    var allOk = r.ok;
    var borderCls = allOk ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50';
    var titleIcon = allOk ? '<i class="fa-solid fa-circle-check text-green-500" style="font-size:12px"></i>' : '<i class="fa-solid fa-circle-xmark text-red-500" style="font-size:12px"></i>';
    var titleText = allOk ? 'All checks passed' : 'Connection test failed';
    var titleCls = allOk ? 'text-green-800' : 'text-red-800';
    var html = '<div class="rounded-lg border ' + borderCls + ' p-3"><div class="flex items-center gap-2 mb-2">' + titleIcon + '<span class="text-xs font-semibold ' + titleCls + '">' + titleText + '</span></div><div class="space-y-1 pl-5">';
    r.checks.forEach(function(c) {
        var icon = c.ok ? '<i class="fa-solid fa-check text-green-500" style="font-size:8px;width:12px"></i>' : '<i class="fa-solid fa-xmark text-red-500" style="font-size:8px;width:12px"></i>';
        var cls = c.ok ? 'text-gray-600' : 'text-red-700 font-medium';
        var info = c.info ? ' <span class="text-gray-400 font-normal">— ' + c.info + '</span>' : '';
        html += '<div class="flex items-center gap-1.5 text-[11px] ' + cls + '">' + icon + c.name + info + '</div>';
    });
    html += '</div></div>';
    el.innerHTML = html;
    el.classList.remove('hidden');
}

function sfSetDefault() {
    _post('/admin/settings/storage/default', {id: _storageId}).then(function(r) { if (r.success) location.reload(); else alert(r.error); });
}

function sfDelete() {
    if (!confirm('Delete this storage? This cannot be undone.')) return;
    _post('/admin/settings/storage/delete', {id: _storageId}).then(function(r) { if (r.success) window.location.href = '/admin/settings?tab=storage'; else alert(r.error); });
}

function sfUpdateNginx() {
    var d = document.querySelector('input[name=sf_driver]:checked').value;
    var code = '', note = '';
    if (d === 'local') {
        code = '# Rate-limit video streaming\nlocation ~* ^/uploads/videos/.*\\.(mp4|webm|ogg)$ {\n    root ' + _appRoot + '/public;\n    limit_rate_after 2m;\n    limit_rate 1200k;\n    expires 7d;\n    access_log off;\n}';
        if (document.getElementById('sfSecure').checked) {
            code += '\n\n# Secure URLs (internal redirect)\nlocation /media/ {\n    internal;\n    alias ' + _appRoot + '/public/uploads/;\n    limit_rate_after 2m;\n    limit_rate 1200k;\n}';
        }
        note = 'Add to /etc/nginx/sites-available/<?= $nginxHost ?>';
    } else if (d === 'ftp' || d === 'webdav') {
        var mk = _monitorKey;
        code = '# Video delivery (add inside server {} block on REMOTE server)\n\n'
             + '# Rate limit bypass for transcode workers\n'
             + 'set $vid_rate 1200k;\n'
             + 'set $vid_burst 2m;\n'
             + 'if ($arg_wk = "' + (mk || 'YOUR_MONITOR_KEY') + '") {\n'
             + '    set $vid_rate 0;\n'
             + '    set $vid_burst 0;\n'
             + '}\n\n'
             + 'location ~* \\.(mp4|webm|ogg)$ {\n'
             + '    limit_rate $vid_rate;\n'
             + '    limit_rate_after $vid_burst;\n'
             + '    expires 7d;\n'
             + '    access_log off;\n'
             + '}';
        note = 'Visitors are limited to 1200 KB/s after 2MB. Transcode workers download at full speed using the key.';
    } else if (d === 's3') {
        code = '# S3/CDN storage\n# No Nginx config needed.\n# Rate limiting is configured on your CDN.';
        note = 'Files are served directly from S3/CloudFront.';
    }
    document.getElementById('sfNginxCode').textContent = code;
    document.getElementById('sfNginxNote').textContent = note;
}

sfUpdateNginx();
document.getElementById('sfSecure').addEventListener('change', sfUpdateNginx);
</script>
