{% extends "base.html" %}

{% block title %}Global Settings - Cuti{% endblock %}

{% block head %}
<style>
    /* Global Settings Page Specific Styles */
    .settings-wrapper {
        padding: 2rem;
        max-width: 1400px;
        margin: 0 auto;
    }
    
    .settings-header {
        text-align: center;
        margin-bottom: 3rem;
        padding: 2rem 0;
    }
    
    .settings-header h1 {
        font-size: 2.5rem;
        font-weight: 700;
        background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin-bottom: 0.5rem;
    }
    
    .settings-header p {
        color: var(--text-secondary);
        font-size: 1.1rem;
        max-width: 600px;
        margin: 0 auto;
    }
    
    /* Cards Grid */
    .settings-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
        gap: 2rem;
        margin-bottom: 3rem;
    }
    
    /* Card Styles using existing variables */
    .settings-card {
        background: var(--bg-card);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        padding: 2rem;
        transition: all var(--transition-base);
    }
    
    .settings-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
        border-color: var(--primary);
    }
    
    .card-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid var(--border);
    }
    
    /* Form Elements */
    .form-group {
        margin-bottom: 1.5rem;
    }
    
    .form-label {
        display: block;
        color: var(--text-primary);
        font-weight: 500;
        margin-bottom: 0.5rem;
        font-size: 0.9rem;
    }
    
    .form-description {
        color: var(--text-muted);
        font-size: 0.8rem;
        margin-bottom: 0.75rem;
    }
    
    .form-input,
    .form-select,
    .form-textarea {
        width: 100%;
        padding: 0.75rem 1rem;
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        color: var(--text-primary);
        font-size: 0.9rem;
        transition: all var(--transition-fast);
    }
    
    .form-input:focus,
    .form-select:focus,
    .form-textarea:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
    }
    
    .form-textarea {
        min-height: 120px;
        resize: vertical;
    }
    
    /* Toggle Container */
    .toggle-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1rem;
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        margin-bottom: 1rem;
        transition: all var(--transition-fast);
    }
    
    .toggle-container:hover {
        border-color: var(--primary);
    }
    
    .toggle-info {
        flex: 1;
    }
    
    .toggle-title {
        color: var(--text-primary);
        font-weight: 500;
        margin-bottom: 0.25rem;
    }
    
    .toggle-desc {
        color: var(--text-muted);
        font-size: 0.8rem;
    }
    
    .toggle-switch {
        position: relative;
        width: 48px;
        height: 24px;
        background: var(--border);
        border-radius: 24px;
        cursor: pointer;
        transition: all var(--transition-fast);
    }
    
    .toggle-switch input {
        display: none;
    }
    
    .toggle-switch.active {
        background: var(--primary);
    }
    
    .toggle-switch::after {
        content: '';
        position: absolute;
        top: 2px;
        left: 2px;
        width: 20px;
        height: 20px;
        background: white;
        border-radius: 50%;
        transition: all var(--transition-fast);
    }
    
    .toggle-switch.active::after {
        transform: translateX(24px);
    }
    
    /* Stats Cards */
    .stats-card {
        background: var(--bg-card);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        padding: 2rem;
        margin-bottom: 2rem;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .stat-item {
        background: var(--bg-secondary);
        border-radius: var(--radius-md);
        padding: 1.5rem;
        text-align: center;
    }
    
    .stat-label {
        color: var(--text-muted);
        font-size: 0.8rem;
        margin-bottom: 0.5rem;
    }
    
    .stat-value {
        color: var(--text-primary);
        font-size: 2rem;
        font-weight: 700;
    }
    
    /* Action Buttons */
    .actions {
        display: flex;
        gap: 1rem;
        flex-wrap: wrap;
        justify-content: center;
        margin-top: 2rem;
    }
    
    .btn {
        padding: 0.75rem 1.5rem;
        border: none;
        border-radius: var(--radius-sm);
        font-weight: 500;
        cursor: pointer;
        transition: all var(--transition-fast);
        font-size: 0.9rem;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .btn-primary {
        background: var(--primary);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
    }
    
    .btn-secondary {
        background: var(--bg-secondary);
        color: var(--text-primary);
        border: 1px solid var(--border);
    }
    
    .btn-secondary:hover {
        background: var(--bg-card);
        border-color: var(--primary);
    }
    
    .btn-success {
        background: var(--success-color);
        color: white;
    }
    
    .btn-danger {
        background: var(--error-color);
        color: white;
    }
    
    .btn-warning {
        background: var(--warning-color);
        color: white;
    }
    
    /* Storage Card */
    .storage-card {
        background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
        border-radius: var(--radius-lg);
        padding: 2rem;
        margin-bottom: 2rem;
        color: white;
    }
    
    .storage-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .storage-item {
        text-align: center;
    }
    
    .storage-label {
        font-size: 0.8rem;
        opacity: 0.9;
        margin-bottom: 0.25rem;
    }
    
    .storage-value {
        font-size: 1.5rem;
        font-weight: 700;
    }
    
    .storage-bar {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 10px;
        height: 8px;
        overflow: hidden;
        margin-bottom: 0.5rem;
    }
    
    .storage-fill {
        background: white;
        height: 100%;
        transition: width 0.3s ease;
        border-radius: 10px;
    }
    
    /* Message Toast */
    .message-toast {
        position: fixed;
        top: 5rem;
        right: 2rem;
        padding: 1rem 1.5rem;
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        gap: 0.75rem;
        animation: slideInRight 0.3s ease;
        z-index: 1000;
    }
    
    .message-toast.success {
        background: var(--success-color);
        color: white;
    }
    
    .message-toast.error {
        background: var(--error-color);
        color: white;
    }
    
    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(20px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    /* Responsive */
    @media (max-width: 768px) {
        .settings-grid {
            grid-template-columns: 1fr;
        }
        
        .storage-grid,
        .stats-grid {
            grid-template-columns: 1fr;
        }
        
        .actions {
            flex-direction: column;
        }
        
        .btn {
            width: 100%;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="settings-wrapper">
    <!-- Page Header -->
    <div class="settings-header">
        <h1>Global Settings</h1>
        <p>Configure your Cuti experience with advanced settings and preferences</p>
    </div>
    
    <!-- Storage Info Card -->
    <div class="storage-card">
        <h2 style="margin: 0 0 1.5rem 0;">Storage Usage</h2>
        <div class="storage-grid">
            <div class="storage-item">
                <div class="storage-label">Total Storage</div>
                <div class="storage-value" id="total-storage">0 MB</div>
            </div>
            <div class="storage-item">
                <div class="storage-label">Database Size</div>
                <div class="storage-value" id="db-size">0 MB</div>
            </div>
            <div class="storage-item">
                <div class="storage-label">File Count</div>
                <div class="storage-value" id="file-count">0</div>
            </div>
        </div>
        <div class="storage-bar">
            <div class="storage-fill" id="storage-bar" style="width: 0%"></div>
        </div>
        <div style="text-align: center; font-size: 0.9rem;" id="storage-text">0 MB / 500 MB (0%)</div>
    </div>
    
    <!-- Settings Grid -->
    <div class="settings-grid">
        <!-- Privacy Settings -->
        <div class="settings-card">
            <h3 class="card-title">🔒 Privacy Settings</h3>
            
            <div class="toggle-container">
                <div class="toggle-info">
                    <div class="toggle-title">Usage Tracking</div>
                    <div class="toggle-desc">Track and analyze your Claude usage patterns</div>
                </div>
                <div class="toggle-switch" id="usage-tracking-toggle">
                    <input type="checkbox" id="usage-tracking">
                </div>
            </div>
            
            <div class="toggle-container">
                <div class="toggle-info">
                    <div class="toggle-title">Privacy Mode</div>
                    <div class="toggle-desc">Enhanced privacy with local-only data storage</div>
                </div>
                <div class="toggle-switch" id="privacy-mode-toggle">
                    <input type="checkbox" id="privacy-mode">
                </div>
            </div>
            
            <div class="toggle-container">
                <div class="toggle-info">
                    <div class="toggle-title">Favorite Prompts</div>
                    <div class="toggle-desc">Save and reuse your favorite prompts</div>
                </div>
                <div class="toggle-switch" id="favorite-prompts-toggle">
                    <input type="checkbox" id="favorite-prompts">
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Auto Cleanup (days)</label>
                <div class="form-description">Automatically delete old data after specified days</div>
                <input type="number" id="cleanup-days" min="1" max="365" class="form-input" value="90">
            </div>
        </div>
        
        <!-- Subscription Settings -->
        <div class="settings-card">
            <h3 class="card-title">💳 Subscription Settings</h3>
            
            <div class="form-group">
                <label class="form-label">Claude Plan</label>
                <div class="form-description">Select your Claude subscription tier</div>
                <select id="claude-plan" class="form-select">
                    <option value="pro">Pro</option>
                    <option value="max5">Max 5</option>
                    <option value="max20">Max 20</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label">Max Storage (MB)</label>
                <div class="form-description">Maximum storage limit for your data</div>
                <input type="number" id="max-storage" min="100" max="10000" class="form-input" value="500">
            </div>
            
            <div class="toggle-container">
                <div class="toggle-info">
                    <div class="toggle-title">Notifications</div>
                    <div class="toggle-desc">Receive alerts for important updates</div>
                </div>
                <div class="toggle-switch" id="notifications-toggle">
                    <input type="checkbox" id="notifications">
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Theme</label>
                <div class="form-description">Choose your preferred interface theme</div>
                <select id="theme" class="form-select">
                    <option value="auto">Auto</option>
                    <option value="light">Light</option>
                    <option value="dark">Dark</option>
                </select>
            </div>
        </div>
        
        <!-- Advanced Configuration -->
        <div class="settings-card">
            <h3 class="card-title">⚙️ Advanced Configuration</h3>
            
            <div class="form-group">
                <label class="form-label">Custom Instructions</label>
                <div class="form-description">Add custom instructions for Claude to follow in all conversations</div>
                <textarea id="custom-instructions" class="form-textarea" 
                          placeholder="Enter any special instructions or context for Claude..."></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label">API Endpoint</label>
                <div class="form-description">Custom API endpoint for Claude (leave blank for default)</div>
                <input type="text" id="api-endpoint" class="form-input" placeholder="https://api.anthropic.com">
            </div>
        </div>
        
        <!-- Integration Settings -->
        <div class="settings-card">
            <h3 class="card-title">🔗 Integration Settings</h3>
            
            <div class="form-group">
                <label class="form-label">GitHub Token</label>
                <div class="form-description">Personal access token for GitHub integration</div>
                <input type="password" id="github-token" class="form-input" placeholder="ghp_xxxxxxxxxxxx">
            </div>
            
            <div class="form-group">
                <label class="form-label">Webhook URL</label>
                <div class="form-description">Webhook for external service notifications</div>
                <input type="url" id="webhook-url" class="form-input" placeholder="https://hooks.example.com/webhook">
            </div>
            
            <div class="form-group">
                <label class="form-label">Export Format</label>
                <div class="form-description">Default format for data exports</div>
                <select id="export-format" class="form-select">
                    <option value="json">JSON</option>
                    <option value="csv">CSV</option>
                    <option value="markdown">Markdown</option>
                </select>
            </div>
        </div>
    </div>
    
    <!-- Usage Statistics -->
    <div class="stats-card">
        <h3 class="card-title">📊 Usage Statistics</h3>
        
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-label">Today</div>
                <div class="stat-value" id="today-tokens">0</div>
                <div class="stat-label">tokens</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">This Month</div>
                <div class="stat-value" id="month-tokens">0</div>
                <div class="stat-label">tokens</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">Total Cost</div>
                <div class="stat-value" id="total-cost">$0.00</div>
                <div class="stat-label">this month</div>
            </div>
        </div>
        
        <div class="actions">
            <button onclick="syncUsage()" class="btn btn-primary">
                🔄 Sync Usage Data
            </button>
            <button onclick="viewDetails()" class="btn btn-secondary">
                📈 View Details
            </button>
        </div>
    </div>
    
    <!-- Sync Service Status -->
    <div class="stats-card">
        <h3 class="card-title">🔄 Sync Service</h3>
        
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-label">Status</div>
                <div class="stat-value" id="sync-status" style="font-size: 1.2rem;">🔴 Stopped</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">Last Sync</div>
                <div class="stat-value" id="last-sync" style="font-size: 1.2rem;">Never</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">Sync Count</div>
                <div class="stat-value" id="sync-count">0</div>
            </div>
        </div>
        
        <div class="actions">
            <button onclick="startSync()" class="btn btn-success">
                ▶️ Start Service
            </button>
            <button onclick="stopSync()" class="btn btn-danger">
                ⏹️ Stop Service
            </button>
        </div>
    </div>
    
    <!-- Action Buttons -->
    <div class="actions" style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border);">
        <button onclick="saveSettings()" class="btn btn-primary">
            💾 Save Settings
        </button>
        <button onclick="resetSettings()" class="btn btn-secondary">
            🔄 Reset to Defaults
        </button>
        <button onclick="cleanupData()" class="btn btn-warning">
            🧹 Cleanup Old Data
        </button>
        <button onclick="createBackup()" class="btn btn-secondary">
            📦 Create Backup
        </button>
        <button onclick="exportData()" class="btn btn-success">
            📤 Export Data
        </button>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let currentSettings = {};
    
    // Initialize all toggle switches
    document.querySelectorAll('.toggle-switch').forEach(toggle => {
        toggle.addEventListener('click', function() {
            const checkbox = this.querySelector('input[type="checkbox"]');
            checkbox.checked = !checkbox.checked;
            this.classList.toggle('active', checkbox.checked);
        });
    });
    
    async function loadSettings() {
        try {
            const response = await fetch('/api/global/settings');
            const data = await response.json();
            currentSettings = data.settings;
            
            // Update toggles
            updateToggle('usage-tracking', data.settings.usage_tracking_enabled);
            updateToggle('privacy-mode', data.settings.privacy_mode);
            updateToggle('favorite-prompts', data.settings.favorite_prompts_enabled);
            updateToggle('notifications', data.settings.notifications_enabled);
            
            // Update inputs
            document.getElementById('cleanup-days').value = data.settings.auto_cleanup_days;
            document.getElementById('claude-plan').value = data.settings.claude_plan;
            document.getElementById('max-storage').value = data.settings.max_storage_mb;
            document.getElementById('theme').value = data.settings.theme;
            
            // Update storage info
            const storage = data.storage;
            document.getElementById('total-storage').textContent = `${storage.total_size_mb} MB`;
            document.getElementById('db-size').textContent = `${storage.database_size_mb} MB`;
            document.getElementById('file-count').textContent = storage.file_count;
            document.getElementById('storage-bar').style.width = `${storage.usage_percentage}%`;
            document.getElementById('storage-text').textContent = 
                `${storage.total_size_mb} MB / ${storage.max_storage_mb} MB (${storage.usage_percentage}%)`;
            
        } catch (error) {
            console.error('Failed to load settings:', error);
            showToast('Failed to load settings', 'error');
        }
    }
    
    function updateToggle(id, checked) {
        const checkbox = document.getElementById(id);
        const toggle = document.getElementById(id + '-toggle');
        if (checkbox && toggle) {
            checkbox.checked = checked;
            toggle.classList.toggle('active', checked);
        }
    }
    
    async function loadUsageStats() {
        try {
            const response = await fetch('/api/global/usage/stats');
            const stats = await response.json();
            
            document.getElementById('today-tokens').textContent = 
                stats.today.tokens.toLocaleString();
            document.getElementById('month-tokens').textContent = 
                stats.this_month.tokens.toLocaleString();
            document.getElementById('total-cost').textContent = 
                `$${stats.this_month.cost.toFixed(2)}`;
                
        } catch (error) {
            console.error('Failed to load usage stats:', error);
        }
    }
    
    async function loadSyncStatus() {
        try {
            const response = await fetch('/api/global/usage/sync/status');
            const status = await response.json();
            
            document.getElementById('sync-status').textContent = 
                status.running ? '🟢 Running' : '🔴 Stopped';
            document.getElementById('last-sync').textContent = 
                status.last_sync ? new Date(status.last_sync).toLocaleString() : 'Never';
            document.getElementById('sync-count').textContent = status.sync_count;
            
        } catch (error) {
            console.error('Failed to load sync status:', error);
        }
    }
    
    async function saveSettings() {
        const settings = {
            usage_tracking_enabled: document.getElementById('usage-tracking').checked,
            privacy_mode: document.getElementById('privacy-mode').checked,
            favorite_prompts_enabled: document.getElementById('favorite-prompts').checked,
            auto_cleanup_days: parseInt(document.getElementById('cleanup-days').value),
            claude_plan: document.getElementById('claude-plan').value,
            max_storage_mb: parseInt(document.getElementById('max-storage').value),
            notifications_enabled: document.getElementById('notifications').checked,
            theme: document.getElementById('theme').value,
            custom_instructions: document.getElementById('custom-instructions').value,
            api_endpoint: document.getElementById('api-endpoint').value,
            github_token: document.getElementById('github-token').value,
            webhook_url: document.getElementById('webhook-url').value,
            export_format: document.getElementById('export-format').value
        };
        
        try {
            const response = await fetch('/api/global/settings', {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(settings)
            });
            
            if (response.ok) {
                showToast('Settings saved successfully!', 'success');
                loadSettings();
            } else {
                showToast('Failed to save settings', 'error');
            }
        } catch (error) {
            console.error('Failed to save settings:', error);
            showToast('Error saving settings', 'error');
        }
    }
    
    async function resetSettings() {
        if (!confirm('Reset all settings to defaults?')) return;
        
        const defaults = {
            usage_tracking_enabled: true,
            privacy_mode: false,
            favorite_prompts_enabled: true,
            auto_cleanup_days: 90,
            claude_plan: 'pro',
            max_storage_mb: 500,
            notifications_enabled: true,
            theme: 'auto'
        };
        
        try {
            const response = await fetch('/api/global/settings', {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(defaults)
            });
            
            if (response.ok) {
                showToast('Settings reset to defaults!', 'success');
                loadSettings();
            }
        } catch (error) {
            console.error('Failed to reset settings:', error);
            showToast('Failed to reset settings', 'error');
        }
    }
    
    async function syncUsage() {
        try {
            const response = await fetch('/api/global/usage/sync', {method: 'POST'});
            const result = await response.json();
            showToast(`Synced ${result.imported} new usage records`, 'success');
            loadUsageStats();
        } catch (error) {
            console.error('Failed to sync usage:', error);
            showToast('Failed to sync usage', 'error');
        }
    }
    
    async function startSync() {
        try {
            await fetch('/api/global/usage/sync/start', {method: 'POST'});
            showToast('Sync service started', 'success');
            loadSyncStatus();
        } catch (error) {
            console.error('Failed to start sync:', error);
            showToast('Failed to start sync service', 'error');
        }
    }
    
    async function stopSync() {
        try {
            await fetch('/api/global/usage/sync/stop', {method: 'POST'});
            showToast('Sync service stopped', 'success');
            loadSyncStatus();
        } catch (error) {
            console.error('Failed to stop sync:', error);
            showToast('Failed to stop sync service', 'error');
        }
    }
    
    async function cleanupData() {
        const days = document.getElementById('cleanup-days').value;
        if (!confirm(`Delete data older than ${days} days?`)) return;
        
        try {
            await fetch(`/api/global/data/cleanup?days=${days}`, {method: 'POST'});
            showToast('Old data cleaned up successfully', 'success');
            loadSettings();
        } catch (error) {
            console.error('Failed to cleanup data:', error);
            showToast('Failed to cleanup data', 'error');
        }
    }
    
    async function createBackup() {
        try {
            const response = await fetch('/api/global/data/backup', {method: 'POST'});
            const result = await response.json();
            showToast(`Backup created: ${result.backup_path}`, 'success');
        } catch (error) {
            console.error('Failed to create backup:', error);
            showToast('Failed to create backup', 'error');
        }
    }
    
    async function exportData() {
        try {
            const response = await fetch('/api/global/data/export', {method: 'POST'});
            const data = await response.json();
            
            // Create download link
            const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `cuti_export_${new Date().toISOString().split('T')[0]}.json`;
            a.click();
            URL.revokeObjectURL(url);
            
            showToast('Data exported successfully', 'success');
        } catch (error) {
            console.error('Failed to export data:', error);
            showToast('Failed to export data', 'error');
        }
    }
    
    function viewDetails() {
        window.location.href = '/statistics';
    }
    
    function showToast(message, type = 'success') {
        const existing = document.querySelector('.message-toast');
        if (existing) existing.remove();
        
        const toast = document.createElement('div');
        toast.className = `message-toast ${type}`;
        toast.innerHTML = `
            <span>${type === 'success' ? '✓' : '⚠'}</span>
            <span>${message}</span>
        `;
        document.body.appendChild(toast);
        
        setTimeout(() => toast.remove(), 5000);
    }
    
    // Initialize Alpine.js component functions
    function init() {
        // Any initialization if needed
    }
    
    function claudeStatus() {
        return {
            claude: { installed: false, authorized: false, version: null, subscription_plan: null },
            statusText: 'Checking...',
            statusClass: 'warning',
            statusDetails: false,
            showDetails: false,
            async checkStatus() {
                try {
                    const response = await fetch('/api/claude-status');
                    const data = await response.json();
                    this.claude = data.claude || {};
                    
                    if (this.claude.installed && this.claude.authorized) {
                        this.statusText = 'Claude Active';
                        this.statusClass = 'success';
                    } else if (this.claude.installed) {
                        this.statusText = 'Claude Not Authorized';
                        this.statusClass = 'warning';
                    } else {
                        this.statusText = 'Claude Not Found';
                        this.statusClass = 'error';
                    }
                    this.statusDetails = true;
                } catch (error) {
                    this.statusText = 'Status Check Failed';
                    this.statusClass = 'error';
                }
            }
        }
    }
    
    // Load everything on page load
    document.addEventListener('DOMContentLoaded', () => {
        loadSettings();
        loadUsageStats();
        loadSyncStatus();
        
        // Refresh sync status every 10 seconds
        setInterval(loadSyncStatus, 10000);
    });
</script>
{% endblock %}