<template>
  <div class="user-zero-view">
    <div class="view-header">
      <div class="header-title-row">
        <button class="back-button" @click="goBack" aria-label="Go back to home">
          ←
        </button>
        <h1 class="page-title">User Zero Stars Testing</h1>
      </div>
      <p class="page-subtitle">Test starred projects querying with TimeSafari User Zero</p>
    </div>

    <!-- User Zero Identity Section -->
    <div class="config-section">
      <h2 class="section-title">User Zero Identity</h2>
      <div class="config-grid">
        <div class="config-item">
          <label>DID:</label>
          <code class="config-value">{{ config.identity.did }}</code>
        </div>
        <div class="config-item">
          <label>Name:</label>
          <span class="config-value">{{ config.identity.name }}</span>
        </div>
        <div class="config-item">
          <label>API Server:</label>
          <span class="config-value">{{ config.getApiServerUrl() }} (mode: {{ config.api.serverMode }})</span>
        </div>
        <div class="config-item">
          <label>JWT Expiration:</label>
          <span class="config-value">{{ config.api.jwtExpirationMinutes }} minutes</span>
        </div>
      </div>
    </div>

    <!-- Starred Projects Section -->
    <div class="config-section">
      <h2 class="section-title">Starred Projects</h2>
      <div class="starred-projects-list">
        <div 
          v-for="projectId in config.starredProjects.planIds" 
          :key="projectId"
          class="project-item"
        >
          <span class="project-id">{{ projectId }}</span>
        </div>
      </div>
      <div class="config-item">
        <label>Last Acked JWT ID:</label>
        <code class="config-value">{{ config.starredProjects.lastAckedJwtId }}</code>
      </div>
    </div>

    <!-- Testing Controls -->
    <div class="config-section">
      <h2 class="section-title">Testing Controls</h2>
      <div class="test-controls">
        <button 
          @click="testStarsQuery" 
          :disabled="isTesting"
          class="test-button primary"
        >
          {{ isTesting ? 'Testing...' : 'Test Stars Query' }}
        </button>
        
        <button 
          @click="testJWTGeneration" 
          :disabled="isTesting"
          class="test-button secondary"
        >
          Test JWT Generation
        </button>
        
        <button 
          @click="testNotificationScheduling" 
          :disabled="isTesting"
          class="test-button secondary"
        >
          Test Notification Scheduling
        </button>
        
        <button 
          @click="toggleMockMode" 
          class="test-button"
          :class="mockMode ? 'warning' : 'success'"
        >
          {{ mockMode ? 'Disable Mock Mode' : 'Enable Mock Mode' }}
        </button>
      </div>
    </div>

    <!-- Test Results -->
    <div v-if="testResults" class="config-section">
      <h2 class="section-title">Test Results</h2>
      <div class="test-results">
        <pre class="results-json">{{ JSON.stringify(testResults, null, 2) }}</pre>
      </div>
    </div>

    <!-- Error Display -->
    <div v-if="errorMessage" class="error-section">
      <h3 class="error-title">Test Error</h3>
      <p class="error-message">{{ errorMessage }}</p>
      <button @click="clearError" class="clear-error-button">Clear Error</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { TEST_USER_ZERO_CONFIG, TestUserZeroAPI } from '../config/test-user-zero'

const router = useRouter()

// Reactive state
const config = reactive(TEST_USER_ZERO_CONFIG)
const isTesting = ref(false)
const testResults = ref<Record<string, unknown> | null>(null)
const errorMessage = ref('')
const mockMode = ref<boolean>(TEST_USER_ZERO_CONFIG.testing.enableMockResponses)

// API client instance
const apiClient = new TestUserZeroAPI()

/**
 * Test stars querying functionality
 */
async function testStarsQuery() {
  isTesting.value = true
  errorMessage.value = ''
  testResults.value = null
  
  try {
    console.log('🔄 Testing stars query for User Zero...')
    
    // Test the stars API call
    const result = await apiClient.getStarredProjectsWithChanges(
      [...config.starredProjects.planIds], // Convert readonly array to mutable array
      config.starredProjects.lastAckedJwtId
    )
    
    console.log('✅ Stars query result:', result)
    testResults.value = {
      test: 'stars_query',
      success: true,
      timestamp: new Date().toISOString(),
      result: result,
      config: {
        starredPlanIds: config.starredProjects.planIds,
        lastAckedJwtId: config.starredProjects.lastAckedJwtId,
        mockMode: mockMode.value
      }
    }
    
  } catch (error) {
    console.error('❌ Stars query test failed:', error)
    errorMessage.value = `Stars query test failed: ${error.message}`
    testResults.value = {
      test: 'stars_query',
      success: false,
      timestamp: new Date().toISOString(),
      error: error.message
    }
  } finally {
    isTesting.value = false
  }
}

/**
 * Test JWT generation
 */
async function testJWTGeneration() {
  isTesting.value = true
  errorMessage.value = ''
  testResults.value = null
  
  try {
    console.log('🔄 Testing JWT generation for User Zero...')
    
    // Generate test JWT
    // Generate a fresh JWT token
    await apiClient.refreshToken()
    const jwt = apiClient.getJWT() // Get the JWT from the client
    
    console.log('✅ JWT generation successful')
    testResults.value = {
      test: 'jwt_generation',
      success: true,
      timestamp: new Date().toISOString(),
      result: {
        did: config.identity.did,
        jwtLength: jwt.length,
        expirationMinutes: config.api.jwtExpirationMinutes
      }
    }
    
  } catch (error) {
    console.error('❌ JWT generation test failed:', error)
    errorMessage.value = `JWT generation test failed: ${error.message}`
    testResults.value = {
      test: 'jwt_generation',
      success: false,
      timestamp: new Date().toISOString(),
      error: error.message
    }
  } finally {
    isTesting.value = false
  }
}

/**
 * Test notification scheduling with 5-minute lead time
 */
async function testNotificationScheduling() {
  isTesting.value = true
  errorMessage.value = ''
  testResults.value = null
  
  try {
    console.log('🔄 Testing notification scheduling for User Zero...')
    
    // Import and use the plugin
    const { DailyNotification } = await import('@timesafari/daily-notification-plugin')
    
    // Schedule a test notification
    const scheduleTime = new Date()
    scheduleTime.setMinutes(scheduleTime.getMinutes() + 10) // 10 minutes from now
    const timeString = scheduleTime.toTimeString().slice(0, 5) // HH:mm format
    
    const options = {
      time: timeString,
      title: config.notifications.defaultTitle,
      body: config.notifications.defaultBody,
      sound: true,
      priority: 'high' as const
    }
    
    console.log('📅 Scheduling notification with options:', options)
    
    await DailyNotification.scheduleDailyNotification(options)
    
    console.log('✅ Notification scheduled successfully!')
    testResults.value = {
      test: 'notification_scheduling',
      success: true,
      timestamp: new Date().toISOString(),
      result: {
        scheduledTime: timeString,
        fetchLeadTimeMinutes: config.notifications.fetchLeadTimeMinutes,
        options: options
      }
    }
    
  } catch (error) {
    console.error('❌ Notification scheduling test failed:', error)
    errorMessage.value = `Notification scheduling test failed: ${error.message}`
    testResults.value = {
      test: 'notification_scheduling',
      success: false,
      timestamp: new Date().toISOString(),
      error: error.message
    }
  } finally {
    isTesting.value = false
  }
}

/**
 * Toggle mock mode for testing
 */
function toggleMockMode() {
  mockMode.value = !mockMode.value
  console.log(`🔄 Mock mode ${mockMode.value ? 'enabled' : 'disabled'}`)
}

/**
 * Clear error message
 */
function clearError() {
  errorMessage.value = ''
}

/**
 * Navigate back to home
 */
function goBack() {
  router.push('/')
}
</script>

<style scoped>
.user-zero-view {
  max-width: 800px;
  margin: 0 auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  color: white;
}

.view-header {
  text-align: center;
  margin-bottom: 30px;
}

.header-title-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.back-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  height: 40px;
}

.back-button:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateX(-2px);
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: white;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
}

.config-section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.config-item label {
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}

.config-value {
  font-family: 'Courier New', monospace;
  background: rgba(0, 0, 0, 0.2);
  padding: 8px 12px;
  border-radius: 6px;
  color: #fff;
  word-break: break-all;
}

.starred-projects-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.project-item {
  background: rgba(255, 255, 255, 0.1);
  padding: 12px;
  border-radius: 8px;
  text-align: center;
}

.project-id {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.test-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.test-button {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.test-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.test-button.primary {
  background: #4CAF50;
  color: white;
}

.test-button.secondary {
  background: #2196F3;
  color: white;
}

.test-button.warning {
  background: #FF9800;
  color: white;
}

.test-button.success {
  background: #4CAF50;
  color: white;
}

.test-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.test-results {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 16px;
  overflow-x: auto;
}

.results-json {
  color: #fff;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  margin: 0;
  white-space: pre-wrap;
}

.error-section {
  background: rgba(244, 67, 54, 0.2);
  border: 1px solid rgba(244, 67, 54, 0.5);
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.error-title {
  margin: 0 0 8px 0;
  color: #ffcdd2;
  font-size: 16px;
  font-weight: 600;
}

.error-message {
  margin: 0 0 12px 0;
  color: #ffcdd2;
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.clear-error-button {
  background: #f44336;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.clear-error-button:hover {
  background: #d32f2f;
}

@media (max-width: 768px) {
  .user-zero-view {
    padding: 16px 0;
  }
  
  .config-grid {
    grid-template-columns: 1fr;
  }
  
  .test-controls {
    flex-direction: column;
  }
  
  .test-button {
    width: 100%;
  }
  
  .header-title-row {
    gap: 8px;
  }
  
  .back-button {
    min-width: 36px;
    height: 36px;
    font-size: 16px;
  }
}
</style>
