Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python
270 KB
Raw Blame
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    {% include 'includes/theme_account.html' %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <title>{% if is_group_admin_only %}Group Management{% else %}Admin Dashboard{% endif %} - Speakr</title>

    <!-- Loading overlay to prevent FOUC - MUST be first -->
    {% include 'includes/loading_overlay.html' %}

    <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
        <!-- All dependencies bundled locally for offline support -->
        <!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/js/chart.umd.min.js') }}"></script>
        <!-- All dependencies bundled locally for offline support -->
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/primitives.css') }}">
    {% include 'includes/i18n_bootstrap.html' %}
    <script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
    <style>
        /* Hide Vue content until compiled */
        [v-cloak] {
            display: none !important;
        }

        /* Hide scrollbar for tabs */
        .scrollbar-hide {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
            display: none;
        }

        /* Custom select dropdown styling */
        select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            padding-right: 2.5rem !important;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 12px 12px;
        }

        .dark select {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23aaa' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
        }
    </style>
    <script>
        // Initialize i18n
        let t = (key) => key; // Default fallback
        
        async function initializeI18n() {
            const userLanguage = "{{ user_language }}";
            
            // Initialize the global i18n instance
            if (window.i18n) {
                await window.i18n.init(userLanguage);
                
                // Create a shorthand translation function
                t = (key, params) => window.i18n.t(key, params);
                
                // Update all elements with data-i18n attribute
                document.querySelectorAll('[data-i18n]').forEach(el => {
                    const key = el.getAttribute('data-i18n');
                    el.textContent = t(key);
                });
                
                // Update all elements with data-i18n-placeholder attribute
                document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
                    const key = el.getAttribute('data-i18n-placeholder');
                    el.placeholder = t(key);
                });
            }
        }
        
        // Function to apply the theme based on localStorage
        function applyTheme() {
            // Guard against early execution
            if (!document.documentElement) return;

            // Apply dark mode
            const savedMode = localStorage.getItem('darkMode');
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            if (savedMode === 'true' || (savedMode === null && prefersDark)) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }

            // Apply color scheme
            const savedScheme = localStorage.getItem('colorScheme') || 'blue';
            const isDark = document.documentElement.classList.contains('dark');
            const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';
            
            // Remove all other theme classes
            const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];
            themeClasses.forEach(theme => {
                document.documentElement.classList.remove(`theme-light-${theme}`);
                document.documentElement.classList.remove(`theme-dark-${theme}`);
            });

            // Add the correct theme class
            if (savedScheme !== 'blue') {
                 document.documentElement.classList.add(themePrefix + savedScheme);
            }
        }
        applyTheme();

        // The header's controls are driven by static/js/global-header.js.
        document.addEventListener('DOMContentLoaded', () => {
            // Update the tab-footer version string by writing to the
            // --footer-version-text CSS variable that .tab-footer::before
            // reads. Same pattern as the account page.
            (async () => {
                try {
                    const r = await fetch('/api/system/info');
                    if (!r.ok) return;
                    const data = await r.json();
                    if (!data.version) return;
                    const value = `Speakr ${data.version} © {{ now.year }}`;
                    const ft = document.getElementById('footer-text');
                    if (ft) ft.textContent = value;
                    document.documentElement.style.setProperty(
                        '--footer-version-text',
                        `"${value.replace(/"/g, '\\"')}"`
                    );
                } catch (e) { /* leave the fallback "Speakr" string */ }
            })();
        });
    </script>
    <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
         <head> so that, as with the former runtime build, they follow the page's
         own stylesheets in the cascade. -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)] h-full flex flex-col overflow-hidden">
    {% set page_label = ('Team Management' if is_team_admin and not current_user.is_admin else 'Admin') %}
    {% set page_label_key = ('nav.groupManagement' if is_team_admin and not current_user.is_admin else 'admin.title') %}
    {% include 'components/page-header.html' %}
    <!-- inline min-height: 0 beats the global #app { min-height: 100% }
         rule in styles.css (ID selector has higher specificity than the
         Tailwind min-h-0 utility); without this override the flex chain
         couldn't shrink #app below its content height and the sticky
         .tab-footer ended up below the viewport. -->
    <div id="app" v-cloak class="flex-1 flex flex-col overflow-hidden" style="min-height: 0;">
        <main class="flex-1 flex flex-col min-h-0 overflow-hidden">
            <div class="flex-1 flex flex-col min-h-0 overflow-hidden">

                {% with messages = get_flashed_messages(with_categories=true) %}
                    {% if messages %}
                    <div class="px-4 sm:px-6 pt-3 flex-shrink-0">
                        {% for category, message in messages %}
                            <div class="mb-2 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">
                                {{ message }}
                            </div>
                        {% endfor %}
                    </div>
                    {% endif %}
                {% endwith %}

                <!-- Primary tabs strip using the shared .tabs primitive
                     + .tabs-scroller wrapper so the horizontal chevron
                     buttons appear when the strip overflows. Tab IDs
                     not needed (Vue v-show binds the content). -->
                <div class="tabs-scroller flex-shrink-0" data-tabs-scroller>
                    <button type="button" class="tabs-scroller__nav tabs-scroller__nav--left" :aria-label="t('adminDashboard.scrollLeft')">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <nav class="tabs px-3 sm:px-4" :aria-label="t('adminDashboard.tabsLabel')">
                        <button v-if="!isTeamAdminOnly" @click="activeTab = 'users'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'users' }">
                            <i class="fas fa-users"></i><span>${t('adminDashboard.userManagement')}</span>
                        </button>
                        <button v-if="!isTeamAdminOnly" @click="activeTab = 'stats'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'stats' }">
                            <i class="fas fa-chart-bar"></i><span>${t('adminDashboard.systemStatistics')}</span>
                        </button>
                        <button v-if="!isTeamAdminOnly" @click="activeTab = 'settings'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'settings' }">
                            <i class="fas fa-cogs"></i><span>${t('adminDashboard.systemSettings')}</span>
                        </button>
                        <button v-if="!isTeamAdminOnly" @click="activeTab = 'prompts'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'prompts' }">
                            <i class="fas fa-file-alt"></i><span>${t('adminDashboard.defaultPrompts')}</span>
                        </button>
                        <button @click="activeTab = 'groups'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'groups' }">
                            <i class="fas fa-users-cog"></i><span>${t('adminDashboard.groupsTab')}</span>
                        </button>
                        <button v-if="!isTeamAdminOnly && inquireModeEnabled" @click="activeTab = 'vectorstore'"
                                class="tab"
                                :class="{ 'is-active': activeTab === 'vectorstore' }">
                            <i class="fas fa-database"></i><span>${t('adminDashboard.vectorStore')}</span>
                        </button>
                    </nav>
                    <button type="button" class="tabs-scroller__nav tabs-scroller__nav--right" :aria-label="t('adminDashboard.scrollRight')">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>

                <div class="tab-content-wrapper">
                
                <!-- User Management Tab -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'users' }">
                  <div class="tab-scroll">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">${t('adminDashboard.userManagement')}</h3>
                        <button @click="showAddUserModal = true" class="btn btn--primary">
                            <i class="fas fa-user-plus mr-2"></i> ${t('adminDashboard.addUser')}
                        </button>
                    </div>
                    
                    <!-- Search and Filter -->
                    <div class="mb-4 flex">
                        <div class="relative flex-grow">
                            <input type="text" v-model="userSearchQuery" :placeholder="t('adminDashboard.searchUsers')" class="w-full px-4 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                            <button v-if="userSearchQuery" @click="userSearchQuery = ''" class="absolute right-3 top-2.5 text-[var(--text-muted)] hover:text-[var(--text-secondary)]">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Users Table -->
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-[var(--border-primary)]">
                            <thead class="bg-[var(--bg-tertiary)]">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.id')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.username')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.email')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.admin')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.publicShare')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.recordings')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.storageUsed')}</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.actions')}</th>
                                </tr>
                            </thead>
                            <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">
                                <tr v-for="user in filteredUsers" :key="user.id" class="hover:bg-[var(--bg-tertiary)]">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.id }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-[var(--text-primary)]">${ user.username }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.email }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        <span v-if="user.is_admin" class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">${ t('common.yes') }</span>
                                        <span v-else class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-pending-light)] text-[var(--text-pending-strong)]">${ t('common.no') }</span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        <button @click="togglePublicSharingPermission(user)"
                                                class="inline-flex items-center"
                                                :title="user.can_share_publicly ? t('tooltips.revokePublicSharing') : t('tooltips.grantPublicSharing')">
                                            <span v-if="user.can_share_publicly" class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">
                                                <i class="fas fa-check mr-1"></i> ${t('adminDashboard.allowed')}
                                            </span>
                                            <span v-else class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]">
                                                <i class="fas fa-times mr-1"></i> ${t('adminDashboard.blocked')}
                                            </span>
                                        </button>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.recordings_count }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        ${ formatFileSize(user.storage_used) }<span v-if="user.storage_quota_mb" class="text-xs" :class="storagePctClass(storagePct(user)) || 'text-[var(--text-muted)]'"> / ${ formatFileSize(user.storage_quota_mb * 1048576) }</span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        <div class="flex space-x-2">
                                            <button @click="editUser(user)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" :title="t('buttons.editUser')">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button @click="toggleAdminStatus(user)" :class="user.is_admin ? 'text-[var(--text-warn-strong)]' : 'text-[var(--text-info-strong)]'" :title="user.is_admin ? t('tooltips.removeAdmin') : t('tooltips.makeAdmin')">
                                                <i class="fas" :class="user.is_admin ? 'fa-user-minus' : 'fa-user-shield'"></i>
                                            </button>
                                            <button @click="confirmDeleteUser(user)" class="text-[var(--text-danger)] hover:text-[var(--text-danger-hover)]" :title="t('buttons.deleteUser')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr v-if="filteredUsers.length === 0">
                                    <td colspan="8" class="px-6 py-4 text-center text-sm text-[var(--text-muted)]">
                                        <div v-if="isLoadingUsers">
                                            <i class="fas fa-spinner fa-spin mr-2"></i> ${ t('adminDashboard.loadingUsers') }
                                        </div>
                                        <div v-else>
                                            ${ t('unifiedShareModal.noUsersFound') }
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div>

                <!-- System Statistics Tab. One read, /admin/stats/overview,
                     for a range of 7, 30 or 90 days compared with the range
                     before it; recording states and the job queue come from
                     /admin/stats. -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'stats' }">
                  <div class="tab-scroll">
                    <div class="flex flex-wrap items-center justify-between gap-3 mb-1">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">${t('adminDashboard.systemStatistics')}</h3>
                        <div class="flex items-center gap-1.5">
                            <button v-for="d in [7, 30, 90]" :key="d" @click="setStatsDays(d)"
                                    class="btn btn--sm" :class="statsDays === d ? 'btn--primary' : 'btn--ghost'"
                                    :aria-pressed="statsDays === d"
                                    v-text="t('adminDashboard.statsPage.lastDays', { count: d })"></button>
                            <button @click="refreshStats" class="btn btn--sm btn--ghost" :title="t('buttons.refresh')" :aria-label="t('buttons.refresh')">
                                <i class="fas fa-sync-alt" :class="{ 'fa-spin': overviewLoading }"></i>
                            </button>
                        </div>
                    </div>
                    <p class="text-xs text-[var(--text-muted)] mb-4" v-if="overview"
                       v-text="t('adminDashboard.statsPage.rangeNote', { start: formatDay(overview.start), end: formatDay(overview.end), count: overview.days })"></p>

                    <!-- Overview: the range against the range before it -->
                    <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3 mb-6">
                        <div v-for="card in overviewCards" :key="card.key"
                             class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <p class="text-xs font-medium text-[var(--text-muted)] flex items-center gap-1.5 truncate">
                                <i :class="card.icon" class="text-[var(--text-accent)]"></i><span v-text="card.label"></span>
                            </p>
                            <p class="text-2xl font-semibold text-[var(--text-primary)] mt-1 truncate" v-text="card.value"></p>
                            <p class="text-xs mt-0.5 leading-snug sm:truncate text-[var(--text-muted)]" v-text="card.note || ' '"></p>
                        </div>
                    </div>

                    <!-- Activity and health -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 lg:items-start gap-6 mb-6">
                        <div class="lg:col-span-2 bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.recordingsPerDay')}</h4>
                            <div class="h-56"><canvas id="statsRecordingsChart"></canvas></div>
                            <div class="mt-3 grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">
                                <div>
                                    <p class="text-xs text-[var(--text-muted)]">${t('adminDashboard.statsPage.created')}</p>
                                    <p class="font-semibold text-[var(--text-primary)]" v-text="overview ? overview.activity.created.toLocaleString(uiLocale()) : '—'"></p>
                                </div>
                                <div>
                                    <p class="text-xs text-[var(--text-muted)]">${t('adminDashboard.statsPage.medianProcessing')}</p>
                                    <p class="font-semibold text-[var(--text-primary)]" v-text="overview && overview.activity.median_processing_seconds != null ? formatSeconds(overview.activity.median_processing_seconds) : '—'"></p>
                                </div>
                                <div>
                                    <p class="text-xs text-[var(--text-muted)]">${t('adminDashboard.statsPage.failureRate')}</p>
                                    <p class="font-semibold" :class="overview && overview.activity.failed ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-primary)]'"
                                       v-text="overview && overview.activity.failure_rate != null ? t('adminDashboard.statsPage.failedOf', { failed: overview.activity.failed, total: overview.activity.created, pct: formatNumber(overview.activity.failure_rate, { maximumFractionDigits: 1 }) }) : '—'"></p>
                                </div>
                            </div>
                        </div>

                        <div class="flex flex-col gap-6 min-w-0">
                            <!-- Health: states now, the job queue, the latest failures -->
                            <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                                <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.health')}</h4>
                                <dl class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1.5 text-sm">
                                    <template v-for="s in statusRows" :key="s.key">
                                        <div class="flex items-center justify-between gap-2 min-w-0">
                                            <dt class="flex items-center gap-1.5 text-[var(--text-secondary)] truncate">
                                                <span class="inline-block w-2 h-2 rounded-full flex-shrink-0" :style="{ background: s.color }"></span><span v-text="s.label"></span>
                                            </dt>
                                            <dd class="font-semibold text-[var(--text-primary)]" v-text="(s.value || 0).toLocaleString(uiLocale())"></dd>
                                        </div>
                                    </template>
                                </dl>
                                <p class="mt-3 text-sm text-[var(--text-secondary)]">
                                    <i class="fas fa-layer-group mr-1 text-[var(--text-muted)]"></i>
                                    <span v-text="t('adminDashboard.jobQueue', { queued: stats.jobs.queued, running: stats.jobs.running })"></span>
                                    <span v-if="stats.jobs.failed_7d" class="ml-2 text-[var(--text-danger-strong)]"
                                          v-text="t('adminDashboard.jobsFailed7d', { count: stats.jobs.failed_7d })"></span>
                                </p>
                                <div v-if="overview && overview.failed_recent.length" class="mt-3 border-t border-[var(--border-primary)] pt-3">
                                    <p class="text-xs font-medium text-[var(--text-muted)] mb-1.5">${t('adminDashboard.statsPage.latestFailures')}</p>
                                    <ul class="space-y-1.5">
                                        <li v-for="f in overview.failed_recent" :key="f.id" class="text-xs min-w-0" :title="f.error">
                                            <p class="text-[var(--text-primary)] truncate" v-text="f.title"></p>
                                            <p class="text-[var(--text-muted)] truncate">
                                                <span v-text="f.username"></span> · <span v-text="formatDate(f.created_at)"></span><span v-if="f.error"> · </span><span v-text="f.error"></span>
                                            </p>
                                        </li>
                                    </ul>
                                </div>
                            </div>

                            <!-- Voice embedding compatibility (#380). The admin
                                 notification's link lands on this anchor. -->
                            <div id="voice-embeddings" v-if="voiceEmbedding.supported !== false"
                                 class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                                <div class="flex flex-wrap items-center justify-between gap-2 mb-1">
                                    <h4 class="text-md font-medium text-[var(--text-secondary)]">${t('adminDashboard.voiceEmbedding.title')}</h4>
                                    <span class="px-2 py-0.5 rounded text-xs font-semibold"
                                          :class="voiceEmbedding.status === 'ok' ? 'bg-[var(--bg-success)] text-[var(--text-success-strong)]' : (voiceEmbedding.status === 'changed' ? 'bg-[var(--bg-danger)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-secondary)] text-[var(--text-muted)]')"
                                          v-text="voiceEmbedding.status === 'ok' ? t('adminDashboard.voiceEmbedding.statusOk') : (voiceEmbedding.status === 'changed' ? t('adminDashboard.voiceEmbedding.statusChanged') : t('adminDashboard.voiceEmbedding.statusUnknown'))"></span>
                                </div>
                                <p class="text-xs text-[var(--text-muted)] mb-2">${t('adminDashboard.voiceEmbedding.help')}</p>
                                <p class="text-xs text-[var(--text-secondary)] mb-2 flex flex-wrap gap-x-3">
                                    <span v-if="voiceEmbedding.dimension">${t('adminDashboard.voiceEmbedding.dimension')}: <span class="font-medium" v-text="voiceEmbedding.dimension"></span></span>
                                    <span v-if="voiceEmbedding.checked_at" class="text-[var(--text-muted)]">${t('adminDashboard.voiceEmbedding.lastChecked')}: <span v-text="formatDate(voiceEmbedding.checked_at)"></span></span>
                                </p>
                                <!-- Diagnostic string and voice spaces, one per embedding model
                                     seen. Profiles are only compared within their space. -->
                                <details v-if="voiceEmbedding.detail || (voiceEmbedding.spaces && voiceEmbedding.spaces.length)" class="mb-3 text-xs">
                                    <summary class="cursor-pointer text-[var(--text-secondary)]" v-text="t('adminDashboard.voiceEmbedding.spacesTitle')"></summary>
                                    <p v-if="voiceEmbedding.detail" class="mt-2 text-[var(--text-muted)] font-mono break-words" v-text="voiceEmbedding.detail"></p>
                                    <div class="overflow-x-auto">
                                    <table v-if="voiceEmbedding.spaces && voiceEmbedding.spaces.length" class="w-full mt-2">
                                        <thead>
                                            <tr class="text-left text-[var(--text-muted)]">
                                                <th class="py-1 pr-2 font-normal" v-text="t('adminDashboard.voiceEmbedding.space')"></th>
                                                <th class="py-1 pr-2 font-normal" v-text="t('adminDashboard.voiceEmbedding.dimension')"></th>
                                                <th class="py-1 pr-2 font-normal" v-text="t('adminDashboard.voiceEmbedding.samples')"></th>
                                                <th class="py-1 pr-2 font-normal" v-text="t('adminDashboard.voiceEmbedding.threshold')"></th>
                                                <th class="py-1 font-normal" v-text="t('adminDashboard.voiceEmbedding.lastSeen')"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="space in voiceEmbedding.spaces" :key="space.id" class="border-t border-[var(--border-primary)]">
                                                <td class="py-1 pr-2">
                                                    #${ space.id }
                                                    <span v-if="space.current" class="ml-1 px-1.5 rounded bg-[var(--bg-success)] text-[var(--text-success-strong)]" v-text="t('adminDashboard.voiceEmbedding.current')"></span>
                                                </td>
                                                <td class="py-1 pr-2">${ space.dimension || '' }</td>
                                                <td class="py-1 pr-2">${ space.sample_count }</td>
                                                <td class="py-1 pr-2" v-text="space.calibrated_threshold != null ? space.calibrated_threshold : t('adminDashboard.voiceEmbedding.notCalibrated')"></td>
                                                <td class="py-1" v-text="space.last_seen_at ? formatDate(space.last_seen_at) : ''"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                    </div>
                                </details>
                                <div class="flex flex-wrap gap-2">
                                    <button @click="checkVoiceEmbedding" :disabled="voiceEmbeddingBusy" class="btn btn--sm btn--ghost">
                                        <i class="fas fa-sync-alt mr-1" :class="{ 'fa-spin': voiceEmbeddingBusy }"></i>${t('adminDashboard.voiceEmbedding.checkNow')}
                                    </button>
                                    <button @click="rebaselineVoiceEmbedding" :disabled="voiceEmbeddingBusy" class="btn btn--sm btn--danger">
                                        <i class="fas fa-redo mr-1"></i>${t('adminDashboard.voiceEmbedding.rebaseline')}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Usage and cost -->
                    <h4 class="text-lg font-medium text-[var(--text-secondary)] mb-4">
                        <i class="fas fa-coins mr-2"></i>${t('adminDashboard.statsPage.usageAndCost')}
                    </h4>
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                        <div class="lg:col-span-2 bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.llmTokensPerDay')}</h5>
                            <div class="h-64"><canvas id="statsOperationsChart"></canvas></div>
                            <p v-if="overview && overview.usage.cache_reads" class="text-xs text-[var(--text-muted)] mt-2">
                                <i class="fas fa-bolt mr-1 text-[var(--text-accent)]"></i><span v-text="t('adminDashboard.statsPage.cacheLine', { reads: formatCompact(overview.usage.cache_reads), writes: formatCompact(overview.usage.cache_writes) })"></span>
                            </p>
                        </div>
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.minutesPerDay')}</h5>
                            <div class="h-48"><canvas id="statsMinutesChart"></canvas></div>
                        </div>
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.embeddingTokensPerDay')}</h5>
                            <div class="h-48"><canvas id="statsEmbeddingChart"></canvas></div>
                        </div>
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.monthlyCost')}</h5>
                            <div class="h-56"><canvas id="statsMonthlyCostChart"></canvas></div>
                        </div>
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm min-w-0">
                            <h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.statsPage.costByModel')}</h5>
                            <div v-if="!overview || !overview.usage.by_model.length" class="text-sm text-[var(--text-muted)]">${t('adminDashboard.tokenUsage.noUsage')}</div>
                            <div v-else class="overflow-x-auto">
                                <table class="w-full text-sm">
                                    <thead>
                                        <tr class="text-left text-xs text-[var(--text-muted)]">
                                            <th class="py-1 pr-3 font-normal">${t('adminDashboard.statsPage.model')}</th>
                                            <th class="py-1 pr-3 font-normal text-right">${t('adminDashboard.statsPage.requests')}</th>
                                            <th class="py-1 pr-3 font-normal text-right">${t('adminDashboard.statsPage.volume')}</th>
                                            <th class="py-1 font-normal text-right">${t('adminDashboard.statsPage.cost')}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="m in overview.usage.by_model" :key="m.kind + m.model" class="border-t border-[var(--border-primary)]">
                                            <td class="py-1.5 pr-3 min-w-0">
                                                <span class="block truncate max-w-[16rem] text-[var(--text-primary)]" :title="m.model" v-text="m.model || '—'"></span>
                                                <span class="text-xs text-[var(--text-muted)]" v-text="t('adminDashboard.statsPage.kind.' + m.kind)"></span>
                                            </td>
                                            <td class="py-1.5 pr-3 text-right tabular-nums" v-text="m.requests.toLocaleString(uiLocale())"></td>
                                            <td class="py-1.5 pr-3 text-right tabular-nums whitespace-nowrap"
                                                v-text="m.kind === 'transcription' ? t('adminDashboard.statsPage.minutesShort', { count: Math.round(m.minutes).toLocaleString(uiLocale()) }) : formatCompact(m.tokens)"></td>
                                            <td class="py-1.5 text-right tabular-nums whitespace-nowrap" v-text="formatModelCost(m)"></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Users: one sortable table, budgets are monthly -->
                    <h4 class="text-lg font-medium text-[var(--text-secondary)] mb-4">
                        <i class="fas fa-users mr-2"></i>${t('adminDashboard.statsPage.users')}
                    </h4>
                    <div class="bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] shadow-sm overflow-x-auto mb-2">
                        <table class="w-full text-sm">
                            <thead>
                                <tr class="text-left text-xs text-[var(--text-muted)] border-b border-[var(--border-primary)]">
                                    <th v-for="col in userColumns" :key="col.key" class="py-2 px-3 font-medium whitespace-nowrap" :class="col.align === 'right' ? 'text-right' : ''"
                                        :aria-sort="statsSort.key === col.key ? (statsSort.dir > 0 ? 'ascending' : 'descending') : 'none'">
                                        <button type="button" @click="sortUsersBy(col.key)" class="inline-flex items-center gap-1 hover:text-[var(--text-primary)]">
                                            <span v-text="col.label"></span>
                                            <i class="fas text-[10px]" :class="statsSort.key === col.key ? (statsSort.dir > 0 ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort opacity-40'"></i>
                                        </button>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="u in sortedStatsUsers" :key="u.id" class="border-t border-[var(--border-primary)] first:border-t-0">
                                    <td class="py-2 px-3 font-medium text-[var(--text-primary)] whitespace-nowrap">
                                        <span v-text="u.username"></span>
                                        <i v-if="(u.token_pct || 0) >= 80 || (u.minutes_pct || 0) >= 80 || (u.storage_pct || 0) >= 80" class="fas fa-exclamation-triangle ml-1.5"
                                           :class="(u.token_pct || 0) >= 100 || (u.minutes_pct || 0) >= 100 || (u.storage_pct || 0) >= 100 ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-warn-strong)]'"
                                           :title="t('adminDashboard.statsPage.nearBudget')"></i>
                                    </td>
                                    <td class="py-2 px-3 text-right tabular-nums" v-text="u.recordings.toLocaleString(uiLocale())"></td>
                                    <td class="py-2 px-3 text-right min-w-[7rem]">
                                        <span class="tabular-nums whitespace-nowrap" v-text="formatFileSize(u.storage)"></span><span v-if="u.storage_quota" class="text-xs text-[var(--text-muted)] whitespace-nowrap"> / <span v-text="formatFileSize(u.storage_quota)"></span></span>
                                        <div v-if="u.storage_quota" class="w-full bg-[var(--bg-secondary)] rounded-full h-1 mt-1">
                                            <div class="h-1 rounded-full" :class="budgetBarClass(u.storage_pct)" :style="{ width: Math.min(u.storage_pct || 0, 100) + '%' }"></div>
                                        </div>
                                    </td>
                                    <td class="py-2 px-3 whitespace-nowrap text-[var(--text-secondary)]" v-text="u.last_recording_at ? formatDay(u.last_recording_at.slice(0, 10)) : '—'"></td>
                                    <td class="py-2 px-3 text-right min-w-[8rem]">
                                        <span class="tabular-nums" v-text="formatCompact(u.tokens_month)"></span><span v-if="u.token_budget" class="text-xs text-[var(--text-muted)]"> / <span v-text="formatCompact(u.token_budget)"></span></span>
                                        <div v-if="u.token_budget" class="w-full bg-[var(--bg-secondary)] rounded-full h-1 mt-1">
                                            <div class="h-1 rounded-full" :class="budgetBarClass(u.token_pct)" :style="{ width: Math.min(u.token_pct || 0, 100) + '%' }"></div>
                                        </div>
                                    </td>
                                    <td class="py-2 px-3 text-right min-w-[8rem]">
                                        <span class="tabular-nums" v-text="u.minutes_month.toLocaleString(uiLocale())"></span><span v-if="u.minutes_budget" class="text-xs text-[var(--text-muted)]"> / <span v-text="u.minutes_budget.toLocaleString(uiLocale())"></span></span>
                                        <div v-if="u.minutes_budget" class="w-full bg-[var(--bg-secondary)] rounded-full h-1 mt-1">
                                            <div class="h-1 rounded-full" :class="budgetBarClass(u.minutes_pct)" :style="{ width: Math.min(u.minutes_pct || 0, 100) + '%' }"></div>
                                        </div>
                                    </td>
                                    <td class="py-2 px-3 text-right tabular-nums whitespace-nowrap" v-text="formatCost(u.cost_month)"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <p class="text-xs text-[var(--text-muted)]">${t('adminDashboard.statsPage.usersNote')}</p>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div>

                <!-- System Settings Tab -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'settings' }">
                  <div class="tab-scroll">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">${t('adminDashboard.systemSettings')}</h3>
                        <button @click="loadSettings" class="btn btn--primary">
                            <i class="fas fa-sync-alt mr-2"></i> ${t('buttons.refresh')}
                        </button>
                    </div>

                    <!-- Transcription Models curation. Single bordered
                         section (no nested card chrome) — the section
                         header carries the title + Discover button on
                         one row; the table fills the panel below; the
                         action row at the bottom carries Add + Save
                         + status. The underlying SystemSetting rows
                         (transcription_models_visible_json,
                         transcription_default_model) are filtered out
                         of the settings list below — managed here. -->
                    <div class="mb-6 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg overflow-hidden">
                        <!-- Section header -->
                        <div class="flex items-center justify-between gap-3 px-4 py-3 border-b border-[var(--border-primary)]">
                            <div class="min-w-0">
                                <h4 class="text-sm font-semibold text-[var(--text-primary)] flex items-center gap-2">
                                    <i class="fas fa-microphone-lines text-[var(--text-accent)]"></i>
                                    <span>${ t('adminDashboard.transcriptionModels') }</span>
                                </h4>
                                <p class="text-xs text-[var(--text-muted)] mt-0.5">${ t('adminDashboard.transcriptionModelsDesc') }</p>
                            </div>
                            <button @click="discoverTranscriptionModels" :disabled="discoveringModels"
                                    class="btn btn--ghost flex-shrink-0 whitespace-nowrap">
                                <i :class="discoveringModels ? 'fas fa-spinner fa-spin' : 'fas fa-search'"></i>
                                <span>${ discoveringModels ? t('adminDashboard.discovering') : t('adminDashboard.discover') }</span>
                            </button>
                        </div>

                        <!-- Connector info / error banners -->
                        <div v-if="modelDiscoveryError" class="banner banner--danger mx-4 mt-3">
                            <i class="fas fa-exclamation-triangle"></i>
                            <span>${ modelDiscoveryError }</span>
                        </div>
                        <div v-if="modelDiscoveryResult" class="px-4 pt-3 text-xs text-[var(--text-muted)]">
                            ${ t('adminDashboard.activeConnector') }: <code class="bg-[var(--bg-tertiary)] px-1.5 py-0.5 rounded text-[var(--text-secondary)]">${ modelDiscoveryResult.connector }</code>
                            <span v-if="!modelDiscoveryResult.supported"> · ${ t('adminDashboard.noDiscoveryApi') }</span>
                        </div>

                        <!-- Models table -->
                        <div v-if="visibleTranscriptionModels.length > 0 || (modelDiscoveryResult && modelDiscoveryResult.models && modelDiscoveryResult.models.length > 0)"
                             class="px-1 py-2">
                            <table class="w-full text-sm">
                                <thead>
                                    <tr class="text-left t-label">
                                        <th class="py-2 px-3 w-16">${ t('adminDashboard.modelVisible') }</th>
                                        <th class="py-2 px-3 w-16">${ t('transcriptTemplates.default') }</th>
                                        <th class="py-2 px-3">${ t('adminDashboard.modelId') }</th>
                                        <th class="py-2 px-3">${ t('adminDashboard.modelLabel') }</th>
                                        <th class="py-2 px-3 w-24">${ t('adminDashboard.modelSource') }</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="row in transcriptionModelRows" :key="row.value"
                                        class="border-t border-[var(--border-primary)] hover:bg-[var(--bg-tertiary)] transition-colors">
                                        <td class="py-2 px-3 text-center"><input type="checkbox" v-model="row.visible" class="h-4 w-4"></td>
                                        <td class="py-2 px-3 text-center"><input type="radio" :value="row.value" v-model="transcriptionDefaultModel" :disabled="!row.visible" class="h-4 w-4"></td>
                                        <td class="py-2 px-3 font-mono text-xs text-[var(--text-primary)]">${ row.value }</td>
                                        <td class="py-2 px-3"><input type="text" v-model="row.label" class="field field--sm" :placeholder="t('adminDashboard.friendlyLabel')"></td>
                                        <td class="py-2 px-3 text-xs text-[var(--text-muted)]">${ row.source }</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div v-else class="empty">
                            <div class="empty__icon"><i class="fas fa-microphone-lines"></i></div>
                            <div class="empty__title">${ t('adminDashboard.noModelsConfigured') }</div>
                            <div class="empty__body">${ t('adminDashboard.noModelsConfiguredHelp') }</div>
                        </div>

                        <!-- Action row -->
                        <div class="flex flex-wrap items-center gap-2 px-4 py-3 border-t border-[var(--border-primary)] bg-[var(--bg-tertiary)]">
                            <button @click="addManualTranscriptionModel" class="btn btn--ghost btn--sm">
                                <i class="fas fa-plus"></i><span>${ t('adminDashboard.addModelId') }</span>
                            </button>
                            <span v-if="modelSaveMessage" class="text-sm ml-2"
                                  :class="modelSaveError ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-success-strong)]'">
                                <i :class="modelSaveError ? 'fas fa-exclamation-circle' : 'fas fa-check-circle'" class="mr-1"></i>
                                ${ modelSaveMessage }
                            </span>
                            <button @click="saveVisibleTranscriptionModels" :disabled="savingModels"
                                    class="btn btn--primary btn--sm ml-auto">
                                <i :class="savingModels ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
                                <span>${ savingModels ? t('adminDashboard.saving') : t('adminDashboard.saveSelection') }</span>
                            </button>
                        </div>
                    </div>

                    <!-- Settings List. We exclude the two settings that
                         are managed by the Transcription Models panel
                         above (transcription_models_visible_json,
                         transcription_default_model) so the admin
                         can't accidentally edit the raw JSON / model
                         string here and put them out of sync. -->
                    <div class="space-y-4">
                        <div v-for="setting in displayedSettings" :key="setting.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex justify-between items-start">
                                <div class="flex-grow">
                                    <h4 class="text-md font-medium text-[var(--text-primary)] mb-1">${ setting.key }</h4>
                                    <p class="text-sm text-[var(--text-muted)] mb-2">${ getSettingDescription(setting) }</p>
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs px-2 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded">${ setting.setting_type }</span>
                                        <span class="text-xs text-[var(--text-muted)]">${t('adminDashboard.lastUpdated')}: ${ formatDate(setting.updated_at) }</span>
                                    </div>
                                </div>
                                <div class="ml-4 flex items-center space-x-2">
                                    <div class="text-right">
                                        <div class="text-sm font-medium text-[var(--text-primary)]">
                                            <span v-if="setting.setting_type === 'boolean'">
                                                <span v-if="setting.value === 'true'" class="text-[var(--text-success-strong)]">
                                                    <i class="fas fa-check-circle mr-1"></i> ${ t('webhooks.enabled') }
                                                </span>
                                                <span v-else class="text-[var(--text-danger-strong)]">
                                                    <i class="fas fa-times-circle mr-1"></i> ${ t('adminDashboard.disabled') }
                                                </span>
                                            </span>
                                            <span v-else-if="setting.key === 'transcript_length_limit' && setting.value === '-1'" class="text-[var(--text-info-strong)]">
                                                <i class="fas fa-infinity mr-1"></i> ${t('adminDashboard.noLimit')}
                                            </span>
                            <span v-else-if="setting.key === 'transcript_length_limit'" class="text-[var(--text-primary)]">
                                ${ Number(setting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.characters')}
                            </span>
                            <span v-else-if="setting.key === 'max_file_size_mb'" class="text-[var(--text-primary)]">
                                ${ Number(setting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.megabytes')}
                            </span>
                            <span v-else-if="setting.key === 'asr_timeout_seconds'" class="text-[var(--text-primary)]">
                                ${ Number(setting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.seconds')}
                            </span>
                                            <span v-else-if="setting.value && setting.value.length > 80" class="text-[var(--text-muted)] italic">${ setting.value.substring(0, 80) }...</span>
                                            <span v-else>${ setting.value || t('adminDashboard.notSet') }</span>
                                        </div>
                                    </div>
                                    <button @click="editSetting(setting)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)] p-1" :title="t('buttons.editSetting')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div v-if="settings.length === 0" class="text-center py-8">
                            <div v-if="isLoadingSettings">
                                <i class="fas fa-spinner fa-spin mr-2"></i> ${ t('adminDashboard.loadingSettings') }
                            </div>
                            <div v-else class="text-[var(--text-muted)]">
                                ${ t('adminDashboard.noSettingsFound') }
                            </div>
                        </div>
                    </div>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div>

                <!-- Default Prompts Tab -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'prompts' }">
                  <div class="tab-scroll">
                    <div class="mb-6">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">${t('adminDashboard.defaultPrompts')}</h3>
                        <div class="bg-[var(--bg-info-light)] text-[var(--text-info-strong)] p-4 rounded-lg mb-4">
                            <i class="fas fa-info-circle mr-2"></i>
                            ${t('adminDashboard.defaultPromptInfo')}
                        </div>
                    </div>
                    
                    <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                                ${t('adminDashboard.defaultSummarizationPrompt')}
                            </label>
                            <p class="text-sm text-[var(--text-muted)] mb-3">
                                ${t('adminDashboard.promptDescription')}
                            </p>
                            <textarea
                                v-model="defaultSummaryPrompt"
                                rows="8"
                                class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                :placeholder="t('form.summaryPromptPlaceholder')">
                            </textarea>
                        </div>
                        
                        <div class="flex justify-between items-center">
                            <div>
                                <button @click="resetDefaultPrompt" 
                                        class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">
                                    <i class="fas fa-undo mr-2"></i> ${t('adminDashboard.resetToDefault')}
                                </button>
                            </div>
                            <div>
                                <button @click="saveDefaultPrompt" 
                                        :disabled="isSavingPrompt"
                                        class="btn btn--primary">
                                    <i v-if="isSavingPrompt" class="fas fa-spinner fa-spin mr-2"></i>
                                    <i v-else class="fas fa-save mr-2"></i>
                                    ${ isSavingPrompt ? t('adminDashboard.saving') : t('buttons.saveChanges') }
                                </button>
                            </div>
                        </div>
                        
                        <div v-if="promptSaveMessage" class="mt-4">
                            <div :class="promptSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
                                 class="p-3 rounded-md text-sm">
                                ${ promptSaveMessage }
                            </div>
                        </div>
                    </div>

                    <!-- Default transcription hints: global initial prompt + hotwords applied
                         when a user has not set their own. Authoritative editor for the
                         admin_default_initial_prompt / admin_default_hotwords settings
                         (hidden from the raw System Settings list to avoid a duplicate editor). -->
                    <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.defaultTranscriptionHints')}</h4>
                        <p class="text-sm text-[var(--text-muted)] mb-4">${t('adminDashboard.defaultTranscriptionHintsInfo')}</p>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">${t('adminDashboard.defaultInitialPromptLabel')}</label>
                            <p class="text-sm text-[var(--text-muted)] mb-3">${t('adminDashboard.defaultInitialPromptDesc')}</p>
                            <textarea
                                v-model="defaultInitialPrompt"
                                rows="3"
                                class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                :placeholder="t('account.defaultInitialPromptPlaceholder')">
                            </textarea>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">${t('adminDashboard.defaultHotwordsLabel')}</label>
                            <p class="text-sm text-[var(--text-muted)] mb-3">${t('adminDashboard.defaultHotwordsDesc')}</p>
                            <input
                                type="text"
                                v-model="defaultHotwords"
                                class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                :placeholder="t('form.hotwordsPlaceholder')">
                        </div>

                        <div class="flex justify-end items-center">
                            <button @click="saveDefaultHints"
                                    :disabled="isSavingHints"
                                    class="btn btn--primary">
                                <i v-if="isSavingHints" class="fas fa-spinner fa-spin mr-2"></i>
                                <i v-else class="fas fa-save mr-2"></i>
                                ${ isSavingHints ? t('adminDashboard.saving') : t('buttons.saveChanges') }
                            </button>
                        </div>

                        <div v-if="hintsSaveMessage" class="mt-4">
                            <div :class="hintsSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
                                 class="p-3 rounded-md text-sm">
                                ${ hintsSaveMessage }
                            </div>
                        </div>
                    </div>

                    <!-- Default title instructions (#400): the admin level of the title
                         precedence (tag > folder > user > admin > shipped default). Only the
                         instructions are editable; the transcript, the language directive and
                         the "reply with the title alone" rule are added in code, after the
                         transcript, so editing this never disturbs prefix caching. -->
                    <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-medium text-[var(--text-secondary)] mb-1" v-text="t('adminDashboard.defaultTitlePromptTitle')"></h4>
                        <p class="text-sm text-[var(--text-muted)] mb-4" v-text="t('adminDashboard.defaultTitlePromptDesc')"></p>
                        <div class="mb-4">
                            <textarea
                                v-model="defaultTitlePrompt"
                                rows="4"
                                class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                :placeholder="t('adminDashboard.defaultTitlePromptPlaceholder')">
                            </textarea>
                        </div>
                        <div class="flex justify-end items-center">
                            <button @click="saveDefaultTitlePrompt"
                                    :disabled="isSavingTitlePrompt"
                                    class="btn btn--primary">
                                <i v-if="isSavingTitlePrompt" class="fas fa-spinner fa-spin mr-2"></i>
                                <i v-else class="fas fa-save mr-2"></i>
                                ${ isSavingTitlePrompt ? t('adminDashboard.saving') : t('buttons.saveChanges') }
                            </button>
                        </div>
                        <div v-if="titlePromptSaveMessage" class="mt-4">
                            <div :class="titlePromptSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
                                 class="p-3 rounded-md text-sm">
                                ${ titlePromptSaveMessage }
                            </div>
                        </div>
                    </div>

                    <!-- Generation temperatures (#411): admin value, else the built-in
                         default, per kind of request. -->
                    <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-medium text-[var(--text-secondary)] mb-1" v-text="t('adminDashboard.temperatures.heading')"></h4>
                        <p class="text-sm text-[var(--text-muted)] mb-4" v-text="t('adminDashboard.temperatures.description')"></p>
                        <div class="grid grid-cols-2 lg:grid-cols-4 gap-3">
                            <div v-for="kind in temperatureKinds" :key="kind">
                                <label :for="'temperature-' + kind" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" v-text="t('adminDashboard.temperatures.' + kind)"></label>
                                <div class="flex items-center gap-1">
                                    <input :id="'temperature-' + kind" type="number" min="0" max="2" step="0.1"
                                           v-model="temperatureInputs[kind]"
                                           :placeholder="temperatureStatus[kind] ? String(temperatureStatus[kind].value) : ''"
                                           class="w-full px-2 py-1 text-sm border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]">
                                    <button v-if="temperatureStatus[kind] && temperatureStatus[kind].source === 'admin'"
                                            type="button" @click="resetTemperature(kind)"
                                            class="btn btn--icon btn--sm" :title="t('adminDashboard.temperatures.reset')" :aria-label="t('adminDashboard.temperatures.reset')">
                                        <i class="fas fa-undo"></i>
                                    </button>
                                </div>
                                <p v-if="temperatureStatus[kind]" class="mt-1 text-xs text-[var(--text-muted)]"
                                   v-text="temperatureSourceText(kind)"></p>
                            </div>
                        </div>
                        <div class="flex justify-end items-center mt-4">
                            <button @click="saveTemperatures" :disabled="isSavingTemperatures" class="btn btn--primary">
                                <i v-if="isSavingTemperatures" class="fas fa-spinner fa-spin mr-2"></i>
                                <i v-else class="fas fa-save mr-2"></i>
                                ${ isSavingTemperatures ? t('adminDashboard.saving') : t('buttons.saveChanges') }
                            </button>
                        </div>
                        <div v-if="temperatureSaveMessage" class="mt-4">
                            <div :class="temperatureSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
                                 class="p-3 rounded-md text-sm" v-text="temperatureSaveMessage"></div>
                        </div>
                    </div>

                    <!-- Contextual speaker labelling: guidance used when a recording has
                         no voice embeddings and speakers are named from the transcript,
                         constrained to the user's saved profiles. Only this guidance is
                         editable; the candidate list and JSON output contract are fixed in
                         code. It is the trailing (variable) part of a transcript-first
                         prompt, so editing it does not disturb prefix caching. -->
                    <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.contextualSpeakerPromptTitle')}</h4>
                        <p class="text-sm text-[var(--text-muted)] mb-4">
                            ${t('adminDashboard.contextualSpeakerPromptDesc')}
                        </p>
                        <div class="mb-4">
                            <textarea
                                v-model="contextualSpeakerPrompt"
                                rows="5"
                                class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                :placeholder="t('adminDashboard.contextualSpeakerPromptPlaceholder')">
                            </textarea>
                        </div>
                        <div class="flex justify-end items-center">
                            <button @click="saveContextualSpeakerPrompt"
                                    :disabled="isSavingContextualPrompt"
                                    class="btn btn--primary">
                                <i v-if="isSavingContextualPrompt" class="fas fa-spinner fa-spin mr-2"></i>
                                <i v-else class="fas fa-save mr-2"></i>
                                ${ isSavingContextualPrompt ? t('adminDashboard.saving') : t('buttons.saveChanges') }
                            </button>
                        </div>
                        <div v-if="contextualPromptSaveMessage" class="mt-4">
                            <div :class="contextualPromptSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
                                 class="p-3 rounded-md text-sm">
                                ${ contextualPromptSaveMessage }
                            </div>
                        </div>
                    </div>

                    <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.promptHierarchy')}</h4>
                        <p class="text-sm text-[var(--text-muted)] mb-3">
                            ${t('adminDashboard.promptPriorityDescription')}
                        </p>
                        <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">
                            <li><strong>${t('adminDashboard.tagCustomPrompt')}:</strong> ${t('adminDashboard.tagCustomPromptDesc')}</li>
                            <li><strong>${t('adminDashboard.folderCustomPrompt')}:</strong> ${t('adminDashboard.folderCustomPromptDesc')}</li>
                            <li><strong>${t('adminDashboard.userCustomPrompt')}:</strong> ${t('adminDashboard.userCustomPromptDesc')}</li>
                            <li><strong>${t('adminDashboard.adminDefaultPrompt')}:</strong> ${t('adminDashboard.adminDefaultPromptDesc')}</li>
                            <li><strong>${t('adminDashboard.systemFallback')}:</strong> ${t('adminDashboard.systemFallbackDesc')}</li>
                        </ol>
                    </div>
                    
                    <!-- Full LLM Prompt Structure Expander -->
                    <div class="mt-6 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)]">
                        <button @click="showFullPromptStructure = !showFullPromptStructure" 
                                class="w-full p-6 flex justify-between items-center hover:bg-[var(--bg-quaternary)] transition-colors duration-200">
                            <h4 class="text-md font-medium text-[var(--text-secondary)]">
                                <i class="fas fa-code mr-2"></i>
                                ${t('adminDashboard.viewFullPromptStructure')}
                            </h4>
                            <i :class="showFullPromptStructure ? 'fas fa-chevron-up' : 'fas fa-chevron-down'" 
                               class="text-[var(--text-muted)]"></i>
                        </button>
                        
                        <div v-show="showFullPromptStructure" class="border-t border-[var(--border-primary)]">
                            <div class="p-6 space-y-6">
                                <!-- Placeholder legend so the two distinct syntaxes in the previews below are unambiguous. -->
                                <div class="flex flex-wrap items-center gap-3 text-xs text-[var(--text-secondary)] -mt-2">
                                    <span class="font-medium">${ t('preview.placeholderLegend') }</span>
                                    <span class="inline-flex items-center gap-1.5">
                                        <span class="pill-status pill-status--info font-mono">{example}</span>
                                        <span>${ t('preview.systemReplaced') }</span>
                                    </span>
                                    <span class="inline-flex items-center gap-1.5">
                                        <span class="pill-status pill-status--warn font-mono">{{ '{{example}}' }}</span>
                                        <span>${ t('preview.userSupplied') }</span>
                                    </span>
                                </div>

                                <div>
                                    <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">${t('adminDashboard.systemPrompt')}:</h5>
                                    <div class="bg-[var(--bg-secondary)] p-4 rounded-md border border-[var(--border-secondary)]">
                                        <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono"><span v-html="formatPromptPreview('You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly.\n\nContext:\n- Current date: {current_date}')"></span>
<span v-html="formatPromptPreview('- Recording date: {recording_date}')"></span> <span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.ifMeetingDate') }</span>
<span v-html="formatPromptPreview('- Recording title: {recording_title}')"></span> <span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.ifTitle') }</span>
<span v-html="formatPromptPreview('- Folder: {folder_name}')"></span> <span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.ifFolder') }</span>
<span v-html="formatPromptPreview('- Tags applied to this transcript by the user: {tag_names}')"></span> <span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.ifTags') }</span>
<span v-html="formatPromptPreview('- Information about the user: Name: {name}, Job title: {job_title}, Company: {company}')"></span> <span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.ifProfile') }</span>

<span class="text-[var(--text-muted)]"><span v-html="formatPromptPreview('Language Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory.')"></span> ${ t('adminDashboard.promptStructure.ifLanguage') }</span></pre>
                                    </div>
                                </div>

                                <div>
                                    <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">${t('adminDashboard.userMessageTemplate')}:</h5>
                                    <div class="bg-[var(--bg-secondary)] p-4 rounded-md border border-[var(--border-secondary)]">
                                        <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono">Transcription:
"""
<span v-html="formatPromptPreview('{transcript_text}')"></span>
"""

Summarization Instructions:
<span class="text-[var(--text-muted)]">${ t('adminDashboard.promptStructure.instructionsComment') }</span>
<span v-if="defaultSummaryPrompt || originalDefaultPrompt" v-html="formatPromptPreview(defaultSummaryPrompt || originalDefaultPrompt)"></span>

<span class="text-[var(--text-muted)]"><span v-html="formatPromptPreview('{language_directive}')"></span> ${ t('adminDashboard.promptStructure.languageDirectiveNote') }</span></pre>
                                    </div>
                                    <p class="text-xs text-[var(--text-muted)] mt-2">
                                        <i class="fas fa-info-circle mr-1"></i>
                                        ${t('adminDashboard.placeholdersNote')}
                                    </p>
                                </div>
                                
                                <div>
                                    <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">${t('adminDashboard.additionalContext')}:</h5>
                                    <div class="bg-[var(--bg-info-light)] p-4 rounded-md">
                                        <ul class="text-xs text-[var(--text-info-strong)] space-y-2">
                                            <li><i class="fas fa-check-circle mr-1"></i> ${t('adminDashboard.contextNotes.transcriptLimit')}</li>
                                            <li><i class="fas fa-check-circle mr-1"></i> ${t('adminDashboard.contextNotes.jsonConversion')}</li>
                                            <li><i class="fas fa-check-circle mr-1"></i> ${t('adminDashboard.contextNotes.tagPrompts')}</li>
                                            <li><i class="fas fa-check-circle mr-1"></i> ${t('adminDashboard.contextNotes.modelConfig')}</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div>

                <!-- Vector Store Tab -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'vectorstore' }" v-if="inquireModeEnabled">
                  <div class="tab-scroll">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">${t('adminDashboard.vectorStoreManagement')}</h3>
                        <button @click="loadInquireStatus" class="btn btn--primary">
                            <i class="fas fa-sync-alt mr-2"></i> ${t('adminDashboard.refreshStatus')}
                        </button>
                    </div>
                    
                    <!-- Vector Store Info -->
                    <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)] mb-6">
                        <h4 class="text-md font-semibold text-[var(--text-primary)] mb-4">
                            <i class="fas fa-info-circle mr-2"></i>${t('adminDashboard.aboutInquireMode')}
                        </h4>
                        <p class="text-sm text-[var(--text-secondary)] mb-3">
                            ${t('adminDashboard.inquireModeDescription')}
                        </p>
                        <div class="grid grid-cols-2 gap-4 text-sm">
                            <div>
                                <span class="text-[var(--text-muted)]">${t('adminDashboard.chunkSize')}:</span>
                                <span class="ml-2 text-[var(--text-primary)]">${ inquireStatus.chunking_strategy === 'legacy' ? ('500 ' + t('adminDashboard.characters')) : ((inquireStatus.chunk_target_chars || 1400) + ' ' + t('adminDashboard.characters')) }</span>
                            </div>
                            <div>
                                <span class="text-[var(--text-muted)]">${t('adminDashboard.chunkingStrategy')}:</span>
                                <span class="ml-2 text-[var(--text-primary)]" v-text="inquireStatus.chunking_strategy === 'legacy' ? t('adminDashboard.chunkingLegacy') : t('adminDashboard.chunkingSegmentAware')"></span>
                            </div>
                            <div>
                                <span class="text-[var(--text-muted)]">${t('adminDashboard.embeddingModel')}:</span>
                                <span class="ml-2 text-[var(--text-primary)] break-all">${ inquireStatus.embedding_model || 'all-MiniLM-L6-v2' }</span>
                            </div>
                            <div>
                                <span class="text-[var(--text-muted)]">${ t('adminDashboard.embeddingProvider') }:</span>
                                <span class="ml-2 text-[var(--text-primary)]">
                                    <template v-if="inquireStatus.embedding_provider === 'api'">
                                        API (${ inquireStatus.embedding_base_url })
                                    </template>
                                    <template v-else>
                                        ${ t('adminDashboard.embeddingProviderLocal') }
                                    </template>
                                </span>
                            </div>
                            <div v-if="inquireStatus.embedding_dimensions_override">
                                <span class="text-[var(--text-muted)]">${t('adminDashboard.vectorDimensions')}:</span>
                                <span class="ml-2 text-[var(--text-primary)]">${ inquireStatus.embedding_dimensions_override }</span>
                            </div>
                        </div>
                    </div>

                    <!-- Identifier mismatch alert: chunks were embedded with a previous configuration -->
                    <div v-if="inquireStatus.embedding_identifier_mismatch" class="mb-6 p-4 rounded-lg bg-[var(--bg-warning-light)] border border-[var(--border-warning)]">
                        <div class="flex items-start">
                            <i class="fas fa-exclamation-triangle text-[var(--text-warning-strong)] mt-0.5 mr-3"></i>
                            <div class="flex-1">
                                <p class="font-semibold text-[var(--text-warning-strong)]">${ t('adminDashboard.embeddingConfigChanged') }</p>
                                <p class="text-sm text-[var(--text-secondary)] mt-1" v-text="t('adminDashboard.embeddingConfigChangedDesc', { count: inquireStatus.total_chunks, stored: inquireStatus.embedding_identifier_stored, active: inquireStatus.embedding_identifier })"></p>
                                <button @click="reembedAllRecordings"
                                        :disabled="isProcessingRecordings"
                                        class="mt-3 px-4 py-2 bg-[var(--bg-warning-strong)] text-white rounded-lg shadow hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed">
                                    <i :class="isProcessingRecordings ? 'fas fa-spinner fa-spin' : 'fas fa-sync-alt'" class="mr-2"></i>
                                    ${ isProcessingRecordings ? t('adminDashboard.reembedding') : t('adminDashboard.reembedAllNow') }
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Grid -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.totalRecordings')}</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ inquireStatus.total_completed_recordings || 0 }</p>
                                </div>
                                <i class="fas fa-file-audio text-3xl text-[var(--text-accent)] opacity-50"></i>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.processedForInquire')}</p>
                                    <p class="text-2xl font-semibold text-[var(--text-success-strong)]">${ inquireStatus.processed_for_inquire || 0 }</p>
                                </div>
                                <i class="fas fa-check-circle text-3xl text-[var(--text-success-strong)] opacity-50"></i>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.needProcessing')}</p>
                                    <p class="text-2xl font-semibold" :class="inquireStatus.need_processing > 0 ? 'text-[var(--text-warning-strong)]' : 'text-[var(--text-primary)]'">
                                        ${ inquireStatus.need_processing || 0 }
                                    </p>
                                </div>
                                <i class="fas fa-clock text-3xl opacity-50" :class="inquireStatus.need_processing > 0 ? 'text-[var(--text-warning-strong)]' : 'text-[var(--text-muted)]'"></i>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.totalChunks')}</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ inquireStatus.total_chunks || 0 }</p>
                                </div>
                                <i class="fas fa-th text-3xl text-[var(--text-accent)] opacity-50"></i>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.embeddingsStatus')}</p>
                                    <p class="text-lg font-semibold" :class="inquireStatus.embeddings_available ? 'text-[var(--text-success-strong)]' : 'text-[var(--text-warning-strong)]'">
                                        <i :class="inquireStatus.embeddings_available ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle'" class="mr-2"></i>
                                        ${ inquireStatus.embeddings_available ? t('adminDashboard.available') : t('adminDashboard.textSearchOnly') }
                                    </p>
                                </div>
                                <i class="fas fa-brain text-3xl opacity-50" :class="inquireStatus.embeddings_available ? 'text-[var(--text-success-strong)]' : 'text-[var(--text-warning-strong)]'"></i>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${t('adminDashboard.processingProgress')}</p>
                                    <div class="mt-2">
                                        <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2.5">
                                            <div class="bg-[var(--text-accent)] h-2.5 rounded-full" :style="{width: getProcessingProgress() + '%'}"></div>
                                        </div>
                                        <p class="text-xs text-[var(--text-muted)] mt-1">${ formatPercent(getProcessingProgress()) } ${t('adminDashboard.complete')}</p>
                                    </div>
                                </div>
                                <i class="fas fa-tasks text-3xl text-[var(--text-accent)] opacity-50"></i>
                            </div>
                        </div>

                        <!-- Embedding API usage (only meaningful in API mode) -->
                        <div v-if="inquireStatus.embedding_provider === 'api'" class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${ t('adminDashboard.embeddingApiTokens') }</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ (inquireStatus.embedding_usage && inquireStatus.embedding_usage.total_tokens || 0).toLocaleString(uiLocale()) }</p>
                                    <p class="text-xs text-[var(--text-muted)] mt-1" v-text="t('adminDashboard.embeddingApiRequests', { count: inquireStatus.embedding_usage && inquireStatus.embedding_usage.request_count || 0 })"></p>
                                </div>
                                <i class="fas fa-coins text-3xl text-[var(--text-accent)] opacity-50"></i>
                            </div>
                        </div>

                        <div v-if="inquireStatus.embedding_provider === 'api'" class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-[var(--text-muted)]">${ t('adminDashboard.embeddingApiCost') }</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">$${ (inquireStatus.embedding_usage && inquireStatus.embedding_usage.total_cost || 0).toFixed(4) }</p>
                                    <p class="text-xs text-[var(--text-muted)] mt-1" v-if="inquireStatus.embedding_usage && inquireStatus.embedding_usage.total_cost === 0">${ t('adminDashboard.embeddingCostUnavailable') }</p>
                                </div>
                                <i class="fas fa-dollar-sign text-3xl text-[var(--text-accent)] opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Processing Actions -->
                    <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
                        <h4 class="text-md font-semibold text-[var(--text-primary)] mb-4">
                            <i class="fas fa-cog mr-2"></i>${t('adminDashboard.processingActions')}
                        </h4>
                        
                        <div v-if="inquireStatus.need_processing > 0" class="mb-4">
                            <p class="text-sm text-[var(--text-secondary)] mb-4">
                                ${ recordingsNeedProcessingMessage }
                            </p>
                            
                            <div class="flex flex-wrap gap-3">
                                <button @click="processAllRecordings" 
                                        :disabled="isProcessingRecordings"
                                        class="btn btn--primary">
                                    <i :class="isProcessingRecordings ? 'fas fa-spinner fa-spin' : 'fas fa-play'" class="mr-2"></i>
                                    ${ isProcessingRecordings ? t('adminDashboard.processing') : t('adminDashboard.processAllRecordings') }
                                </button>
                                
                                <button @click="processBatchRecordings(10)" 
                                        :disabled="isProcessingRecordings"
                                        class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded-lg shadow hover:bg-[var(--bg-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed">
                                    <i class="fas fa-forward mr-2"></i>
                                    ${t('adminDashboard.processNext10')}
                                </button>
                            </div>
                            
                            <div v-if="processingResult" class="mt-4 p-4 rounded-lg" 
                                 :class="processingResult.success ? 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]' : 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]'">
                                <p class="font-medium">${ processingResult.message }</p>
                                <div v-if="processingResult.failed && processingResult.failed.length > 0" class="mt-2">
                                    <p class="text-sm font-medium">${ t('adminDashboard.failedRecordingsLabel') }:</p>
                                    <ul class="text-xs mt-1 space-y-1">
                                        <li v-for="fail in processingResult.failed" :key="fail.id">
                                            ID ${ fail.id }: ${ fail.title } - ${ fail.reason }
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <div v-else class="text-center py-4">
                            <i class="fas fa-check-circle text-4xl text-[var(--text-success-strong)] mb-3"></i>
                            <p class="text-[var(--text-success-strong)] font-medium">${t('adminDashboard.allRecordingsProcessed')}</p>
                            <p class="text-sm text-[var(--text-muted)] mt-1">${t('adminDashboard.vectorStoreUpToDate')}</p>
                        </div>

                        <!-- Re-embed all (always available) -->
                        <div class="mt-6 pt-4 border-t border-[var(--border-primary)]">
                            <p class="text-sm text-[var(--text-secondary)] mb-3">
                                ${ t('adminDashboard.reembedHelp') }
                            </p>
                            <button @click="reembedAllRecordings"
                                    :disabled="isProcessingRecordings || (inquireStatus.processed_for_inquire || 0) === 0"
                                    class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded-lg shadow hover:bg-[var(--bg-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed">
                                <i :class="isProcessingRecordings ? 'fas fa-spinner fa-spin' : 'fas fa-sync-alt'" class="mr-2"></i>
                                ${ isProcessingRecordings ? t('adminDashboard.reembedding') : t('adminDashboard.reembedAll') }
                            </button>
                        </div>
                    </div>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div>

                <!-- Groups Tab -->
                <div class="tab-content" :class="{ hidden: activeTab !== 'groups' }">
                  <div class="tab-scroll">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">${ t('groups.title') }</h3>
                        <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" class="btn btn--primary">
                            <i class="fas fa-plus mr-2"></i> ${ t('groups.createTeam') }
                        </button>
                    </div>

                    <!-- Groups List -->
                    <div class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] overflow-hidden">
                        <div v-if="groups.length > 0">
                            <table class="min-w-full divide-y divide-[var(--border-primary)]">
                                <thead class="bg-[var(--bg-tertiary)]">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.groupName')}</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.description')}</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.members')}</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.created')}</th>
                                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.actions')}</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">
                                    <tr v-for="group in groups" :key="group.id" class="hover:bg-[var(--bg-tertiary)]">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm font-medium text-[var(--text-primary)]">${ group.name }</div>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="text-sm text-[var(--text-secondary)]">${ group.description || t('adminDashboard.noDescription') }</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm text-[var(--text-secondary)]">
                                                <i class="fas fa-users mr-1"></i>
                                                ${ group.member_count || 0 } ${t('adminDashboard.membersCount')}
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-muted)]">
                                            ${ parseInstant(group.created_at).toLocaleDateString(uiLocale()) }
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
                                            <button @click="openManageTeamModal(group)" class="text-[var(--text-accent)] hover:opacity-80" :title="t('tooltips.manageMembers')">
                                                <i class="fas fa-users-cog"></i>
                                            </button>
                                            <button @click="openManageTeamTagsModal(group)" class="text-purple-500 hover:text-purple-700" :title="t('tooltips.manageTeamTags')">
                                                <i class="fas fa-tags"></i>
                                            </button>
                                            <button @click="openEditTeamModal(group)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" :title="t('tooltips.editTeam')">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button v-if="!isTeamAdminOnly" @click="confirmDeleteTeam(group)" class="text-[var(--text-danger)] hover:opacity-80" :title="t('tooltips.deleteTeam')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div v-else class="p-8 text-center">
                            <i class="fas fa-users-slash text-4xl text-[var(--text-muted)] mb-3"></i>
                            <p class="text-[var(--text-muted)]" v-text="isTeamAdminOnly ? t('adminDashboard.noGroupsAdmin') : t('adminDashboard.noGroupsCreated')"></p>
                            <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" class="mt-4 px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">
                                <i class="fas fa-plus mr-2"></i> ${t('adminDashboard.createFirstGroup')}
                            </button>
                        </div>
                    </div>
                  </div><!-- /.tab-scroll -->
                  <div class="tab-footer"></div>
                </div><!-- /.tab-content (groups) -->

                </div><!-- /.tab-content-wrapper -->
            </div><!-- /inner flex shell -->
        </main>
        <!-- Standalone footer removed; the copyright now lives in each
             .tab-footer via the ::before pseudo-element driven by the
             --footer-version-text CSS variable. The hidden #footer-text
             span keeps any existing version-loading JS happy. -->
        <span id="footer-text" style="display: none;"></span>

        <!-- Add User Modal -->
        <div v-if="showAddUserModal" @click.self="showAddUserModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${t('adminDashboard.addNewUser')}</h3>
                    <button @click="showAddUserModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <form @submit.prevent="addUser" class="contents">
                    <div class="modal-body">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.usernameLabel')}</label>
                        <input v-model="newUser.username" type="text" required minlength="2" maxlength="20" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.emailLabel')}</label>
                        <input v-model="newUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.passwordLabel')}</label>
                        <input v-model="newUser.password" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.confirmPasswordLabel')}</label>
                        <input v-model="newUser.confirmPassword" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="flex items-center cursor-pointer">
                            <input v-model="newUser.isAdmin" type="checkbox" class="sr-only peer">
                            <div class="relative w-11 h-6 bg-gray-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--text-accent)]"></div>
                            <span class="ml-3 text-sm text-[var(--text-secondary)]">${t('adminDashboard.adminUser')}</span>
                        </label>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTokenBudget')}</label>
                        <input v-model.number="newUser.monthlyTokenBudget" type="number" min="100000" step="10000" :placeholder="t('adminDashboard.tokenBudgetPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.tokenBudgetHelp')}</p>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTranscriptionBudget')}</label>
                        <input v-model.number="newUser.monthlyTranscriptionBudgetMinutes" type="number" min="10" step="10" :placeholder="t('adminDashboard.transcriptionBudgetPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.transcriptionBudgetHelp')}</p>
                    </div>
                    <!-- Storage quota (#413). Left empty, the default from System Settings applies. -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.storageQuota')}</label>
                        <input v-model.number="newUser.storageQuotaMb" type="number" min="1" step="1" :placeholder="t('adminDashboard.storageQuotaNewPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.storageQuotaHelp')}</p>
                    </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" @click="showAddUserModal = false" class="btn btn--ghost">${t('buttons.cancel')}</button>
                        <button type="submit" class="btn btn--primary">${t('adminDashboard.addUser')}</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Edit User Modal -->
        <div v-if="showEditUserModal" @click.self="showEditUserModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${t('adminDashboard.editUser')}</h3>
                    <button @click="showEditUserModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <form @submit.prevent="updateUser" class="contents">
                    <div class="modal-body">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.usernameLabel')}</label>
                        <input v-model="editingUser.username" type="text" required minlength="2" maxlength="20" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.emailLabel')}</label>
                        <input v-model="editingUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.newPasswordLabel')}</label>
                        <input v-model="editingUser.password" type="password" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="flex items-center cursor-pointer">
                            <input v-model="editingUser.is_admin" type="checkbox" class="sr-only peer">
                            <div class="relative w-11 h-6 bg-gray-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--text-accent)]"></div>
                            <span class="ml-3 text-sm text-[var(--text-secondary)]">${t('adminDashboard.adminUser')}</span>
                        </label>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTokenBudget')}</label>
                        <input v-model.number="editingUser.monthly_token_budget" type="number" min="100000" step="10000" :placeholder="t('adminDashboard.tokenBudgetPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.tokenBudgetHelp')}</p>
                        <div v-if="editingUser.monthly_token_budget && editingUser.current_token_usage !== undefined" class="mt-2">
                            <div class="flex justify-between text-xs text-[var(--text-muted)] mb-1">
                                <span>${t('adminDashboard.currentUsage')}: ${ editingUser.current_token_usage?.toLocaleString(uiLocale()) || 0 } ${t('adminDashboard.tokens')}</span>
                                <span :class="{'text-[var(--text-danger-strong)]': editingUser.token_usage_percentage >= 100, 'text-[var(--text-warn-strong)]': editingUser.token_usage_percentage >= 80 && editingUser.token_usage_percentage < 100}">${ formatPercent(editingUser.token_usage_percentage || 0) }</span>
                            </div>
                            <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
                                <div class="h-2 rounded-full" :class="{'bg-[var(--text-danger-strong)]': editingUser.token_usage_percentage >= 100, 'bg-[var(--text-warn-strong)]': editingUser.token_usage_percentage >= 80 && editingUser.token_usage_percentage < 100, 'bg-[var(--text-success-strong)]': editingUser.token_usage_percentage < 80}" :style="{width: Math.min(editingUser.token_usage_percentage || 0, 100) + '%'}"></div>
                            </div>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTranscriptionBudget')}</label>
                        <input v-model.number="editingUser.monthly_transcription_budget_minutes" type="number" min="10" step="10" :placeholder="t('adminDashboard.transcriptionBudgetPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.transcriptionBudgetHelp')}</p>
                        <div v-if="editingUser.monthly_transcription_budget && editingUser.current_transcription_usage !== undefined" class="mt-2">
                            <div class="flex justify-between text-xs text-[var(--text-muted)] mb-1">
                                <span>${t('adminDashboard.currentUsageMinutes')}: ${ editingUser.current_transcription_usage_minutes || 0 } ${t('adminDashboard.minutes')}</span>
                                <span :class="{'text-[var(--text-danger-strong)]': editingUser.transcription_usage_percentage >= 100, 'text-[var(--text-warn-strong)]': editingUser.transcription_usage_percentage >= 80 && editingUser.transcription_usage_percentage < 100}">${ formatPercent(editingUser.transcription_usage_percentage || 0) }</span>
                            </div>
                            <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
                                <div class="h-2 rounded-full" :class="{'bg-[var(--text-danger-strong)]': editingUser.transcription_usage_percentage >= 100, 'bg-[var(--text-warn-strong)]': editingUser.transcription_usage_percentage >= 80 && editingUser.transcription_usage_percentage < 100, 'bg-[var(--text-success-strong)]': editingUser.transcription_usage_percentage < 80}" :style="{width: Math.min(editingUser.transcription_usage_percentage || 0, 100) + '%'}"></div>
                            </div>
                        </div>
                    </div>
                    <!-- Storage quota (#413) -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.storageQuota')}</label>
                        <input v-model.number="editingUser.storage_quota_mb" type="number" min="1" step="1" :placeholder="t('adminDashboard.storageQuotaPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                        <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.storageQuotaHelp')}</p>
                        <div class="mt-2">
                            <div class="flex justify-between text-xs text-[var(--text-muted)] mb-1">
                                <span>${t('adminDashboard.storageUsedLabel')}: ${ formatFileSize(editingUser.storage_used || 0) }</span>
                                <span v-if="editingUser.storage_quota_mb" :class="storagePctClass(storagePct(editingUser))">${ formatPercent(storagePct(editingUser)) }</span>
                            </div>
                            <div v-if="editingUser.storage_quota_mb" class="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
                                <div class="h-2 rounded-full" :class="budgetBarClass(storagePct(editingUser))" :style="{width: Math.min(storagePct(editingUser), 100) + '%'}"></div>
                            </div>
                        </div>
                    </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" @click="showEditUserModal = false" class="btn btn--ghost">${ t('buttons.cancel') }</button>
                        <button type="submit" class="btn btn--primary">${t('adminDashboard.updateUser')}</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Delete User Confirmation Modal -->
        <div v-if="showDeleteUserModal" @click.self="showDeleteUserModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${ t('adminDashboard.confirmDelete') }</h3>
                    <button @click="showDeleteUserModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">
                    <p class="text-[var(--text-secondary)]" v-text="t('adminDashboard.deleteUserConfirm', { username: userToDelete?.username })"></p>
                </div>
                <div class="modal-footer">
                    <button @click="showDeleteUserModal = false" class="btn btn--ghost">${ t('buttons.cancel') }</button>
                    <button @click="deleteUser" class="btn btn--danger">${ t('buttons.deleteUser') }</button>
                </div>
            </div>
        </div>
        
        <!-- Edit System Setting Modal -->
        <div v-if="showEditSettingModal" class="modal-overlay">
            <div class="modal-panel modal-panel--md">
                <div class="modal-header">
                    <h3 class="modal-title">${ t('adminDashboard.editSystemSetting') }</h3>
                    <button @click="showEditSettingModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>

                <div v-if="editingSetting" class="modal-body space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('adminDashboard.settingKey') }</label>
                        <div class="px-3 py-2 bg-[var(--bg-tertiary)] text-[var(--text-muted)] rounded-md font-mono text-sm">
                            ${ editingSetting.key }
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('adminDashboard.description') }</label>
                        <div class="px-3 py-2 text-[var(--text-muted)] text-sm">
                            ${ editingSetting.description || t('adminDashboard.noDescriptionAvailable') }
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('adminDashboard.settingType') }</label>
                        <span class="inline-block px-2 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded text-xs">
                            ${ editingSetting.setting_type }
                        </span>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('adminDashboard.currentValue') }</label>
                        <div class="px-3 py-2 bg-[var(--bg-tertiary)] text-[var(--text-muted)] rounded-md max-h-24 overflow-y-auto text-sm break-words">
                            <span v-if="editingSetting.key === 'transcript_length_limit' && editingSetting.value === '-1'">
                                ${t('adminDashboard.noLimit')}
                            </span>
                            <span v-else-if="editingSetting.key === 'transcript_length_limit'">
                                ${ Number(editingSetting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.characters')}
                            </span>
                            <span v-else-if="editingSetting.key === 'max_file_size_mb'">
                                ${ Number(editingSetting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.megabytes')}
                            </span>
                            <span v-else-if="editingSetting.key === 'asr_timeout_seconds'">
                                ${ Number(editingSetting.value).toLocaleString(uiLocale()) } ${t('adminDashboard.seconds')} (${ Math.round(Number(editingSetting.value) / 60) } ${t('adminDashboard.minutes')})
                            </span>
                            <span v-else>${ editingSetting.value || t('adminDashboard.notSet') }</span>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">${ t('adminDashboard.newValue') }</label>
                        
                        <!-- Boolean type -->
                        <div v-if="editingSetting.setting_type === 'boolean'" class="flex items-center space-x-4">
                            <label class="flex items-center cursor-pointer">
                                <input v-model="settingNewValue" type="radio" value="true" class="mr-2 text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
                                <span class="text-[var(--text-primary)]">${ t('webhooks.enabled') }</span>
                            </label>
                            <label class="flex items-center cursor-pointer">
                                <input v-model="settingNewValue" type="radio" value="false" class="mr-2 text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
                                <span class="text-[var(--text-primary)]">${ t('adminDashboard.disabled') }</span>
                            </label>
                        </div>
                        
                        <!-- Integer/Float type with special handling for specific keys -->
                        <div v-else-if="editingSetting.setting_type === 'integer' || editingSetting.setting_type === 'float'" class="space-y-2">
                            <!-- Special input for transcript_length_limit -->
                            <div v-if="editingSetting.key === 'transcript_length_limit'" class="space-y-2">
                                <div class="flex items-center space-x-2">
                                    <input v-model="settingUseNoLimit" type="checkbox" id="noLimit" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
                                    <label for="noLimit" class="text-sm text-[var(--text-secondary)]">${ t('adminDashboard.noLimitUseEntireTranscript') }</label>
                                </div>
                                <input v-if="!settingUseNoLimit" v-model.number="settingNewValue" type="number" min="1000" step="1000" 
                                       class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                       :placeholder="t('form.placeholderCharacterLimit')">
                                <small v-if="!settingUseNoLimit" class="text-[var(--text-muted)]">${ t('adminDashboard.transcriptLimitRecommendation') }</small>
                            </div>
                            
                            <!-- Zone picker for default_timezone (#412) -->
                            <div v-else-if="editingSetting.key === 'default_timezone'" class="space-y-2">
                                <select v-model="settingNewValue"
                                        class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                                    <option v-for="z in timezoneOptions" :key="z" :value="z">${ z.replace(/_/g, ' ') }</option>
                                </select>
                                <small class="text-[var(--text-muted)]" v-text="t('adminDashboard.defaultTimezoneHelp')"></small>
                            </div>

                            <!-- Special input for max_file_size_mb -->
                            <div v-else-if="editingSetting.key === 'max_file_size_mb'" class="space-y-2">
                                <input v-model.number="settingNewValue" type="number" min="1" max="10000" step="50"
                                       class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                       :placeholder="t('form.placeholderSizeMB')">
                                <small class="text-[var(--text-muted)]">${t('adminDashboard.maxFileSizeHelp')}</small>
                            </div>
                            
                            <!-- Special input for asr_timeout_seconds -->
                            <div v-else-if="editingSetting.key === 'asr_timeout_seconds'" class="space-y-2">
                                <div class="flex space-x-2">
                                    <div class="flex-1">
                                        <input v-model.number="settingTimeoutMinutes" type="number" min="1" max="600" step="1"
                                               class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                               :placeholder="t('form.placeholderMinutes')">
                                        <small class="text-[var(--text-muted)]">${t('adminDashboard.minutes')}</small>
                                    </div>
                                    <div class="flex-1">
                                        <input v-model.number="settingTimeoutSeconds" type="number" min="0" max="59" step="1"
                                               class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                               :placeholder="t('form.placeholderSeconds')">
                                        <small class="text-[var(--text-muted)]">${t('adminDashboard.seconds')}</small>
                                    </div>
                                </div>
                                <div class="text-sm text-[var(--text-muted)]">
                                    ${t('adminDashboard.total')}: <span class="font-medium text-[var(--text-primary)]">${ (settingTimeoutMinutes * 60 + settingTimeoutSeconds).toLocaleString(uiLocale()) } ${t('adminDashboard.seconds')}</span>
                                </div>
                                <small class="text-[var(--text-muted)]">${t('adminDashboard.timeoutRecommendation')}</small>
                            </div>
                            
                            <!-- Default number input -->
                            <input v-else v-model.number="settingNewValue" :type="editingSetting.setting_type === 'integer' ? 'number' : 'text'" 
                                   class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                   :placeholder="`Enter ${editingSetting.setting_type} value`">
                        </div>
                        
                        <!-- String type -->
                        <textarea v-else v-model="settingNewValue" rows="3"
                                  class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                  :placeholder="t('adminDashboard.enterValue')"></textarea>
                    </div>
                    
                    <div v-if="settingError" class="p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
                        ${ settingError }
                    </div>
                </div>

                <div class="modal-footer">
                    <button @click="showEditSettingModal = false"
                            class="btn btn--ghost">
                        ${ t('buttons.cancel') }
                    </button>
                    <button @click="saveSettingValue"
                            class="btn btn--primary">
                        ${t('buttons.saveChanges')}
                    </button>
                </div>
            </div>
        </div>

        <!-- Create/Edit Group Modal -->
        <div v-if="showTeamModal" @click.self="closeTeamModal" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${ editingTeam ? t('groups.editTeam') : t('groups.createTeam') }</h3>
                    <button @click="closeTeamModal" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <form @submit.prevent="saveTeam" class="contents">
                    <div class="modal-body">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('groups.teamName') } *</label>
                            <input v-model="teamForm.name" type="text" required
                                   class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                   :placeholder="t('groups.teamNamePlaceholder')">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${ t('adminDashboard.description') }</label>
                            <textarea v-model="teamForm.description" rows="3"
                                      class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                                      :placeholder="t('groups.optionalDescription')"></textarea>
                        </div>
                        <div v-if="teamError" class="p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
                            ${ teamError }
                        </div>
                    </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" @click="closeTeamModal"
                                class="btn btn--ghost">
                            ${ t('buttons.cancel') }
                        </button>
                        <button type="submit"
                                class="btn btn--primary">
                            ${ editingTeam ? t('groups.updateTeam') : t('groups.createTeam') }
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Manage Group Members Modal -->
        <div v-if="showManageTeamModal" @click.self="closeManageTeamModal" class="modal-overlay">
            <div class="modal-panel modal-panel--lg">
                <div class="modal-header">
                    <h3 class="modal-title" v-text="t('groups.manageGroupTitle', { name: currentTeam?.name })"></h3>
                    <button @click="closeManageTeamModal" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">

                <!-- Add Member Section -->
                <div class="mb-6 p-4 bg-[var(--bg-tertiary)] rounded-lg">
                    <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">${ t('groups.addMember') }</h4>
                    <div class="flex space-x-2">
                        <div class="flex-1">
                            <select v-model="newMemberUserId"
                                    class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                                <option value="">${ t('groups.selectUser') }</option>
                                <option v-for="user in availableUsers" :key="user.id" :value="user.id">
                                    ${ user.username } (${ user.email })
                                </option>
                            </select>
                        </div>
                        <div>
                            <select v-model="newMemberRole"
                                    class="px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                                <option value="member">${ t('groups.roleMember') }</option>
                                <option value="admin">${ t('groups.roleAdmin') }</option>
                            </select>
                        </div>
                        <button @click="addTeamMember" :disabled="!newMemberUserId"
                                class="btn btn--primary">
                            <i class="fas fa-plus"></i> ${ t('unifiedShareModal.add') }
                        </button>
                    </div>
                </div>

                <!-- Current Members -->
                <div>
                    <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3" v-text="t('groups.currentMembers', { count: teamMembers.length })"></h4>
                    <div v-if="teamMembers.length > 0" class="space-y-2">
                        <div v-for="member in teamMembers" :key="member.user_id"
                             class="flex items-center justify-between p-3 bg-[var(--bg-tertiary)] rounded-md">
                            <div class="flex items-center space-x-3">
                                <i class="fas fa-user text-[var(--text-muted)]"></i>
                                <div>
                                    <div class="text-sm font-medium text-[var(--text-primary)]">${ member.username }</div>
                                    <div class="text-xs text-[var(--text-muted)]">${ member.email }</div>
                                </div>
                            </div>
                            <div class="flex items-center space-x-2">
                                <select v-model="member.role" @change="updateMemberRole(member)"
                                        class="px-2 py-1 text-sm border border-[var(--border-secondary)] rounded bg-[var(--bg-input)] text-[var(--text-primary)]">
                                    <option value="member">${ t('groups.roleMember') }</option>
                                    <option value="admin">${ t('groups.roleAdmin') }</option>
                                </select>
                                <button @click="removeTeamMember(member)"
                                        class="text-[var(--text-danger)] hover:opacity-80" :title="t('groups.removeFromGroup')">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div v-else class="text-center py-4 text-[var(--text-muted)]">
                        ${t('adminDashboard.noMembersYet')}
                    </div>
                </div>

                <div v-if="teamMemberError" class="mt-4 p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
                    ${ teamMemberError }
                </div>
                </div>

                <div class="modal-footer modal-footer--between">
                    <button @click="syncTeamShares"
                            class="btn btn--primary">
                        <i class="fas fa-sync-alt"></i>
                        ${ t('groups.syncTeamShares') }
                    </button>
                    <button @click="closeManageTeamModal"
                            class="btn btn--primary">
                        ${ t('common.done') }
                    </button>
                </div>
            </div>
        </div>

        <!-- Sync Group Shares Confirmation Modal -->
        <div v-if="showSyncSharesModal" @click.self="showSyncSharesModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${ t('groups.syncTeamShares') }</h3>
                    <button @click="showSyncSharesModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">
                <p class="mb-4 text-[var(--text-secondary)]">
                    ${ t('groups.syncSharesExplain') }
                </p>
                <p class="text-[var(--text-muted)] text-sm">
                    <i class="fas fa-info-circle mr-1"></i>
                    ${ t('groups.syncSharesOnlyMissing') }
                </p>
                </div>
                <div class="modal-footer">
                    <button @click="showSyncSharesModal = false" class="btn btn--ghost">${ t('buttons.cancel') }</button>
                    <button @click="confirmSyncShares" class="btn btn--primary">
                        <i class="fas fa-sync-alt mr-2"></i>${ t('groups.syncNow') }
                    </button>
                </div>
            </div>
        </div>

        <!-- Sync Results Modal -->
        <div v-if="showSyncResultsModal" @click.self="showSyncResultsModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <i class="fas fa-check-circle text-green-500"></i>
                    <h3 class="modal-title">${ t('groups.syncCompleteTitle') }</h3>
                    <button @click="showSyncResultsModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">
                <div class="space-y-2">
                    <div class="flex justify-between text-[var(--text-secondary)]">
                        <span>${ t('groups.sharesCreated') }:</span>
                        <span class="font-semibold">${ syncResults.shares_created }</span>
                    </div>
                    <div class="flex justify-between text-[var(--text-secondary)]">
                        <span>${ t('groups.recordingsProcessed') }:</span>
                        <span class="font-semibold">${ syncResults.recordings_processed }</span>
                    </div>
                </div>
                </div>
                <div class="modal-footer">
                    <button @click="showSyncResultsModal = false" class="btn btn--primary">
                        ${ t('common.done') }
                    </button>
                </div>
            </div>
        </div>

        <!-- Delete Group Confirmation Modal -->
        <div v-if="showDeleteTeamModal" @click.self="showDeleteTeamModal = false" class="modal-overlay">
            <div class="modal-panel modal-panel--sm">
                <div class="modal-header">
                    <h3 class="modal-title">${ t('groups.deleteTeam') }</h3>
                    <button @click="showDeleteTeamModal = false" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">
                    <p class="text-[var(--text-secondary)]" v-text="t('groups.deleteGroupConfirm', { name: teamToDelete?.name })"></p>
                </div>
                <div class="modal-footer">
                    <button @click="showDeleteTeamModal = false" class="btn btn--ghost">${ t('buttons.cancel') }</button>
                    <button @click="deleteTeam" class="btn btn--danger">${ t('groups.deleteTeam') }</button>
                </div>
            </div>
        </div>

        <!-- Manage Group Tags Modal -->
        <div v-if="showManageTeamTagsModal" @click.self="closeManageTeamTagsModal" class="modal-overlay">
            <div class="modal-panel modal-panel--lg">
                <div class="modal-header">
                    <h3 class="modal-title" v-text="t('groups.manageTagsTitle', { name: currentTeam?.name })"></h3>
                    <button @click="closeManageTeamTagsModal" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>
                </div>
                <div class="modal-body">

                <!-- Create/Edit Tag Form -->
                <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg mb-4 border border-[var(--border-primary)]">
                    <div class="flex justify-between items-center mb-3">
                        <h4 class="text-sm font-medium text-[var(--text-secondary)]">
                            ${ editingTeamTagId ? t('groups.editTeamTag') : t('groups.createTeamTag') }
                        </h4>
                        <button v-if="editingTeamTagId" @click="cancelEditTeamTag" type="button" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)]">
                            <i class="fas fa-times mr-1"></i> ${ t('buttons.cancel') }
                        </button>
                    </div>
                    <form @submit.prevent="saveTeamTag" class="space-y-3">
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">${ t('editTagModal.tagName') }</label>
                                <input v-model="newTeamTag.name" type="text" required maxlength="50"
                                       class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                       :placeholder="t('groups.tagNamePlaceholder')">
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">${ t('editTagModal.color') }</label>
                                <input v-model="newTeamTag.color" type="color"
                                       class="w-full h-10 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] cursor-pointer">
                            </div>
                        </div>

                        <!-- Custom Prompt -->
                        <div>
                            <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                                ${ t('reprocessModal.customSummaryPrompt') }
                                <span class="text-[var(--text-muted)] font-normal">- ${ t('groups.optionalAiInstructions') }</span>
                            </label>
                            <textarea v-model="newTeamTag.custom_prompt" rows="3"
                                   class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                   :placeholder="t('groups.tagPromptPlaceholder')"></textarea>
                            <p class="text-xs text-[var(--text-muted)] mt-1">
                                ${ t('groups.tagPromptHelp') }
                            </p>
                        </div>
                        <!-- Title Prompt (#400) -->
                        <div>
                            <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('editTagModal.titlePrompt')"></label>
                            <textarea v-model="newTeamTag.title_prompt" rows="2"
                                   class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                   :placeholder="t('editTagModal.titlePromptPlaceholder')"></textarea>
                            <p class="text-xs text-[var(--text-muted)] mt-1" v-text="t('editTagModal.titlePromptHelp')"></p>
                        </div>

                        <!-- Transcription Settings -->
                        <div class="grid grid-cols-3 gap-3">
                            <div>
                                <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">${ t('editTagModal.defaultLanguage') }</label>
                                <select v-model="newTeamTag.default_language"
                                        class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]">
                                    <option value="">${ t('languages.autoDetect') }</option>
                                    <option value="en">${ t('languages.en') }</option>
                                    <option value="es">${ t('languages.es') }</option>
                                    <option value="fr">${ t('languages.fr') }</option>
                                    <option value="de">${ t('languages.de') }</option>
                                    <option value="zh">${ t('languages.zh') }</option>
                                    <option value="ja">${ t('languages.ja') }</option>
                                    <option value="pt">${ t('languages.pt') }</option>
                                    <option value="it">${ t('languages.it') }</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">${ t('editTagModal.minSpeakers') }</label>
                                <input v-model.number="newTeamTag.default_min_speakers" type="number" min="1" max="10"
                                       class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                       placeholder="1">
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">${ t('editTagModal.maxSpeakers') }</label>
                                <input v-model.number="newTeamTag.default_max_speakers" type="number" min="1" max="10"
                                       class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                       placeholder="5">
                            </div>
                        </div>

                        <!-- Retention and Protection -->
                        <div>
                            <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                                ${ t('groups.retentionPeriod') }
                                <span class="text-[var(--text-muted)] font-normal">- ${ t('groups.optionalRetentionOverride') }</span>
                            </label>
                            <input v-model.number="newTeamTag.retention_days" type="number" min="0" step="1"
                                   class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
                                   :placeholder="t('groups.retentionPlaceholder')">
                            <p class="text-xs text-[var(--text-muted)] mt-1" v-text="t('groups.retentionHelp', { days: globalRetentionDays })"></p>
                        </div>
                        <div class="flex items-center">
                            <input v-model="newTeamTag.protect_from_deletion" type="checkbox" id="protectFromDeletion"
                                   class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
                            <label for="protectFromDeletion" class="text-xs text-[var(--text-secondary)]">
                                <i class="fas fa-shield-alt mr-1"></i> ${ t('groups.protectTagHelp') }
                            </label>
                        </div>
                        <div class="space-y-2">
                            <div class="flex items-center">
                                <input v-model="newTeamTag.auto_share_on_apply" type="checkbox" id="autoShareOnApply"
                                       class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
                                <label for="autoShareOnApply" class="text-xs text-[var(--text-secondary)]">
                                    <i class="fas fa-user-friends mr-1"></i> ${ t('groups.autoShareTagHelp') }
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input v-model="newTeamTag.share_with_group_lead" type="checkbox" id="shareWithGroupLead"
                                       class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
                                <label for="shareWithGroupLead" class="text-xs text-[var(--text-secondary)]">
                                    <i class="fas fa-user-tie mr-1"></i> ${ t('groups.shareWithAdminsTagHelp') }
                                </label>
                            </div>
                            <p class="text-xs text-[var(--text-muted)] ml-6">
                                ${ t('groups.autoShareNote') }
                            </p>
                        </div>
                        <div v-if="teamTagError" class="text-[var(--text-danger)] text-xs">${ teamTagError }</div>
                        <button type="submit" class="btn btn--primary">
                            <i :class="editingTeamTagId ? 'fas fa-save' : 'fas fa-plus'" class="mr-1"></i>
                            ${ editingTeamTagId ? t('buttons.updateTag') : t('buttons.createTag') }
                        </button>
                    </form>
                </div>

                <!-- Existing Group Tags -->
                <div>
                    <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">${ t('groups.teamTags') }</h4>
                    <div v-if="teamTags.length > 0" class="space-y-3">
                        <div v-for="tag in teamTags" :key="tag.id"
                             class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
                            <div class="flex items-start justify-between mb-2">
                                <div class="flex items-center space-x-3 flex-1">
                                    <span class="inline-block w-4 h-4 rounded flex-shrink-0" :style="{ backgroundColor: tag.color }"></span>
                                    <div class="flex-1">
                                        <div class="text-sm font-medium text-[var(--text-primary)]">${ tag.name }</div>
                                        <div class="text-xs text-[var(--text-muted)] mt-1 space-x-3">
                                            <span v-if="tag.retention_days">
                                                <i class="fas fa-clock mr-1"></i> ${ tag.retention_days } ${ t('groups.dayRetention') }
                                            </span>
                                            <span v-else>
                                                <i class="fas fa-globe mr-1"></i> ${ t('groups.globalRetention') }
                                            </span>
                                            <span v-if="tag.protect_from_deletion" class="text-green-500">
                                                <i class="fas fa-shield-alt mr-1"></i> ${ t('groups.protected') }
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex gap-2 flex-shrink-0">
                                    <button @click="editTeamTag(tag)" class="text-[var(--text-accent)] hover:opacity-80 px-2 py-1" :title="t('buttons.editTag')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button @click="deleteTeamTag(tag)" class="text-[var(--text-danger)] hover:opacity-80 px-2 py-1" :title="t('buttons.deleteTag')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Additional details if configured -->
                            <div v-if="tag.custom_prompt || tag.default_language || tag.default_min_speakers || tag.default_max_speakers"
                                 class="mt-2 pt-2 border-t border-[var(--border-secondary)] space-y-1">
                                <div v-if="tag.custom_prompt" class="text-xs text-[var(--text-muted)]">
                                    <i class="fas fa-comment-dots mr-1"></i> ${ t('groups.customPromptConfigured') }
                                </div>
                                <div v-if="tag.default_language" class="text-xs text-[var(--text-muted)]">
                                    <i class="fas fa-language mr-1"></i> ${ t('metadata.language') }: ${ tag.default_language.toUpperCase() }
                                </div>
                                <div v-if="tag.default_min_speakers || tag.default_max_speakers" class="text-xs text-[var(--text-muted)]">
                                    <i class="fas fa-users mr-1"></i> ${ t('form.speakers') }:
                                    <span v-if="tag.default_min_speakers">${ tag.default_min_speakers }-</span><span v-if="tag.default_max_speakers">${ tag.default_max_speakers }</span><span v-else>${ t('form.auto') }</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="text-center py-8 text-[var(--text-muted)]">
                        <i class="fas fa-tags text-3xl mb-2"></i>
                        <p class="text-sm">${ t('groups.noTeamTags') }</p>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, computed, onMounted, watch, nextTick } = Vue
        
        // Initialize i18n before Vue app creation
        initializeI18n().then(() => {
            // Get the i18n instance to properly bind the t function
            const i18nInstance = window.i18n;
            
            createApp({
            setup() {
                
                // State
                const isTeamAdminOnly = ref({% if is_group_admin_only %}true{% else %}false{% endif %});
                const activeTab = ref({% if is_group_admin_only %}'teams'{% else %}'users'{% endif %});
                const users = ref([]);
                const stats = ref({
                    total_users: 0,
                    total_recordings: 0,
                    total_storage: 0,
                    ai_requests_month: 0,
                    completed_recordings: 0,
                    processing_recordings: 0,
                    transcribing_recordings: 0,
                    summarizing_recordings: 0,
                    pending_recordings: 0,
                    failed_recordings: 0,
                    audio_removed_recordings: 0,
                    archived_recordings: 0,
                    jobs: { queued: 0, running: 0, failed_7d: 0 },
                    top_users: []
                });
                const statsDays = ref(30);
                const overview = ref(null);
                const overviewLoading = ref(false);
                const statsSort = ref({ key: 'storage', dir: -1 });
                // Voice embedding compatibility (#380). Reads the stored verdict;
                // a probe costs a real transcription so it only runs on the button.
                const voiceEmbedding = ref({ status: 'unknown', supported: null, dimension: null, checked_at: null, detail: null });
                const voiceEmbeddingBusy = ref(false);
                const settings = ref([]);
                // Settings that are managed by dedicated UI panels
                // elsewhere and should not appear as raw editable cards
                // in the catch-all settings list below. Editing those
                // values here would duplicate the dedicated editor and
                // risk the two getting out of sync.
                //   - transcription_* : managed by the Transcription
                //     Models panel above.
                //   - admin_default_summary_prompt : managed by the
                //     dedicated "Default Prompts" tab, which is the
                //     authoritative editor (reset-to-default, prompt
                //     hierarchy explainer, full prompt-structure
                //     preview). Both used to write the same key, so the
                //     raw card here was a redundant second editor.
                const HIDDEN_SETTING_KEYS = new Set([
                    'transcription_models_visible_json',
                    'transcription_default_model',
                    'admin_default_summary_prompt',
                    // Managed by the dedicated "Default transcription hints"
                    // editor in the Default Prompts tab — hidden here so the
                    // raw card isn't a redundant second editor.
                    'admin_default_initial_prompt',
                    'admin_default_hotwords',
                    // Managed by the dedicated title prompt editor in the
                    // Default Prompts tab (#400).
                    'admin_default_title_prompt',
                    // Managed by the dedicated contextual-speaker-prompt editor
                    // in the Default Prompts tab.
                    'admin_default_contextual_speaker_prompt',
                    // Managed by the generation temperature editor in the
                    // Default Prompts tab (#411).
                    'llm_temperature_summary', 'llm_temperature_title',
                    'llm_temperature_chat', 'llm_temperature_event',
                ]);
                const displayedSettings = computed(() =>
                    (settings.value || []).filter(s => !HIDDEN_SETTING_KEYS.has(s.key))
                );
                // Transcription model curation state
                const visibleTranscriptionModels = ref([]); // [{value, label}, ...]
                const transcriptionDefaultModel = ref(null);
                const transcriptionDefaultModelSaved = ref(null); // For change tracking
                const modelDiscoveryResult = ref(null);
                const modelDiscoveryError = ref('');
                const discoveringModels = ref(false);
                const savingModels = ref(false);
                const modelSaveMessage = ref('');
                const modelSaveError = ref(false);
                const manualModelRows = ref([]); // for "Add custom model id" entries

                // Combined view: discovered ∪ saved ∪ manual, deduped by id.
                const transcriptionModelRows = computed(() => {
                    const map = new Map();
                    // Saved selections come first so order is stable.
                    for (const opt of visibleTranscriptionModels.value) {
                        if (opt && opt.value && !map.has(opt.value)) {
                            map.set(opt.value, {
                                value: opt.value,
                                label: opt.label || opt.value,
                                visible: true,
                                source: 'saved',
                            });
                        }
                    }
                    // Discovery additions
                    const discovered = (modelDiscoveryResult.value && modelDiscoveryResult.value.models) || [];
                    for (const m of discovered) {
                        if (!m.id) continue;
                        if (map.has(m.id)) {
                            const row = map.get(m.id);
                            if (row.source === 'saved') row.source = 'saved + discovered';
                        } else {
                            map.set(m.id, {
                                value: m.id,
                                label: m.label || m.id,
                                visible: false,
                                source: 'discovered (' + (m.owned_by || 'unknown') + ')',
                            });
                        }
                    }
                    // Manual additions
                    for (const m of manualModelRows.value) {
                        if (!m.value) continue;
                        if (!map.has(m.value)) {
                            map.set(m.value, {
                                value: m.value,
                                label: m.label || m.value,
                                visible: true,
                                source: 'manual',
                            });
                        }
                    }
                    return Array.from(map.values());
                });

                const loadVisibleTranscriptionModels = async () => {
                    try {
                        const r = await fetch('/admin/transcription/visible-models');
                        if (!r.ok) return;
                        const data = await r.json();
                        visibleTranscriptionModels.value = (data.options || []).map(o => ({
                            value: o.value,
                            label: o.label || o.value,
                        }));
                        transcriptionDefaultModel.value = data.default_model || null;
                        transcriptionDefaultModelSaved.value = data.default_model || null;
                    } catch (e) {
                        console.error('Failed to load visible transcription models:', e);
                    }
                };

                const discoverTranscriptionModels = async () => {
                    discoveringModels.value = true;
                    modelDiscoveryError.value = '';
                    try {
                        const r = await fetch('/admin/transcription/discover-models');
                        const data = await r.json();
                        if (!r.ok) {
                            modelDiscoveryError.value = data.error || t('adminDashboard.discoveryFailed');
                            modelDiscoveryResult.value = null;
                        } else {
                            modelDiscoveryResult.value = data;
                            if (data.supported && (!data.models || data.models.length === 0)) {
                                modelDiscoveryError.value = t('adminDashboard.discoveryNoModels');
                            }
                        }
                    } catch (e) {
                        modelDiscoveryError.value = t('adminDashboard.networkErrorWithMessage', { error: e.message });
                    } finally {
                        discoveringModels.value = false;
                    }
                };

                const addManualTranscriptionModel = () => {
                    const id = window.prompt(t('adminDashboard.enterModelIdPrompt'));
                    if (!id) return;
                    manualModelRows.value.push({ value: id.trim(), label: id.trim() });
                };

                const saveVisibleTranscriptionModels = async () => {
                    savingModels.value = true;
                    modelSaveMessage.value = '';
                    modelSaveError.value = false;
                    try {
                        const visible = transcriptionModelRows.value
                            .filter(r => r.visible)
                            .map(r => ({ value: r.value, label: r.label || r.value }));
                        // Drop default if it's not in the visible list anymore
                        const defaultModel = visible.some(o => o.value === transcriptionDefaultModel.value)
                            ? transcriptionDefaultModel.value
                            : null;
                        const r = await fetch('/admin/transcription/visible-models', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            },
                            body: JSON.stringify({ options: visible, default_model: defaultModel }),
                        });
                        const data = await r.json();
                        if (!r.ok) throw new Error(data.error || t('adminDashboard.saveFailed'));
                        visibleTranscriptionModels.value = data.options || [];
                        transcriptionDefaultModel.value = data.default_model || null;
                        transcriptionDefaultModelSaved.value = data.default_model || null;
                        manualModelRows.value = [];
                        modelSaveMessage.value = data.options.length === 1
                            ? t('adminDashboard.modelsSavedOne')
                            : t('adminDashboard.modelsSavedMany', { count: data.options.length });
                    } catch (e) {
                        modelSaveMessage.value = t('messages.saveParticipantsFailed', { error: e.message });
                        modelSaveError.value = true;
                    } finally {
                        savingModels.value = false;
                    }
                };

                const isLoadingUsers = ref(true);
                const isLoadingSettings = ref(false);
                const userSearchQuery = ref('');
                const isDarkMode = ref(false);
                const isUserMenuOpen = ref(false);
                
                // Modal state
                const showAddUserModal = ref(false);
                const showEditUserModal = ref(false);
                const showDeleteUserModal = ref(false);
                const newUser = ref({
                    username: '',
                    email: '',
                    password: '',
                    confirmPassword: '',
                    isAdmin: false,
                    monthlyTokenBudget: null,
                    monthlyTranscriptionBudgetMinutes: null,
                    storageQuotaMb: null
                });
                const editingUser = ref(null);
                const userToDelete = ref(null);
                
                // Inquire Mode state
                const inquireModeEnabled = ref({{ 'true' if inquire_mode_enabled else 'false' }});
                const inquireStatus = ref({
                    total_completed_recordings: 0,
                    recordings_with_transcriptions: 0,
                    processed_for_inquire: 0,
                    need_processing: 0,
                    total_chunks: 0,
                    embeddings_available: false
                });
                const isProcessingRecordings = ref(false);
                const processingResult = ref(null);

                // Teams state
                const groups = ref([]);
                const showTeamModal = ref(false);
                const showManageTeamModal = ref(false);
                const showDeleteTeamModal = ref(false);
                const showSyncSharesModal = ref(false);
                const showSyncResultsModal = ref(false);
                const syncResults = ref({ shares_created: 0, recordings_processed: 0 });
                const editingTeam = ref(null);
                const teamToDelete = ref(null);
                const currentTeam = ref(null);
                const teamForm = ref({ name: '', description: '' });
                const teamError = ref('');
                const teamMembers = ref([]);
                const newMemberUserId = ref('');
                const newMemberRole = ref('member');
                const teamMemberError = ref('');

                // Group Tags state
                const showManageTeamTagsModal = ref(false);
                const teamTags = ref([]);
                const editingTeamTagId = ref(null);
                const newTeamTag = ref({
                    name: '',
                    color: '#3B82F6',
                    custom_prompt: '',
                    title_prompt: '',
                    default_language: '',
                    default_min_speakers: null,
                    default_max_speakers: null,
                    retention_days: null,
                    protect_from_deletion: false,
                    auto_share_on_apply: true,
                    share_with_group_lead: true
                });
                const teamTagError = ref('');
                const globalRetentionDays = ref({{ global_retention_days }});

                // Default Prompts state
                const defaultSummaryPrompt = ref('');
                const isSavingPrompt = ref(false);
                const promptSaveMessage = ref('');
                const promptSaveError = ref(false);
                const showFullPromptStructure = ref(false);
                // Default transcription hints (managed in the Default Prompts tab)
                const defaultInitialPrompt = ref('');
                const defaultHotwords = ref('');
                const isSavingHints = ref(false);
                const hintsSaveMessage = ref('');
                const hintsSaveError = ref(false);
                // Contextual speaker-labelling guidance (managed in this tab)
                const contextualSpeakerPrompt = ref('');
                const defaultTitlePrompt = ref('');
                const isSavingTitlePrompt = ref(false);
                const titlePromptSaveMessage = ref('');
                const titlePromptSaveError = ref(false);
                const isSavingContextualPrompt = ref(false);
                const contextualPromptSaveMessage = ref('');
                const contextualPromptSaveError = ref(false);
                const originalDefaultPrompt = `Generate a comprehensive summary that includes the following sections:
- **Key Issues Discussed**: A bulleted list of the main topics
- **Key Decisions Made**: A bulleted list of any decisions reached
- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned`;

                {% raw %}
                // Render a prompt-preview string with placeholder chips:
                //   { var }   -> blue chip ("system-replaced", e.g. {transcript_text})
                //   {{ var }} -> amber chip ("user value at upload time")
                // HTML-escape the source first so any stray markup is rendered as text.
                const _escapeHtml = (s) => String(s).replace(/[&<>"']/g, c => ({
                    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
                }[c]));
                const formatPromptPreview = (text) => {
                    if (!text) return '';
                    return _escapeHtml(text)
                        // Amber for {{user_var}} — substituted at upload/reprocess time. Match
                        // first because it is the longer pattern; prevents single-brace pass
                        // from biting into the inner {var}.
                        .replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g,
                            '<span class="pill-status pill-status--warn font-mono" title="' + _escapeHtml(t('adminDashboard.userVariableTooltip')) + '">{{$1}}</span>')
                        // Blue for {system_var} — replaced by the framework (current_date,
                        // tag_names, transcript_text, ...). Only match identifier-shaped
                        // names so we don't mangle JSON-looking literals.
                        .replace(/\{(\s*[A-Za-z_][A-Za-z0-9_]*\s*)\}/g,
                            '<span class="pill-status pill-status--info font-mono" title="' + _escapeHtml(t('adminDashboard.systemPlaceholderTooltip')) + '">{$1}</span>');
                };
                {% endraw %}
                
                // Computed properties
                const filteredUsers = computed(() => {
                    if (!userSearchQuery.value) return users.value;

                    const query = userSearchQuery.value.toLowerCase();
                    return users.value.filter(user =>
                        user.username.toLowerCase().includes(query) ||
                        user.email.toLowerCase().includes(query)
                    );
                });

                const availableUsers = computed(() => {
                    if (!currentTeam.value) return users.value;
                    const memberUserIds = teamMembers.value.map(m => m.user_id);
                    return users.value.filter(user => !memberUserIds.includes(user.id));
                });
                
                // Methods
                const loadUsers = async () => {
                    isLoadingUsers.value = true;
                    try {
                        const response = await fetch('/admin/users');
                        if (!response.ok) throw new Error('Failed to load users');
                        
                        const data = await response.json();
                        users.value = data;
                    } catch (error) {
                        console.error('Error loading users:', error);
                        // Show error notification
                    } finally {
                        isLoadingUsers.value = false;
                    }
                };
                
                const loadVoiceEmbedding = async () => {
                    try {
                        const r = await fetch('/admin/voice-embeddings/status');
                        if (r.ok) voiceEmbedding.value = await r.json();
                    } catch (e) { /* card just keeps its last state */ }
                };
                const _voiceEmbeddingPost = async (path) => {
                    voiceEmbeddingBusy.value = true;
                    try {
                        const r = await fetch(path, {
                            method: 'POST',
                            headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content') },
                        });
                        const data = await r.json();
                        if (!r.ok) throw new Error(data.error || t('errors.requestFailed', { status: r.status }));
                        voiceEmbedding.value = data;
                    } catch (e) {
                        alert(e.message);   // how every other action on this page reports failure
                    } finally {
                        voiceEmbeddingBusy.value = false;
                    }
                };
                const checkVoiceEmbedding = () => _voiceEmbeddingPost('/admin/voice-embeddings/check');
                const rebaselineVoiceEmbedding = () => {
                    // Discards the reference the existing profiles were built
                    // against; restoring the old backend cannot undo it.
                    if (!confirm(t('adminDashboard.voiceEmbedding.rebaselineConfirm'))) return;
                    return _voiceEmbeddingPost('/admin/voice-embeddings/rebaseline');
                };

                const loadStats = async () => {
                    try {
                        const response = await fetch('/admin/stats');
                        if (!response.ok) throw new Error('Failed to load statistics');
                        
                        const data = await response.json();
                        stats.value = data;
                    } catch (error) {
                        console.error('Error loading statistics:', error);
                        // Show error notification
                    }
                };
                
                const loadSettings = async () => {
                    isLoadingSettings.value = true;
                    try {
                        const response = await fetch('/admin/settings');
                        if (response.status === 429) {
                            throw new Error('Rate limit exceeded. Please wait a moment and try again.');
                        }
                        if (!response.ok) throw new Error('Failed to load settings');

                        const data = await response.json();
                        // Sort so related settings are grouped together
                        const settingOrder = [
                            'transcript_length_limit',
                            'max_file_size_mb',
                            'max_audio_only_video_size_mb',
                            'default_storage_quota_mb',
                            'asr_timeout_seconds',
                            'default_timezone',
                            'admin_default_summary_prompt',
                            'recording_disclaimer',
                            'upload_disclaimer',
                            'custom_banner',
                            'disable_auto_summarization',
                            'enable_folders'
                        ];
                        data.sort((a, b) => {
                            const ai = settingOrder.indexOf(a.key);
                            const bi = settingOrder.indexOf(b.key);
                            // Unknown keys go to the end in original order
                            const aOrder = ai === -1 ? settingOrder.length : ai;
                            const bOrder = bi === -1 ? settingOrder.length : bi;
                            return aOrder - bOrder;
                        });
                        settings.value = data;
                    } catch (error) {
                        console.error('Error loading settings:', error);
                        // Show error notification
                    } finally {
                        isLoadingSettings.value = false;
                    }
                };

                // System Statistics: one read for a range of days, compared
                // with the range before it.
                const _t = (key, params) => i18nInstance ? i18nInstance.t(key, params) : key;
                const loadOverview = async () => {
                    overviewLoading.value = true;
                    try {
                        const response = await fetch(`/admin/stats/overview?days=${statsDays.value}`);
                        if (!response.ok) throw new Error('Failed to load statistics');
                        overview.value = await response.json();
                        await nextTick();
                        renderStatsCharts();
                    } catch (error) {
                        console.error('Error loading statistics:', error);
                    } finally {
                        overviewLoading.value = false;
                    }
                };
                const setStatsDays = (days) => {
                    if (statsDays.value === days) return;
                    statsDays.value = days;
                    loadOverview();
                };
                const refreshStats = () => { loadStats(); loadOverview(); };

                const formatCompact = (n) => {
                    n = Number(n) || 0;
                    if (n < 1000) return n.toLocaleString(window.i18n?.getIntlLocale?.());
                    return new Intl.NumberFormat(window.i18n?.getIntlLocale?.(), { notation: 'compact', maximumFractionDigits: 1 }).format(n);
                };
                const formatCost = (v) => {
                    v = Number(v) || 0;
                    if (v === 0) return '$0';
                    return '$' + (v < 1 ? v.toFixed(v < 0.01 ? 4 : 3) : v.toFixed(2));
                };
                // A model that costs nothing and runs locally reads "Local", not $0.
                const formatModelCost = (m) => {
                    const local = overview.value && (m.kind === 'embedding' ? overview.value.usage.embeddings_local : overview.value.usage.models_local);
                    return m.cost === 0 && local ? _t('adminDashboard.tokenUsage.local') : formatCost(m.cost);
                };
                const formatSeconds = (s) => {
                    s = Math.round(Number(s) || 0);
                    if (s < 60) return _t('adminDashboard.statsPage.seconds', { count: s });
                    const m = Math.floor(s / 60), r = s % 60;
                    return r ? _t('adminDashboard.statsPage.minSec', { min: m, sec: r }) : _t('adminDashboard.statsPage.minutesShort', { count: m });
                };
                const formatMinutes = (min) => {
                    min = Math.round(Number(min) || 0);
                    if (min < 60) return _t('adminDashboard.statsPage.minutesShort', { count: min });
                    return _t('adminDashboard.statsPage.hoursMinutes', { h: Math.floor(min / 60), m: min % 60 });
                };
                // "2026-10-02" read as a calendar day, not as UTC midnight.
                const formatDay = (iso) => {
                    if (!iso) return '';
                    const [y, m, d] = String(iso).slice(0, 10).split('-').map(Number);
                    return new Date(y, m - 1, d).toLocaleDateString(window.i18n?.getIntlLocale?.(), { day: 'numeric', month: 'short', year: 'numeric' });
                };
                const _change = (cur, prev) => {
                    if (!prev) return cur ? _t('adminDashboard.statsPage.newInRange') : _t('adminDashboard.statsPage.noChange');
                    const pct = Math.round((cur - prev) / prev * 100);
                    if (pct === 0) return _t('adminDashboard.statsPage.noChange');
                    return _t('adminDashboard.statsPage.vsPrevious', {
                        pct: window.i18n?.formatPercent
                            ? window.i18n.formatPercent(pct, { signDisplay: 'exceptZero' })
                            : (pct > 0 ? '+' : '') + pct + '%',
                    });
                };
                const overviewCards = computed(() => {
                    const o = overview.value && overview.value.overview;
                    if (!o) return [];
                    const costLocal = o.ai_cost.current === 0 && overview.value.usage.models_local;
                    return [
                        { key: 'recordings', icon: 'fas fa-file-audio', label: _t('adminDashboard.statsPage.recordings'),
                          value: o.recordings.current.toLocaleString(window.i18n?.getIntlLocale?.()), note: _change(o.recordings.current, o.recordings.previous) },
                        { key: 'audio', icon: 'fas fa-microphone', label: _t('adminDashboard.statsPage.audioTranscribed'),
                          value: formatMinutes(o.audio_minutes.current), note: _change(o.audio_minutes.current, o.audio_minutes.previous) },
                        { key: 'requests', icon: 'fas fa-comments', label: _t('adminDashboard.statsPage.aiRequests'),
                          value: o.ai_requests.current.toLocaleString(window.i18n?.getIntlLocale?.()), note: _change(o.ai_requests.current, o.ai_requests.previous) },
                        { key: 'cost', icon: 'fas fa-dollar-sign', label: _t('adminDashboard.statsPage.aiCost'),
                          value: costLocal ? _t('adminDashboard.tokenUsage.local') : formatCost(o.ai_cost.current),
                          note: costLocal ? '' : _change(o.ai_cost.current, o.ai_cost.previous) },
                        { key: 'users', icon: 'fas fa-users', label: _t('adminDashboard.statsPage.activeUsers'),
                          value: o.active_users.current.toLocaleString(window.i18n?.getIntlLocale?.()), note: _t('adminDashboard.statsPage.ofTotal', { total: o.active_users.total }) },
                        { key: 'storage', icon: 'fas fa-database', label: _t('adminDashboard.totalStorage'),
                          value: formatFileSize(o.storage), note: _t('adminDashboard.statsPage.allRecordings', { count: stats.value.total_recordings || 0 }) },
                    ];
                });
                const STATUS_COLORS = { completed: '#16a34a', transcribing: '#d97706', summarizing: '#ca8a04', pending: '#6366f1',
                                        failed: '#dc2626', audioRemoved: '#94a3b8', archived: '#64748b' };
                const statusRows = computed(() => [
                    { key: 'completed', label: _t('adminDashboard.completedRecordings'), value: stats.value.completed_recordings },
                    { key: 'transcribing', label: _t('adminDashboard.transcribingRecordings'), value: stats.value.transcribing_recordings },
                    { key: 'summarizing', label: _t('adminDashboard.summarizingRecordings'), value: stats.value.summarizing_recordings },
                    { key: 'pending', label: _t('adminDashboard.pendingRecordings'), value: stats.value.pending_recordings },
                    { key: 'failed', label: _t('adminDashboard.failedRecordings'), value: stats.value.failed_recordings },
                    { key: 'audioRemoved', label: _t('adminDashboard.audioRemovedRecordings'), value: stats.value.audio_removed_recordings },
                    { key: 'archived', label: _t('adminDashboard.archivedRecordings'), value: stats.value.archived_recordings },
                ].map(r => ({ ...r, color: STATUS_COLORS[r.key] })));

                const userColumns = computed(() => [
                    { key: 'username', label: _t('adminDashboard.statsPage.user') },
                    { key: 'recordings', label: _t('adminDashboard.statsPage.recordings'), align: 'right' },
                    { key: 'storage', label: _t('adminDashboard.statsPage.storage'), align: 'right' },
                    { key: 'last_recording_at', label: _t('adminDashboard.statsPage.lastRecording') },
                    { key: 'tokens_month', label: _t('adminDashboard.statsPage.tokensMonth'), align: 'right' },
                    { key: 'minutes_month', label: _t('adminDashboard.statsPage.minutesMonth'), align: 'right' },
                    { key: 'cost_month', label: _t('adminDashboard.statsPage.costMonth'), align: 'right' },
                ]);
                const sortUsersBy = (key) => {
                    statsSort.value = statsSort.value.key === key
                        ? { key, dir: -statsSort.value.dir }
                        : { key, dir: key === 'username' ? 1 : -1 };
                };
                const sortedStatsUsers = computed(() => {
                    const rows = overview.value ? [...overview.value.users] : [];
                    const { key, dir } = statsSort.value;
                    return rows.sort((a, b) => {
                        const x = a[key], y = b[key];
                        if (x == null && y == null) return 0;
                        if (x == null) return 1;
                        if (y == null) return -1;
                        return (typeof x === 'string' ? x.localeCompare(y) : x - y) * dir;
                    });
                });
                // Storage used against a quota in MB, as a percentage (#413).
                const storagePct = (u) => u && u.storage_quota_mb
                    ? Math.round((u.storage_used || 0) / (u.storage_quota_mb * 1048576) * 1000) / 10 : 0;
                const storagePctClass = (pct) => pct >= 100 ? 'text-[var(--text-danger-strong)]' : (pct >= 80 ? 'text-[var(--text-warn-strong)]' : '');
                const budgetBarClass = (pct) => pct >= 100 ? 'bg-[var(--text-danger-strong)]'
                    : (pct >= 80 ? 'bg-[var(--text-warn-strong)]' : 'bg-[var(--text-success-strong)]');

                // Charts live outside Vue's reactivity; Chart.js mutates them.
                const statsCharts = {};
                const OP_COLORS = ['79, 70, 229', '22, 163, 74', '217, 119, 6', '219, 39, 119', '8, 145, 178',
                                   '147, 51, 234', '220, 38, 38', '101, 163, 13', '100, 116, 139'];
                const _bar = (canvasId, labels, datasets, { stacked = false, legend = false, yTicks } = {}) => {
                    const ctx = document.getElementById(canvasId);
                    if (!ctx || typeof Chart === 'undefined') return;
                    if (statsCharts[canvasId]) statsCharts[canvasId].destroy();
                    const isDark = document.documentElement.classList.contains('dark');
                    const textColor = isDark ? '#9ca3af' : '#6b7280';
                    const gridColor = isDark ? '#374151' : '#e5e7eb';
                    statsCharts[canvasId] = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels,
                            datasets: datasets.map(d => ({ ...d, backgroundColor: `rgba(${d.rgb}, 0.75)`,
                                                          borderColor: `rgba(${d.rgb}, 1)`, borderWidth: 1 }))
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            locale: window.i18n?.getIntlLocale?.(),
                            plugins: {
                                legend: { display: legend, position: 'bottom', labels: { color: textColor, boxWidth: 10, boxHeight: 10 } },
                                tooltip: { mode: 'index', intersect: false,
                                           filter: (item) => !stacked || item.raw > 0,
                                           callbacks: yTicks ? { label: (c) => `${c.dataset.label}: ${yTicks(c.raw)}` } : {} }
                            },
                            scales: {
                                x: { stacked, ticks: { color: textColor, maxRotation: 0, autoSkip: true, maxTicksLimit: 8 }, grid: { display: false } },
                                y: { stacked, beginAtZero: true, grid: { color: gridColor },
                                     ticks: { color: textColor, precision: yTicks ? undefined : 0, callback: yTicks || ((v) => formatCompact(v)) } }
                            }
                        }
                    });
                };
                const _dayLabel = (iso) => {
                    const [y, m, d] = String(iso).split('-').map(Number);
                    return new Date(y, m - 1, d).toLocaleDateString(window.i18n?.getIntlLocale?.(), { month: 'short', day: 'numeric' });
                };
                const renderStatsCharts = () => {
                    const o = overview.value;
                    if (!o) return;
                    const recDays = o.activity.daily;
                    const sources = [['upload', '79, 70, 229'], ['recording', '22, 163, 74'], ['merge', '217, 119, 6'], ['other', '100, 116, 139']];
                    _bar('statsRecordingsChart', recDays.map(d => _dayLabel(d.date)),
                         sources.filter(([k]) => recDays.some(d => d[k] > 0) || k === 'upload')
                                .map(([k, rgb]) => ({ label: _t('adminDashboard.statsPage.source.' + k), data: recDays.map(d => d[k]), rgb })),
                         { stacked: true, legend: true });

                    const useDays = o.usage.daily;
                    const labels = useDays.map(d => _dayLabel(d.date));
                    _bar('statsOperationsChart', labels,
                         o.usage.operations.map((op, i) => ({
                             label: op.replace(/_/g, ' ').replace(/^./, c => c.toUpperCase()),
                             data: useDays.map(d => d.operations[op] || 0),
                             rgb: OP_COLORS[i % OP_COLORS.length] })),
                         { stacked: true, legend: true });
                    _bar('statsMinutesChart', labels,
                         [{ label: _t('adminDashboard.statsPage.minutes'), data: useDays.map(d => d.minutes), rgb: '8, 145, 178' }]);
                    _bar('statsEmbeddingChart', labels,
                         [{ label: _t('adminDashboard.statsPage.embeddingTokens'), data: useDays.map(d => d.embedding_tokens), rgb: '22, 163, 74' }]);

                    const months = o.usage.monthly;
                    const monthLabels = months.map((m, i) => {
                        const name = new Date(m.year, m.month - 1, 1).toLocaleDateString(window.i18n?.getIntlLocale?.(), { month: 'short' });
                        return i === 0 || m.month === 1 ? `${name} ${m.year}` : name;
                    });
                    _bar('statsMonthlyCostChart', monthLabels, [
                        { label: _t('adminDashboard.statsPage.kind.llm'), data: months.map(m => m.llm_cost), rgb: '79, 70, 229' },
                        { label: _t('adminDashboard.statsPage.kind.embedding'), data: months.map(m => m.embedding_cost), rgb: '22, 163, 74' },
                        { label: _t('adminDashboard.statsPage.kind.transcription'), data: months.map(m => m.transcription_cost), rgb: '8, 145, 178' },
                    ], { stacked: true, legend: true, yTicks: (v) => formatCost(v) });
                };

                const showEditSettingModal = ref(false);
                const editingSetting = ref(null);
                const settingNewValue = ref('');
                // IANA zones for the default_timezone picker (#412)
                const timezoneOptions = (() => {
                    let zones = [];
                    try { zones = Intl.supportedValuesOf('timeZone'); } catch (e) { /* older browser */ }
                    return zones.includes('UTC') ? zones : ['UTC', ...zones];
                })();
                const settingUseNoLimit = ref(false);
                const settingTimeoutMinutes = ref(30);
                const settingTimeoutSeconds = ref(0);
                const settingError = ref('');
                
                const editSetting = (setting) => {
                    editingSetting.value = { ...setting };
                    settingError.value = '';
                    
                    // Initialize form values based on setting type and key
                    if (setting.key === 'transcript_length_limit') {
                        if (setting.value === '-1') {
                            settingUseNoLimit.value = true;
                            settingNewValue.value = 30000; // Default if unchecked
                        } else {
                            settingUseNoLimit.value = false;
                            settingNewValue.value = parseInt(setting.value) || 30000;
                        }
                    } else if (setting.key === 'asr_timeout_seconds') {
                        const totalSeconds = parseInt(setting.value) || 1800;
                        settingTimeoutMinutes.value = Math.floor(totalSeconds / 60);
                        settingTimeoutSeconds.value = totalSeconds % 60;
                    } else if (setting.setting_type === 'boolean') {
                        settingNewValue.value = setting.value || 'false';
                    } else {
                        settingNewValue.value = setting.value || '';
                    }
                    
                    showEditSettingModal.value = true;
                };
                
                const saveSettingValue = async () => {
                    settingError.value = '';
                    
                    let finalValue;
                    
                    // Validate and prepare the value based on setting type
                    if (editingSetting.value.key === 'transcript_length_limit') {
                        if (settingUseNoLimit.value) {
                            finalValue = '-1';
                        } else {
                            const num = parseInt(settingNewValue.value);
                            if (isNaN(num) || num < 1000) {
                                settingError.value = t('adminDashboard.errors.minCharacters');
                                return;
                            }
                            finalValue = num.toString();
                        }
                    } else if (editingSetting.value.key === 'max_file_size_mb') {
                        const num = parseInt(settingNewValue.value);
                        if (isNaN(num) || num < 1 || num > 10000) {
                            settingError.value = t('adminDashboard.errors.invalidFileSize');
                            return;
                        }
                        finalValue = num.toString();
                    } else if (editingSetting.value.key === 'asr_timeout_seconds') {
                        const totalSeconds = (settingTimeoutMinutes.value * 60) + settingTimeoutSeconds.value;
                        if (totalSeconds < 60) {
                            settingError.value = t('adminDashboard.errors.minTimeout');
                            return;
                        }
                        if (totalSeconds > 36000) {
                            settingError.value = t('adminDashboard.errors.maxTimeout');
                            return;
                        }
                        finalValue = totalSeconds.toString();
                    } else if (editingSetting.value.setting_type === 'integer') {
                        const num = parseInt(settingNewValue.value);
                        if (isNaN(num)) {
                            settingError.value = t('adminDashboard.errors.invalidInteger');
                            return;
                        }
                        finalValue = num.toString();
                    } else if (editingSetting.value.setting_type === 'float') {
                        const num = parseFloat(settingNewValue.value);
                        if (isNaN(num)) {
                            settingError.value = t('adminDashboard.errors.invalidNumber');
                            return;
                        }
                        finalValue = num.toString();
                    } else {
                        finalValue = settingNewValue.value;
                    }
                    
                    // Save the setting
                    await updateSetting(
                        editingSetting.value.key,
                        finalValue,
                        editingSetting.value.description,
                        editingSetting.value.setting_type
                    );
                    
                    showEditSettingModal.value = false;
                };
                
                const updateSetting = async (key, value, description, settingType) => {
                    try {
                        // Get CSRF token
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        
                        const headers = {
                            'Content-Type': 'application/json'
                        };
                        
                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }
                        
                        const response = await fetch('/admin/settings', {
                            method: 'POST',
                            headers: headers,
                            body: JSON.stringify({
                                key: key,
                                value: value,
                                description: description,
                                setting_type: settingType
                            })
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.updateSettingFailed'));
                        }
                        
                        // Reload settings
                        await loadSettings();
                        
                    } catch (error) {
                        console.error('Error updating setting:', error);
                        alert(error.message);
                    }
                };
                
                // Backend INSTANT timestamps are naive UTC; append 'Z' so they're
                // read as UTC and rendered in the viewer's local timezone.
                const parseInstant = (s) => {
                    if (s == null) return new Date(NaN);
                    if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {
                        s = s.replace(' ', 'T') + 'Z';
                    }
                    return new Date(s);
                };
                const formatDate = (dateString) => {
                    if (!dateString) return t('adminDashboard.never');
                    const date = parseInstant(dateString);
                    // Guard against unparseable input so we never render the
                    // literal "Invalid Date Invalid Date".
                    if (isNaN(date.getTime())) return t('adminDashboard.never');
                    return date.toLocaleDateString(window.i18n?.getIntlLocale?.()) + ' ' + date.toLocaleTimeString(window.i18n?.getIntlLocale?.());
                };
                
                const getSettingDescription = (setting) => {
                    // Map setting keys to translation keys
                    const descriptionKeys = {
                        'transcript_length_limit': 'adminDashboard.settings.transcriptLengthLimitDesc',
                        'max_file_size_mb': 'adminDashboard.settings.maxFileSizeDesc',
                        'max_audio_only_video_size_mb': 'adminDashboard.settings.maxAudioOnlyVideoSizeDesc',
                        'asr_timeout_seconds': 'adminDashboard.settings.asrTimeoutDesc',
                        'admin_default_summary_prompt': 'adminDashboard.settings.defaultSummaryPromptDesc',
                        'recording_disclaimer': 'adminDashboard.settings.recordingDisclaimerDesc',
                        'upload_disclaimer': 'adminDashboard.settings.uploadDisclaimerDesc',
                        'custom_banner': 'adminDashboard.settings.customBannerDesc'
                    };
                    
                    const key = descriptionKeys[setting.key];
                    return key ? t(key) : setting.description || t('adminDashboard.noDescriptionAvailable');
                };
                
                const addUser = async () => {
                    if (newUser.value.password !== newUser.value.confirmPassword) {
                        alert(t('adminDashboard.passwordsDoNotMatch'));
                        return;
                    }
                    
                    try {
                        // Get CSRF token
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        
                        const headers = {
                            'Content-Type': 'application/json'
                        };
                        
                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }
                        
                        const response = await fetch('/admin/users', {
                            method: 'POST',
                            headers: headers,
                            body: JSON.stringify({
                                username: newUser.value.username,
                                email: newUser.value.email,
                                password: newUser.value.password,
                                is_admin: newUser.value.isAdmin,
                                monthly_token_budget: newUser.value.monthlyTokenBudget || null,
                                monthly_transcription_budget: newUser.value.monthlyTranscriptionBudgetMinutes ? newUser.value.monthlyTranscriptionBudgetMinutes * 60 : null,
                                // Left empty, the server applies the default for new accounts.
                                ...(newUser.value.storageQuotaMb ? { storage_quota_mb: newUser.value.storageQuotaMb } : {})
                            })
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.addUserFailed'));
                        }
                        
                        // Reset form and close modal
                        newUser.value = {
                            username: '',
                            email: '',
                            password: '',
                            confirmPassword: '',
                            isAdmin: false,
                            monthlyTokenBudget: null,
                            monthlyTranscriptionBudgetMinutes: null,
                            storageQuotaMb: null
                        };
                        showAddUserModal.value = false;
                        
                        // Reload users
                        await loadUsers();
                        await loadStats();
                        
                    } catch (error) {
                        console.error('Error adding user:', error);
                        alert(error.message);
                    }
                };
                
                const editUser = (user) => {
                    editingUser.value = { ...user, password: '' };
                    showEditUserModal.value = true;
                };
                
                const updateUser = async () => {
                    try {
                        // Convert transcription budget from minutes to seconds
                        const transcriptionBudgetSeconds = editingUser.value.monthly_transcription_budget_minutes
                            ? editingUser.value.monthly_transcription_budget_minutes * 60
                            : null;

                        const payload = {
                            username: editingUser.value.username,
                            email: editingUser.value.email,
                            is_admin: editingUser.value.is_admin,
                            monthly_token_budget: editingUser.value.monthly_token_budget || null,
                            monthly_transcription_budget: transcriptionBudgetSeconds,
                            storage_quota_mb: editingUser.value.storage_quota_mb || null
                        };

                        // Only include password if it was changed
                        if (editingUser.value.password) {
                            payload.password = editingUser.value.password;
                        }
                        
                        // Get CSRF token
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        
                        const headers = {
                            'Content-Type': 'application/json'
                        };
                        
                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }
                        
                        const response = await fetch(`/admin/users/${editingUser.value.id}`, {
                            method: 'PUT',
                            headers: headers,
                            body: JSON.stringify(payload)
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.updateUserFailed'));
                        }
                        
                        // Close modal and reload users
                        showEditUserModal.value = false;
                        await loadUsers();
                        
                    } catch (error) {
                        console.error('Error updating user:', error);
                        alert(error.message);
                    }
                };
                
                const confirmDeleteUser = (user) => {
                    userToDelete.value = user;
                    showDeleteUserModal.value = true;
                };
                
                const deleteUser = async () => {
                    try {
                        // Get CSRF token
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        
                        const headers = {};
                        
                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }
                        
                        const response = await fetch(`/admin/users/${userToDelete.value.id}`, {
                            method: 'DELETE',
                            headers: headers
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.deleteUserFailed'));
                        }
                        
                        // Close modal and reload users
                        showDeleteUserModal.value = false;
                        await loadUsers();
                        await loadStats();
                        
                    } catch (error) {
                        console.error('Error deleting user:', error);
                        alert(error.message);
                    }
                };
                
                const toggleAdminStatus = async (user) => {
                    try {
                        // Get CSRF token
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');

                        const headers = {};

                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }

                        const response = await fetch(`/admin/users/${user.id}/toggle-admin`, {
                            method: 'POST',
                            headers: headers
                        });

                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.toggleAdminFailed'));
                        }

                        // Reload users
                        await loadUsers();

                    } catch (error) {
                        console.error('Error toggling admin status:', error);
                        alert(error.message);
                    }
                };

                const togglePublicSharingPermission = async (user) => {
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };

                        if (csrfToken) {
                            headers['X-CSRFToken'] = csrfToken;
                        }

                        const response = await fetch(`/admin/users/${user.id}`, {
                            method: 'PUT',
                            headers: headers,
                            body: JSON.stringify({
                                can_share_publicly: !user.can_share_publicly
                            })
                        });

                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || t('adminDashboard.togglePublicSharingFailed'));
                        }

                        // Reload users
                        await loadUsers();

                    } catch (error) {
                        console.error('Error toggling public sharing permission:', error);
                        alert(error.message);
                    }
                };

                // Group Management Functions
                const loadGroups = async () => {
                    try {
                        const response = await fetch('/api/admin/groups');
                        if (!response.ok) throw new Error('Failed to load groups');
                        const data = await response.json();
                        groups.value = data.groups || [];
                    } catch (error) {
                        console.error('Error loading teams:', error);
                    }
                };

                const openCreateTeamModal = () => {
                    editingTeam.value = null;
                    teamForm.value = { name: '', description: '' };
                    teamError.value = '';
                    showTeamModal.value = true;
                };

                const openEditTeamModal = (group) => {
                    editingTeam.value = group;
                    teamForm.value = { name: group.name, description: group.description || '' };
                    teamError.value = '';
                    showTeamModal.value = true;
                };

                const closeTeamModal = () => {
                    showTeamModal.value = false;
                    editingTeam.value = null;
                    teamForm.value = { name: '', description: '' };
                    teamError.value = '';
                };

                const saveTeam = async () => {
                    teamError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const url = editingTeam.value
                            ? `/api/admin/groups/${editingTeam.value.id}`
                            : '/api/admin/groups';
                        const method = editingTeam.value ? 'PUT' : 'POST';

                        const response = await fetch(url, {
                            method,
                            headers,
                            body: JSON.stringify(teamForm.value)
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.saveFailed'));
                        }

                        closeTeamModal();
                        await loadGroups();
                    } catch (error) {
                        teamError.value = error.message;
                    }
                };

                const confirmDeleteTeam = (group) => {
                    teamToDelete.value = group;
                    showDeleteTeamModal.value = true;
                };

                const deleteTeam = async () => {
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = {};
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/admin/groups/${teamToDelete.value.id}`, {
                            method: 'DELETE',
                            headers
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.deleteFailed'));
                        }

                        showDeleteTeamModal.value = false;
                        teamToDelete.value = null;
                        await loadGroups();
                    } catch (error) {
                        alert(error.message);
                    }
                };

                const openManageTeamModal = async (group) => {
                    currentTeam.value = group;
                    newMemberUserId.value = '';
                    newMemberRole.value = 'member';
                    teamMemberError.value = '';
                    showManageTeamModal.value = true;
                    await loadTeamMembers(group.id);
                };

                const closeManageTeamModal = () => {
                    showManageTeamModal.value = false;
                    currentTeam.value = null;
                    teamMembers.value = [];
                    newMemberUserId.value = '';
                    newMemberRole.value = 'member';
                    teamMemberError.value = '';
                };

                const loadTeamMembers = async (groupId) => {
                    try {
                        const response = await fetch(`/api/admin/groups/${groupId}`);
                        if (!response.ok) throw new Error(t('groups.loadMembersFailed'));
                        const data = await response.json();
                        teamMembers.value = data.members || [];
                    } catch (error) {
                        console.error('Error loading group members:', error);
                        teamMemberError.value = error.message;
                    }
                };

                const addTeamMember = async () => {
                    if (!newMemberUserId.value) return;

                    teamMemberError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members`, {
                            method: 'POST',
                            headers,
                            body: JSON.stringify({
                                user_id: parseInt(newMemberUserId.value),
                                role: newMemberRole.value
                            })
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.addMemberFailed'));
                        }

                        newMemberUserId.value = '';
                        newMemberRole.value = 'member';
                        await loadTeamMembers(currentTeam.value.id);
                        await loadGroups(); // Refresh to update member count
                    } catch (error) {
                        teamMemberError.value = error.message;
                    }
                };

                const updateMemberRole = async (member) => {
                    teamMemberError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
                            method: 'PUT',
                            headers,
                            body: JSON.stringify({ role: member.role })
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.updateRoleFailed'));
                        }
                    } catch (error) {
                        teamMemberError.value = error.message;
                        await loadTeamMembers(currentTeam.value.id); // Reload to revert on error
                    }
                };

                const removeTeamMember = async (member) => {
                    if (!confirm(t('groups.removeMemberConfirm', { username: member.username }))) return;

                    teamMemberError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = {};
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
                            method: 'DELETE',
                            headers
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.removeMemberFailed'));
                        }

                        await loadTeamMembers(currentTeam.value.id);
                        await loadGroups(); // Refresh to update member count
                    } catch (error) {
                        teamMemberError.value = error.message;
                    }
                };

                const syncTeamShares = () => {
                    if (!currentTeam.value) return;
                    showSyncSharesModal.value = true;
                };

                const confirmSyncShares = async () => {
                    showSyncSharesModal.value = false;
                    teamMemberError.value = '';

                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/groups/${currentTeam.value.id}/sync-shares`, {
                            method: 'POST',
                            headers
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.syncSharesFailed'));
                        }

                        const result = await response.json();
                        syncResults.value = {
                            shares_created: result.shares_created,
                            recordings_processed: result.recordings_processed
                        };
                        showSyncResultsModal.value = true;
                    } catch (error) {
                        teamMemberError.value = error.message;
                    }
                };

                // Group Tags Management
                const openManageTeamTagsModal = async (group) => {
                    currentTeam.value = group;
                    teamTagError.value = '';
                    await loadTeamTags(group.id);
                    showManageTeamTagsModal.value = true;
                };

                const closeManageTeamTagsModal = () => {
                    showManageTeamTagsModal.value = false;
                    currentTeam.value = null;
                    teamTags.value = [];
                    editingTeamTagId.value = null;
                    newTeamTag.value = {
                        name: '',
                        color: '#3B82F6',
                        custom_prompt: '',
                        title_prompt: '',
                        default_language: '',
                        default_min_speakers: null,
                        default_max_speakers: null,
                        retention_days: null,
                        protect_from_deletion: false,
                        auto_share_on_apply: true,
                        share_with_group_lead: true
                    };
                    teamTagError.value = '';
                };

                const loadTeamTags = async (groupId) => {
                    try {
                        const response = await fetch(`/api/groups/${groupId}/tags`);
                        if (!response.ok) throw new Error(t('groups.loadTagsFailed'));
                        const data = await response.json();
                        teamTags.value = data.tags || [];
                    } catch (error) {
                        teamTagError.value = error.message;
                    }
                };

                const editTeamTag = (tag) => {
                    editingTeamTagId.value = tag.id;
                    newTeamTag.value = {
                        name: tag.name,
                        color: tag.color,
                        custom_prompt: tag.custom_prompt || '',
                        title_prompt: tag.title_prompt || '',
                        default_language: tag.default_language || '',
                        default_min_speakers: tag.default_min_speakers,
                        default_max_speakers: tag.default_max_speakers,
                        retention_days: tag.retention_days,
                        protect_from_deletion: tag.protect_from_deletion || false,
                        auto_share_on_apply: tag.auto_share_on_apply !== undefined ? tag.auto_share_on_apply : true,
                        share_with_group_lead: tag.share_with_group_lead !== undefined ? tag.share_with_group_lead : true
                    };
                    // Scroll to top of modal
                    document.querySelector('.max-h-\\[90vh\\]')?.scrollTo({ top: 0, behavior: 'smooth' });
                };

                const cancelEditTeamTag = () => {
                    editingTeamTagId.value = null;
                    newTeamTag.value = {
                        name: '',
                        color: '#3B82F6',
                        custom_prompt: '',
                        title_prompt: '',
                        default_language: '',
                        default_min_speakers: null,
                        default_max_speakers: null,
                        retention_days: null,
                        protect_from_deletion: false,
                        auto_share_on_apply: true,
                        share_with_group_lead: true
                    };
                    teamTagError.value = '';
                };

                const saveTeamTag = async () => {
                    teamTagError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = { 'Content-Type': 'application/json' };
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const payload = {
                            name: newTeamTag.value.name,
                            color: newTeamTag.value.color,
                            protect_from_deletion: newTeamTag.value.protect_from_deletion,
                            auto_share_on_apply: newTeamTag.value.auto_share_on_apply,
                            share_with_group_lead: newTeamTag.value.share_with_group_lead
                        };

                        // Add custom prompt if provided
                        if (newTeamTag.value.custom_prompt && newTeamTag.value.custom_prompt.trim()) {
                            payload.custom_prompt = newTeamTag.value.custom_prompt.trim();
                        }
                        // Title instructions are always sent so clearing the field clears them (#400)
                        payload.title_prompt = (newTeamTag.value.title_prompt || '').trim() || null;

                        // Add language if selected
                        if (newTeamTag.value.default_language) {
                            payload.default_language = newTeamTag.value.default_language;
                        }

                        // Add speaker settings if provided
                        if (newTeamTag.value.default_min_speakers) {
                            payload.default_min_speakers = newTeamTag.value.default_min_speakers;
                        }
                        if (newTeamTag.value.default_max_speakers) {
                            payload.default_max_speakers = newTeamTag.value.default_max_speakers;
                        }

                        // Only include retention_days if it's set and > 0
                        if (newTeamTag.value.retention_days && newTeamTag.value.retention_days > 0) {
                            payload.retention_days = newTeamTag.value.retention_days;
                        }

                        let response;
                        if (editingTeamTagId.value) {
                            // Update existing tag
                            response = await fetch(`/api/tags/${editingTeamTagId.value}`, {
                                method: 'PUT',
                                headers,
                                body: JSON.stringify(payload)
                            });
                        } else {
                            // Create new tag
                            response = await fetch(`/api/groups/${currentTeam.value.id}/tags`, {
                                method: 'POST',
                                headers,
                                body: JSON.stringify(payload)
                            });
                        }

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || (editingTeamTagId.value ? t('groups.updateTagFailed') : t('groups.createTagFailed')));
                        }

                        // Reset form and reload
                        editingTeamTagId.value = null;
                        newTeamTag.value = {
                            name: '',
                            color: '#3B82F6',
                            custom_prompt: '',
                            title_prompt: '',
                            default_language: '',
                            default_min_speakers: null,
                            default_max_speakers: null,
                            retention_days: null,
                            protect_from_deletion: false,
                            auto_share_on_apply: true,
                            share_with_group_lead: true
                        };
                        await loadTeamTags(currentTeam.value.id);
                    } catch (error) {
                        teamTagError.value = error.message;
                    }
                };

                const deleteTeamTag = async (tag) => {
                    if (!confirm(t('groups.deleteTagConfirm', { name: tag.name }))) return;

                    teamTagError.value = '';
                    try {
                        const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                        const headers = {};
                        if (csrfToken) headers['X-CSRFToken'] = csrfToken;

                        const response = await fetch(`/api/tags/${tag.id}`, {
                            method: 'DELETE',
                            headers
                        });

                        if (!response.ok) {
                            const error = await response.json();
                            throw new Error(error.error || t('groups.deleteTagFailed'));
                        }

                        await loadTeamTags(currentTeam.value.id);
                    } catch (error) {
                        teamTagError.value = error.message;
                    }
                };

                // Localized number and units (#481)
                // Without i18n.js (not loaded yet) the page still shows a size.
                const formatFileSize = (bytes) => (window.i18n?.formatFileSize ? window.i18n.formatFileSize(bytes) : `${Number(bytes) || 0} bytes`);
                const formatPercent = (pct, options) => (window.i18n?.formatPercent ? window.i18n.formatPercent(pct, options) : `${Math.round((Number(pct) || 0) * 10) / 10}%`);
                const formatNumber = (n, options) => (window.i18n?.formatNumber ? window.i18n.formatNumber(n, options) : String(n));
                
                const toggleDarkMode = () => {
                    isDarkMode.value = !isDarkMode.value;
                    if (isDarkMode.value) {
                        document.documentElement.classList.add('dark');
                        localStorage.setItem('darkMode', 'true');
                    } else {
                        document.documentElement.classList.remove('dark');
                        localStorage.setItem('darkMode', 'false');
                    }
                    if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
                };
                
                // Initialize dark mode
                const initializeDarkMode = () => {
                    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                    const savedMode = localStorage.getItem('darkMode');

                    if (savedMode === 'true' || (savedMode === null && prefersDark)) {
                        isDarkMode.value = true;
                        document.documentElement.classList.add('dark');
                    } else {
                        isDarkMode.value = false;
                        document.documentElement.classList.remove('dark');
                    }
                };

                /**
                 * Set up global click handler to close dropdowns when clicking outside
                 * Provides elegant UX by closing menus when users click elsewhere
                 */
                const setupGlobalClickHandler = () => {
                    document.addEventListener('click', (event) => {
                        const target = event.target;

                        // Close user menu if clicking outside of it
                        if (isUserMenuOpen.value) {
                            const userMenuButton = target.closest('[data-user-menu-toggle]');
                            const userMenuDropdown = target.closest('[data-user-menu-dropdown]');

                            if (!userMenuButton && !userMenuDropdown) {
                                isUserMenuOpen.value = false;
                            }
                        }
                    });
                };

                // Inquire Mode methods
                // Default Prompts methods
                const loadDefaultPrompt = async () => {
                    try {
                        // Use already loaded settings if available, otherwise load them
                        let settingsData = settings.value;
                        
                        if (!settingsData || settingsData.length === 0) {
                            const response = await fetch('/admin/settings');
                            if (response.status === 429) {
                                throw new Error('Rate limit exceeded. Please wait a moment and try again.');
                            }
                            if (!response.ok) throw new Error('Failed to load settings');
                            settingsData = await response.json();
                            settings.value = settingsData;
                        }
                        
                        const promptSetting = settingsData.find(s => s.key === 'admin_default_summary_prompt');
                        if (promptSetting) {
                            defaultSummaryPrompt.value = promptSetting.value || '';
                        }

                        // Default transcription hints share this tab.
                        const ipSetting = settingsData.find(s => s.key === 'admin_default_initial_prompt');
                        defaultInitialPrompt.value = ipSetting ? (ipSetting.value || '') : '';
                        const hwSetting = settingsData.find(s => s.key === 'admin_default_hotwords');
                        defaultHotwords.value = hwSetting ? (hwSetting.value || '') : '';
                        const cspSetting = settingsData.find(s => s.key === 'admin_default_contextual_speaker_prompt');
                        contextualSpeakerPrompt.value = cspSetting ? (cspSetting.value || '') : '';
                        const titleSetting = settingsData.find(s => s.key === 'admin_default_title_prompt');
                        defaultTitlePrompt.value = titleSetting ? (titleSetting.value || '') : '';
                        loadTemperatures();
                    } catch (error) {
                        console.error('Error loading default prompt:', error);
                        promptSaveMessage.value = t('adminDashboard.errors.failedToLoadPrompt');
                        promptSaveError.value = true;
                    }
                };

                const saveDefaultHints = async () => {
                    isSavingHints.value = true;
                    hintsSaveMessage.value = '';
                    hintsSaveError.value = false;

                    const csrf = document.querySelector('meta[name="csrf-token"]').content;
                    const putSetting = async (key, value, description) => {
                        const response = await fetch('/admin/settings', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf },
                            body: JSON.stringify({ key, value, description, setting_type: 'string' })
                        });
                        if (!response.ok) throw new Error('Failed to save ' + key);
                    };

                    try {
                        await putSetting(
                            'admin_default_initial_prompt',
                            defaultInitialPrompt.value,
                            'Global initial prompt injected into all transcription requests. Applied when users have not set their own initial prompt.'
                        );
                        await putSetting(
                            'admin_default_hotwords',
                            defaultHotwords.value,
                            'Global hotwords injected into all transcription requests. Comma-separated. Applied when users have not set their own hotwords.'
                        );

                        // Keep the cached settings list in sync so the hidden
                        // raw cards don't show stale values if revisited.
                        const sync = (key, value) => {
                            const row = (settings.value || []).find(s => s.key === key);
                            if (row) row.value = value;
                        };
                        sync('admin_default_initial_prompt', defaultInitialPrompt.value);
                        sync('admin_default_hotwords', defaultHotwords.value);

                        hintsSaveMessage.value = t('adminDashboard.promptSavedSuccessfully');
                        hintsSaveError.value = false;
                        setTimeout(() => { hintsSaveMessage.value = ''; }, 3000);
                    } catch (error) {
                        console.error('Error saving default hints:', error);
                        hintsSaveMessage.value = t('adminDashboard.errors.failedToSavePrompt');
                        hintsSaveError.value = true;
                    } finally {
                        isSavingHints.value = false;
                    }
                };
                
                const saveDefaultPrompt = async () => {
                    isSavingPrompt.value = true;
                    promptSaveMessage.value = '';
                    promptSaveError.value = false;
                    
                    try {
                        const response = await fetch('/admin/settings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify({
                                key: 'admin_default_summary_prompt',
                                value: defaultSummaryPrompt.value,
                                description: 'Default summarization prompt used when users have not set their own prompt. This serves as the base prompt for all users.',
                                setting_type: 'string'
                            })
                        });
                        
                        if (!response.ok) throw new Error('Failed to save prompt');
                        
                        promptSaveMessage.value = t('adminDashboard.promptSavedSuccessfully');
                        promptSaveError.value = false;
                        
                        // Clear message after 3 seconds
                        setTimeout(() => {
                            promptSaveMessage.value = '';
                        }, 3000);
                    } catch (error) {
                        console.error('Error saving default prompt:', error);
                        promptSaveMessage.value = t('adminDashboard.errors.failedToSavePrompt');
                        promptSaveError.value = true;
                    } finally {
                        isSavingPrompt.value = false;
                    }
                };
                
                const resetDefaultPrompt = () => {
                    defaultSummaryPrompt.value = originalDefaultPrompt;
                    promptSaveMessage.value = t('adminDashboard.promptResetMessage');
                    promptSaveError.value = false;
                };

                // ---- Generation temperatures (#411) ----
                const temperatureKinds = ['summary', 'title', 'chat', 'event'];
                const temperatureStatus = ref({});
                const temperatureInputs = ref({ summary: '', title: '', chat: '', event: '' });
                const isSavingTemperatures = ref(false);
                const temperatureSaveMessage = ref('');
                const temperatureSaveError = ref(false);

                const applyTemperatureStatus = (status) => {
                    temperatureStatus.value = status || {};
                    const inputs = {};
                    temperatureKinds.forEach(kind => {
                        const st = temperatureStatus.value[kind];
                        inputs[kind] = st && st.source === 'admin' ? String(st.value) : '';
                    });
                    temperatureInputs.value = inputs;
                };

                const loadTemperatures = async () => {
                    try {
                        const response = await fetch('/admin/llm-temperatures');
                        if (!response.ok) return;
                        const data = await response.json();
                        applyTemperatureStatus(data.temperatures);
                    } catch (error) {
                        console.error('Error loading temperatures:', error);
                    }
                };

                const temperatureSourceText = (kind) => {
                    const st = temperatureStatus.value[kind];
                    if (!st) return '';
                    const key = 'adminDashboard.temperatures.source' + st.source.charAt(0).toUpperCase() + st.source.slice(1);
                    return t(key, { value: st.value, default: st.default });
                };

                const postTemperatures = async (values) => {
                    isSavingTemperatures.value = true;
                    temperatureSaveMessage.value = '';
                    temperatureSaveError.value = false;
                    try {
                        const response = await fetch('/admin/llm-temperatures', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify({ values })
                        });
                        const data = await response.json().catch(() => ({}));
                        if (!response.ok) throw new Error(data.error || 'save failed');
                        applyTemperatureStatus(data.temperatures);
                        temperatureSaveMessage.value = t('adminDashboard.temperatures.saved');
                        setTimeout(() => { temperatureSaveMessage.value = ''; }, 3000);
                    } catch (error) {
                        console.error('Error saving temperatures:', error);
                        temperatureSaveMessage.value = t('adminDashboard.temperatures.invalid');
                        temperatureSaveError.value = true;
                    } finally {
                        isSavingTemperatures.value = false;
                    }
                };

                const saveTemperatures = () => {
                    const values = {};
                    temperatureKinds.forEach(kind => {
                        const raw = temperatureInputs.value[kind];
                        values[kind] = raw === '' || raw === null || raw === undefined ? null : raw;
                    });
                    return postTemperatures(values);
                };

                const resetTemperature = (kind) => {
                    const values = {};
                    values[kind] = null;
                    return postTemperatures(values);
                };

                const saveDefaultTitlePrompt = async () => {
                    isSavingTitlePrompt.value = true;
                    titlePromptSaveMessage.value = '';
                    titlePromptSaveError.value = false;
                    try {
                        const response = await fetch('/admin/settings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify({
                                key: 'admin_default_title_prompt',
                                value: defaultTitlePrompt.value,
                                description: 'Default instructions for AI-generated recording titles, used when no tag, folder or user title prompt is set.',
                                setting_type: 'string'
                            })
                        });
                        if (!response.ok) throw new Error('Failed to save prompt');
                        const row = (settings.value || []).find(s => s.key === 'admin_default_title_prompt');
                        if (row) row.value = defaultTitlePrompt.value;
                        titlePromptSaveMessage.value = t('adminDashboard.promptSavedSuccessfully');
                        titlePromptSaveError.value = false;
                        setTimeout(() => { titlePromptSaveMessage.value = ''; }, 3000);
                    } catch (error) {
                        console.error('Error saving default title prompt:', error);
                        titlePromptSaveMessage.value = t('adminDashboard.errors.failedToSavePrompt');
                        titlePromptSaveError.value = true;
                    } finally {
                        isSavingTitlePrompt.value = false;
                    }
                };

                const saveContextualSpeakerPrompt = async () => {
                    isSavingContextualPrompt.value = true;
                    contextualPromptSaveMessage.value = '';
                    contextualPromptSaveError.value = false;
                    try {
                        const response = await fetch('/admin/settings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify({
                                key: 'admin_default_contextual_speaker_prompt',
                                value: contextualSpeakerPrompt.value,
                                description: 'Guidance for contextual speaker labelling (used when a recording has no voice embeddings). Only the guidance is editable; the candidate list and JSON format are fixed in code. Leave blank to use the built-in default.',
                                setting_type: 'string'
                            })
                        });
                        if (!response.ok) throw new Error('Failed to save prompt');
                        // Keep the cached settings row in sync.
                        const row = (settings.value || []).find(s => s.key === 'admin_default_contextual_speaker_prompt');
                        if (row) row.value = contextualSpeakerPrompt.value;
                        contextualPromptSaveMessage.value = t('adminDashboard.promptSavedSuccessfully');
                        contextualPromptSaveError.value = false;
                        setTimeout(() => { contextualPromptSaveMessage.value = ''; }, 3000);
                    } catch (error) {
                        console.error('Error saving contextual speaker prompt:', error);
                        contextualPromptSaveMessage.value = t('adminDashboard.errors.failedToSavePrompt');
                        contextualPromptSaveError.value = true;
                    } finally {
                        isSavingContextualPrompt.value = false;
                    }
                };
                
                const loadInquireStatus = async () => {
                    try {
                        const response = await fetch('/admin/inquire/status');
                        if (!response.ok) throw new Error('Failed to load inquire status');
                        
                        const data = await response.json();
                        inquireStatus.value = data;
                    } catch (error) {
                        console.error('Error loading inquire status:', error);
                    }
                };
                
                const processAllRecordings = async () => {
                    if (isProcessingRecordings.value) return;
                    
                    isProcessingRecordings.value = true;
                    processingResult.value = null;
                    
                    try {
                        const response = await fetch('/admin/inquire/process-recordings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({})
                        });
                        
                        if (!response.ok) throw new Error('Failed to process recordings');
                        
                        const data = await response.json();
                        processingResult.value = data;
                        
                        // Reload status after processing
                        await loadInquireStatus();
                    } catch (error) {
                        console.error('Error processing recordings:', error);
                        processingResult.value = {
                            success: false,
                            message: t('adminDashboard.processRecordingsFailed')
                        };
                    } finally {
                        isProcessingRecordings.value = false;
                    }
                };
                
                const reembedAllRecordings = async () => {
                    if (isProcessingRecordings.value) return;
                    if (!confirm(t('adminDashboard.reembedConfirm'))) {
                        return;
                    }
                    isProcessingRecordings.value = true;
                    processingResult.value = null;
                    try {
                        const response = await fetch('/admin/inquire/process-recordings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({ force: true })
                        });
                        if (!response.ok) throw new Error('Failed to re-embed recordings');
                        const data = await response.json();
                        processingResult.value = data;
                        await loadInquireStatus();
                    } catch (error) {
                        console.error('Error re-embedding:', error);
                        processingResult.value = { success: false, message: t('adminDashboard.reembedFailed') };
                    } finally {
                        isProcessingRecordings.value = false;
                    }
                };

                const processBatchRecordings = async (batchSize) => {
                    if (isProcessingRecordings.value) return;
                    
                    isProcessingRecordings.value = true;
                    processingResult.value = null;
                    
                    try {
                        const response = await fetch('/admin/inquire/process-recordings', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({ max_recordings: batchSize })
                        });
                        
                        if (!response.ok) throw new Error('Failed to process recordings');
                        
                        const data = await response.json();
                        processingResult.value = data;
                        
                        // Reload status after processing
                        await loadInquireStatus();
                    } catch (error) {
                        console.error('Error processing recordings:', error);
                        processingResult.value = {
                            success: false,
                            message: t('adminDashboard.processRecordingsFailed')
                        };
                    } finally {
                        isProcessingRecordings.value = false;
                    }
                };
                
                const getProcessingProgress = () => {
                    const total = (inquireStatus.value.processed_for_inquire || 0) + (inquireStatus.value.need_processing || 0);
                    if (total === 0) return 100;
                    return Math.round((inquireStatus.value.processed_for_inquire / total) * 100);
                };

                // Built outside the template so the inline ${...} interpolation
                // does not have to contain a JS object literal. Vue's custom
                // ${...} delimiter does not track nested braces, so embedding
                // `{ count: ... }` inside the interpolation breaks compilation.
                const recordingsNeedProcessingMessage = computed(() =>
                    t('adminDashboard.recordingsNeedProcessing', {
                        count: inquireStatus.value.need_processing || 0,
                    })
                );
                
                // Lifecycle hooks - MUST be registered before any await statements
                onMounted(async () => {
                    // Only load admin-specific data if user is full admin
                    if (!isTeamAdminOnly.value) {
                        loadUsers();
                        loadStats();
                        loadVoiceEmbedding();
                        loadOverview();

                        // Load settings first, then default prompt can use that data
                        if (activeTab.value === 'settings' || activeTab.value === 'prompts') {
                            await loadSettings();
                        }
                        loadDefaultPrompt();
                        loadVisibleTranscriptionModels();

                        if (inquireModeEnabled.value) {
                            loadInquireStatus();
                        }
                    } else {
                        // Group admins only need users list (for adding members) and groups
                        loadUsers();
                        loadGroups();
                    }

                    initializeDarkMode();
                    setupGlobalClickHandler();

                    // Setup scroll indicators for tabs
                    const tabsContainer = document.getElementById('admin-tabs-container');
                    const leftIndicator = document.getElementById('admin-left-scroll-indicator');
                    const rightIndicator = document.getElementById('admin-right-scroll-indicator');

                    function updateScrollIndicators() {
                        if (tabsContainer && leftIndicator && rightIndicator) {
                            const scrollLeft = tabsContainer.scrollLeft;
                            const scrollWidth = tabsContainer.scrollWidth;
                            const clientWidth = tabsContainer.clientWidth;

                            // Show/hide left indicator
                            if (scrollLeft > 10) {
                                leftIndicator.classList.remove('opacity-0');
                                leftIndicator.classList.add('opacity-100');
                            } else {
                                leftIndicator.classList.remove('opacity-100');
                                leftIndicator.classList.add('opacity-0');
                            }

                            // Show/hide right indicator
                            if (scrollWidth - scrollLeft - clientWidth > 10) {
                                rightIndicator.classList.remove('opacity-0');
                                rightIndicator.classList.add('opacity-100');
                            } else {
                                rightIndicator.classList.remove('opacity-100');
                                rightIndicator.classList.add('opacity-0');
                            }
                        }
                    }

                    if (tabsContainer) {
                        tabsContainer.addEventListener('scroll', updateScrollIndicators);
                        window.addEventListener('resize', updateScrollIndicators);
                        // Initial check
                        updateScrollIndicators();
                        setTimeout(updateScrollIndicators, 100);
                        setTimeout(updateScrollIndicators, 500);
                    }
                });
                
                // Watch for tab changes to reload data
                watch(activeTab, async (newTab) => {
                    // Only allow full admins to load admin-specific data
                    if (!isTeamAdminOnly.value) {
                        if (newTab === 'users') {
                            loadUsers();
                        } else if (newTab === 'stats') {
                            loadStats();
                            loadOverview();
                        } else if (newTab === 'settings') {
                            await loadSettings();
                        } else if (newTab === 'prompts') {
                            // If settings aren't loaded, load them first
                            if (!settings.value || settings.value.length === 0) {
                                await loadSettings();
                            }
                            loadDefaultPrompt();
                        } else if (newTab === 'vectorstore' && inquireModeEnabled.value) {
                            loadInquireStatus();
                        }
                    }

                    // Both full admins and group admins can access teams
                    if (newTab === 'groups') {
                        loadGroups();
                        loadUsers(); // Load users for member selection
                    }
                });
                
                return {
                    // i18n - bind to i18n instance to maintain context
                    t: (key, params) => i18nInstance ? i18nInstance.t(key, params) : key,
                    // The interface locale for toLocale*String calls in the template (#480)
                    uiLocale: () => window.i18n?.getIntlLocale?.(),

                    // State
                    isTeamAdminOnly,
                    activeTab,
                    users,
                    stats,
                    voiceEmbedding, voiceEmbeddingBusy, checkVoiceEmbedding, rebaselineVoiceEmbedding,
                    statsDays, overview, overviewLoading, overviewCards, statusRows,
                    userColumns, statsSort, sortUsersBy, sortedStatsUsers, budgetBarClass, storagePct, storagePctClass,
                    formatCompact, formatCost, formatModelCost, formatSeconds, formatDay,
                    settings,
                    displayedSettings,
                    isLoadingUsers,
                    isLoadingSettings,
                    userSearchQuery,
                    isDarkMode,
                    isUserMenuOpen,
                    
                    // Modal state
                    showAddUserModal,
                    showEditUserModal,
                    showDeleteUserModal,
                    newUser,
                    editingUser,
                    userToDelete,
                    
                    // Settings modal state
                    showEditSettingModal,
                    editingSetting,
                    settingNewValue,
                    timezoneOptions,
                    settingUseNoLimit,
                    settingTimeoutMinutes,
                    settingTimeoutSeconds,
                    settingError,
                    
                    // Inquire Mode state
                    inquireModeEnabled,
                    inquireStatus,
                    isProcessingRecordings,
                    processingResult,

                    // Teams state
                    groups,
                    showTeamModal,
                    showManageTeamModal,
                    showDeleteTeamModal,
                    showSyncSharesModal,
                    showSyncResultsModal,
                    syncResults,
                    editingTeam,
                    teamToDelete,
                    currentTeam,
                    teamForm,
                    teamError,
                    teamMembers,
                    newMemberUserId,
                    newMemberRole,
                    teamMemberError,

                    // Group Tags state
                    showManageTeamTagsModal,
                    teamTags,
                    editingTeamTagId,
                    newTeamTag,
                    teamTagError,
                    globalRetentionDays,

                    // Default Prompts state
                    defaultSummaryPrompt,
                    isSavingPrompt,
                    promptSaveMessage,
                    promptSaveError,
                    showFullPromptStructure,
                    originalDefaultPrompt,
                    formatPromptPreview,
                    defaultInitialPrompt,
                    defaultHotwords,
                    isSavingHints,
                    hintsSaveMessage,
                    hintsSaveError,
                    contextualSpeakerPrompt,
                    defaultTitlePrompt, isSavingTitlePrompt, titlePromptSaveMessage, titlePromptSaveError,
                    temperatureKinds, temperatureStatus, temperatureInputs, isSavingTemperatures, temperatureSaveMessage, temperatureSaveError,
                    temperatureSourceText, saveTemperatures, resetTemperature,
                    isSavingContextualPrompt,
                    contextualPromptSaveMessage,
                    contextualPromptSaveError,

                    // Computed
                    filteredUsers,
                    availableUsers,
                    getProcessingProgress,
                    recordingsNeedProcessingMessage,

                    // Methods
                    loadUsers,
                    loadStats,
                    loadSettings,
                    loadOverview, setStatsDays, refreshStats,
                    editSetting,
                    saveSettingValue,
                    updateSetting,
                    formatDate,
                    parseInstant,
                    getSettingDescription,
                    addUser,
                    editUser,
                    updateUser,
                    confirmDeleteUser,
                    deleteUser,
                    toggleAdminStatus,
                    togglePublicSharingPermission,
                    formatFileSize,
                    formatPercent,
                    formatNumber,
                    toggleDarkMode,

                    // Group Management methods
                    loadGroups,
                    openCreateTeamModal,
                    openEditTeamModal,
                    closeTeamModal,
                    saveTeam,
                    confirmDeleteTeam,
                    deleteTeam,
                    openManageTeamModal,
                    closeManageTeamModal,
                    loadTeamMembers,
                    addTeamMember,
                    updateMemberRole,
                    removeTeamMember,
                    syncTeamShares,
                    confirmSyncShares,

                    // Group Tags methods
                    openManageTeamTagsModal,
                    closeManageTeamTagsModal,
                    loadTeamTags,
                    saveTeamTag,
                    editTeamTag,
                    cancelEditTeamTag,
                    deleteTeamTag,

                    // Inquire Mode methods
                    loadInquireStatus,
                    processAllRecordings,
                    processBatchRecordings,
                    reembedAllRecordings,

                    // Transcription model curation
                    visibleTranscriptionModels,
                    transcriptionDefaultModel,
                    modelDiscoveryResult,
                    modelDiscoveryError,
                    discoveringModels,
                    savingModels,
                    modelSaveMessage,
                    modelSaveError,
                    transcriptionModelRows,
                    discoverTranscriptionModels,
                    addManualTranscriptionModel,
                    saveVisibleTranscriptionModels,
                    loadVisibleTranscriptionModels,

                    // Default Prompts methods
                    loadDefaultPrompt,
                    saveDefaultPrompt,
                    resetDefaultPrompt,
                    saveDefaultHints,
                    saveContextualSpeakerPrompt,
                    saveDefaultTitlePrompt
                };
            },
            delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2
        }).mount('#app');

        // Hide loading overlay after Vue is mounted
        Vue.nextTick(() => {
            if (window.AppLoader) {
                window.AppLoader.hide();
            }
        });
        }); // End of initializeI18n().then()
    </script>
</body>
</html>