<!-- Token Management Widget -->
<div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 p-6 mt-6">
    <div class="flex items-center justify-between gap-2 mb-4">
        <h3 class="text-base font-semibold text-gray-800 dark:text-gray-100">API Token Management</h3>
        <button onclick="tw_openModal()" class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition">
            + Create Token
        </button>
    </div>

    <!-- Stats bar -->
    <div id="tw-stats-bar" class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4"></div>

    <!-- Tokens table -->
    <div class="overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg">
        <table class="w-full text-sm text-left">
            <thead class="bg-gray-50 dark:bg-gray-700/50 text-gray-500 dark:text-gray-400">
                <tr>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Name</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Token</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Quota</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Models</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Status</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Expires</th>
                    <th class="px-4 py-3 font-semibold uppercase text-[11px] tracking-wider">Last Used</th>
                    <th class="px-4 py-3 w-24 font-semibold uppercase text-[11px] tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody id="tw-tbody" class="divide-y divide-gray-100 dark:divide-gray-700"></tbody>
        </table>
        <div id="tw-empty-state" class="hidden p-8 text-center text-gray-400 text-sm">No tokens yet. Click "+ Create Token" to get started.</div>
    </div>
</div>

<!-- Token Modal -->
<div id="tw-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div class="p-6">
            <h3 id="tw-modal-title" class="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">Create Token</h3>
            <form id="tw-form" onsubmit="tw_save(event)">
                <input type="hidden" id="tw-token-id">
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
                        <input type="text" id="tw-name" required class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Quota Limit</label>
                        <input type="number" id="tw-quota" min="0" placeholder="0 = unlimited" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Model Access</label>
                        <select id="tw-model-access" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100">
                            <option value="all">All models</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Allowed Models</label>
                        <div id="tw-model-checks" class="space-y-1 max-h-32 overflow-y-auto border border-gray-200 dark:border-gray-600 rounded-md p-2"></div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Expires</label>
                        <input type="datetime-local" id="tw-expires" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100">
                    </div>
                    <div id="tw-status-field">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Status</label>
                        <select id="tw-status" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100">
                            <option value="active">Active</option>
                            <option value="suspended">Suspended</option>
                        </select>
                    </div>
                </div>
                <div class="mt-6 flex justify-end gap-3">
                    <button type="button" onclick="tw_closeModal()" class="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">Cancel</button>
                    <button type="submit" id="tw-save-btn" class="px-4 py-2 text-sm text-white bg-indigo-600 rounded-md hover:bg-indigo-700">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="tw-delete-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 w-full max-w-sm p-6">
        <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-2">Delete Token</h3>
        <p class="text-sm text-gray-500 mb-6">Are you sure you want to delete this token? This action cannot be undone.</p>
        <div class="flex justify-end gap-3">
            <button onclick="tw_closeDeleteModal()" class="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">Cancel</button>
            <button onclick="tw_confirmDelete()" class="px-4 py-2 text-sm text-white bg-red-600 rounded-md hover:bg-red-700">Delete</button>
        </div>
    </div>
</div>

<!-- Token Created Modal -->
<div id="tw-created-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 w-full max-w-lg p-6">
        <h3 class="text-lg font-semibold text-green-700 dark:text-green-400 mb-2">Token Created</h3>
        <p class="text-sm text-gray-500 mb-4">Copy this token now. It will not be shown again.</p>
        <div class="flex gap-2 mb-4">
            <input type="text" id="tw-created-token-value" readonly class="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-50 dark:bg-gray-600 text-gray-800 dark:text-gray-100 font-mono text-sm">
            <button onclick="tw_copyCreatedToken()" class="px-3 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700 transition">Copy</button>
        </div>
        <div class="flex justify-end">
            <button onclick="tw_doneCreatedToken()" class="px-4 py-2 text-sm text-white bg-indigo-600 rounded-md hover:bg-indigo-700">Done</button>
        </div>
    </div>
</div>

<!-- Token Detail Modal -->
<div id="tw-detail-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 w-full max-w-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">Token Details</h3>
        <div class="space-y-3">
            <div>
                <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Name</label>
                <p id="tw-detail-name" class="text-sm text-gray-800 dark:text-gray-100 font-medium"></p>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Token</label>
                <div class="flex gap-2 items-center">
                    <span id="tw-detail-token" class="text-sm font-mono text-gray-600 dark:text-gray-300"></span>
                    <button id="tw-detail-reveal-btn" onclick="tw_revealDetailToken()" class="px-2 py-1 text-xs text-indigo-600 border border-indigo-200 rounded hover:bg-indigo-50">Reveal</button>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Quota</label>
                    <p id="tw-detail-quota" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Status</label>
                    <p id="tw-detail-status" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Created</label>
                    <p id="tw-detail-created" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Expires</label>
                    <p id="tw-detail-expires" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
                <div class="col-span-2">
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Last Used</label>
                    <p id="tw-detail-last-used" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
                <div class="col-span-2">
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider">Allowed Models</label>
                    <p id="tw-detail-models" class="text-sm text-gray-800 dark:text-gray-100"></p>
                </div>
            </div>
        </div>
        <div class="mt-6 flex justify-end gap-2">
            <button onclick="tw_closeDetailModal()" class="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">Close</button>
        </div>
    </div>
</div>

<script>
// ---- Token Widget State ----
var twTokens = [];
var twModelMap = {};
var twDeleteId = null;

// ---- Init ----
(function() {
    tw_loadModelMap().then(function() { tw_loadTokens(); });
})();

// ---- API Helpers ----
function tw_api(path) {
    return '/api/' + '{{ plugin_id }}' + '/admin' + path;
}

function tw_loadModelMap() {
    return $.get('/api/model-router/models').then(function(data) {
        twModelMap = {};
        (data.models || []).forEach(function(m) {
            twModelMap[m.id || m.model_name] = m.name || m.id || m.model_name;
        });
    }).fail(function() { twModelMap = {}; });
}

function tw_loadTokens() {
    return $.get(tw_api('/tokens')).done(function(data) {
        twTokens = data.tokens || [];
        tw_renderStats();
        tw_renderTable();
    });
}

// ---- Render ----
function tw_renderStats() {
    var active = twTokens.filter(function(t) { return t.status === 'active'; }).length;
    var suspended = twTokens.filter(function(t) { return t.status === 'suspended'; }).length;
    var total = twTokens.length;
    var unlimited = twTokens.filter(function(t) { return t.quota_limit === null; }).length;
    $('#tw-stats-bar').html(
        '<div class="bg-indigo-50 dark:bg-indigo-900/30 rounded-lg p-3 text-center"><div class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">' + total + '</div><div class="text-xs text-gray-500">Total</div></div>' +
        '<div class="bg-green-50 dark:bg-green-900/30 rounded-lg p-3 text-center"><div class="text-2xl font-bold text-green-600 dark:text-green-400">' + active + '</div><div class="text-xs text-gray-500">Active</div></div>' +
        '<div class="bg-yellow-50 dark:bg-yellow-900/30 rounded-lg p-3 text-center"><div class="text-2xl font-bold text-yellow-600 dark:text-yellow-400">' + suspended + '</div><div class="text-xs text-gray-500">Suspended</div></div>' +
        '<div class="bg-purple-50 dark:bg-purple-900/30 rounded-lg p-3 text-center"><div class="text-2xl font-bold text-purple-600 dark:text-purple-400">' + unlimited + '</div><div class="text-xs text-gray-500">Unlimited</div></div>'
    );
}

function tw_renderTable() {
    var $tbody = $('#tw-tbody');
    var $empty = $('#tw-empty-state');
    $tbody.empty();
    if (twTokens.length === 0) {
        $empty.removeClass('hidden');
        return;
    }
    $empty.addClass('hidden');
    twTokens.forEach(function(t) {
        var statusClass = t.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700';
        var models = t.allowed_models && t.allowed_models.length > 0 ? t.allowed_models.join(', ') : 'All';
        var expires = t.expires_at ? new Date(t.expires_at).toLocaleDateString() : 'Never';
        var lastUsed = t.last_used_at ? tw_timeAgo(t.last_used_at) : 'Never';
        var quota = t.quota_limit !== null ? (t.quota_used || 0) + '/' + t.quota_limit : 'Unlimited';

        $tbody.append(
            '<tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer" onclick="tw_openDetailModal(' + t.id + ')">' +
            '<td class="px-4 py-3 font-medium text-gray-800 dark:text-gray-100">' + tw_esc(t.name) + '</td>' +
            '<td class="px-4 py-3 font-mono text-xs text-gray-500" title="' + tw_esc(t.token_preview) + '">...' + (t.token_preview || '****').slice(-4) + '</td>' +
            '<td class="px-4 py-3 text-gray-600 dark:text-gray-300">' + quota + '</td>' +
            '<td class="px-4 py-3 text-gray-600 dark:text-gray-300 text-xs">' + tw_esc(models) + '</td>' +
            '<td class="px-4 py-3"><span class="px-2 py-1 rounded-full text-xs font-medium ' + statusClass + '">' + t.status + '</span></td>' +
            '<td class="px-4 py-3 text-gray-600 dark:text-gray-300 text-xs">' + expires + '</td>' +
            '<td class="px-4 py-3 text-gray-600 dark:text-gray-300 text-xs">' + lastUsed + '</td>' +
            '<td class="px-4 py-3" onclick="event.stopPropagation()">' +
            '<button onclick="tw_editToken(' + t.id + ')" class="p-1 rounded border border-indigo-400 dark:border-indigo-500 text-indigo-500 dark:text-indigo-400 bg-transparent cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-950/50 transition-colors" title="Edit"><svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg></button>' +
            '<button onclick="tw_deleteToken(' + t.id + ')" class="p-1 rounded border border-red-400 dark:border-red-500 text-red-400 dark:text-red-400 bg-transparent cursor-pointer hover:bg-red-50 dark:hover:bg-red-950/50 transition-colors" title="Delete"><svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg></button>' +
            '</td></tr>'
        );
    });
}

// ---- Modal ----
function tw_openModal(id) {
    $('#tw-modal').removeClass('hidden');
    $('#tw-save-btn').prop('disabled', false).text('Save');
    if (id) {
        var t = twTokens.find(function(tok) { return tok.id === id; });
        if (!t) return;
        $('#tw-modal-title').text('Edit Token');
        $('#tw-token-id').val(t.id);
        $('#tw-name').val(t.name);
        $('#tw-quota').val(t.quota_limit || '');
        $('#tw-status').val(t.status);
        $('#tw-status-field').removeClass('hidden');
        $('#tw-expires').val(t.expires_at ? t.expires_at.slice(0, 16) : '');
    } else {
        $('#tw-modal-title').text('Create Token');
        $('#tw-token-id').val('');
        $('#tw-name').val('');
        $('#tw-quota').val('');
        $('#tw-expires').val('');
        $('#tw-status-field').addClass('hidden');
    }
    tw_renderModelChecks(id ? t.allowed_models || [] : []);
}

function tw_closeModal() {
    $('#tw-modal').addClass('hidden');
}

function tw_editToken(id) {
    tw_openModal(id);
}

// ---- Model Checks ----
function tw_renderModelChecks(selected) {
    var $container = $('#tw-model-checks');
    $container.empty();
    var models = Object.keys(twModelMap).sort();
    if (models.length === 0) {
        $container.append('<span class="text-xs text-gray-400">No models configured.</span>');
        return;
    }
    models.forEach(function(m) {
        var checked = selected.includes(m) ? 'checked' : '';
        $container.append(
            '<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">' +
            '<input type="checkbox" class="tw-model-check rounded" value="' + m + '" ' + checked + '>' +
            '<span>' + tw_esc(m) + '</span></label>'
        );
    });
}

function tw_getCheckedModels() {
    return $('.tw-model-check:checked').map(function() { return this.value; }).get();
}

// ---- Save ----
function tw_save(e) {
    e.preventDefault();
    var id = $('#tw-token-id').val();
    var data = {
        name: $('#tw-name').val(),
        quota_limit: $('#tw-quota').val() ? parseInt($('#tw-quota').val()) : null,
        allowed_models: tw_getCheckedModels(),
        expires_at: $('#tw-expires').val() || null
    };
    var btn = $('#tw-save-btn');
    btn.prop('disabled', true).text('Saving...');
    var method = id ? 'PUT' : 'POST';
    var url = id ? tw_api('/tokens/' + id) : tw_api('/tokens');
    if (id) {
        data.status = $('#tw-status').val();
    }
    $.ajax({ url: url, method: method, contentType: 'application/json', data: JSON.stringify(data) })
    .done(function(resp) {
        tw_closeModal();
        if (!id && resp && resp.plaintext) {
            $('#tw-created-token-value').val(resp.plaintext);
            $('#tw-created-modal').removeClass('hidden');
        } else {
            tw_loadTokens();
        }
    })
    .fail(function(xhr) { alert(xhr.responseJSON ? xhr.responseJSON.error : 'Failed to save token'); })
    .always(function() { btn.prop('disabled', false).text('Save'); });
}

// ---- Delete ----
function tw_deleteToken(id) {
    twDeleteId = id;
    $('#tw-delete-modal').removeClass('hidden');
}

function tw_closeDeleteModal() {
    $('#tw-delete-modal').addClass('hidden');
    twDeleteId = null;
}

function tw_confirmDelete() {
    if (!twDeleteId) return;
    $.ajax({ url: tw_api('/tokens/' + twDeleteId), method: 'DELETE' })
    .done(function() { tw_closeDeleteModal(); tw_loadTokens(); })
    .fail(function(xhr) { alert(xhr.responseJSON ? xhr.responseJSON.error : 'Failed to delete token'); });
}

// ---- Token Created Modal ----
function tw_copyCreatedToken() {
    var input = document.getElementById('tw-created-token-value');
    input.select();
    document.execCommand('copy');
}

function tw_doneCreatedToken() {
    $('#tw-created-modal').addClass('hidden');
    tw_loadTokens();
}

// ---- Token Detail Modal ----
var tw_detailTokenId = null;

function tw_openDetailModal(id) {
    var t = twTokens.find(function(tok) { return tok.id === id; });
    if (!t) return;
    tw_detailTokenId = id;
    $('#tw-detail-name').text(t.name);
    $('#tw-detail-token').text('...' + (t.token_preview || '****').slice(-4));
    $('#tw-detail-reveal-btn').prop('disabled', false).text('Reveal');
    var quota = t.quota_limit !== null ? (t.quota_used || 0) + ' / ' + t.quota_limit : 'Unlimited';
    $('#tw-detail-quota').text(quota);
    $('#tw-detail-status').text(t.status);
    $('#tw-detail-created').text(t.created_at ? new Date(t.created_at).toLocaleString() : '-');
    $('#tw-detail-expires').text(t.expires_at ? new Date(t.expires_at).toLocaleDateString() : 'Never');
    $('#tw-detail-last-used').text(t.last_used_at ? tw_timeAgo(t.last_used_at) : 'Never');
    var models = t.allowed_models && t.allowed_models.length > 0 ? t.allowed_models.join(', ') : 'All models';
    $('#tw-detail-models').text(models);
    $('#tw-detail-modal').removeClass('hidden');
}

function tw_revealDetailToken() {
    if (!tw_detailTokenId) return;
    var btn = $('#tw-detail-reveal-btn');
    btn.prop('disabled', true).text('Loading...');
    $.get(tw_api('/tokens/' + tw_detailTokenId + '/reveal'))
    .done(function(data) {
        if (data && data.plaintext) {
            $('#tw-detail-token').text(data.plaintext);
            btn.text('Revealed');
        } else {
            btn.text('Not available');
        }
    })
    .fail(function() {
        $('#tw-detail-token').text('Not available (token not cached)');
        btn.text('Not available');
    });
}

function tw_closeDetailModal() {
    $('#tw-detail-modal').addClass('hidden');
    tw_detailTokenId = null;
}

// ---- Helpers ----
function tw_esc(s) {
    var d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
}

function tw_timeAgo(isoStr) {
    if (!isoStr) return '';
    var diff = (Date.now() - new Date(isoStr).getTime()) / 1000;
    if (diff < 60) return 'Just now';
    var mins = Math.floor(diff / 60);
    if (mins < 60) return mins + 'm ago';
    var hrs = Math.floor(mins / 60);
    if (hrs < 24) return hrs + 'h ago';
    var days = Math.floor(hrs / 24);
    if (days < 30) return days + 'd ago';
    return new Date(isoStr).toLocaleDateString();
}
</script>
