<script setup lang="ts">
import { ref } from 'vue'
import TheWelcome from '../components/TheWelcome.vue'
import { callDemoApi, type ApiResponse, type DemoResponse } from '../utils/api'

const loading = ref(false)
const result = ref<ApiResponse<DemoResponse> | null>(null)
const error = ref<string | null>(null)

const handleCallDemo = async () => {
  loading.value = true
  error.value = null
  result.value = null
  
  try {
    const response = await callDemoApi()
    result.value = response
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Unknown error occurred'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main>
    <div class="demo-section">
      <h2>Demo API Test</h2>
      <button 
        @click="handleCallDemo" 
        :disabled="loading"
        class="demo-button"
      >
        {{ loading ? 'Calling...' : 'Call Demo API' }}
      </button>
      
      <div v-if="result" class="result">
        <h3>Response:</h3>
        <pre>{{ JSON.stringify(result, null, 2) }}</pre>
        <p v-if="result.payload" class="sleep-time">
          Sleep time: <strong>{{ result.payload.sleep_time_ms }}ms</strong>
        </p>
      </div>
      
      <div v-if="error" class="error">
        <h3>Error:</h3>
        <p>{{ error }}</p>
      </div>
    </div>
    
    <TheWelcome />
  </main>
</template>

<style scoped>
.demo-section {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.demo-section h2 {
  margin-bottom: 1rem;
}

.demo-button {
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.demo-button:hover:not(:disabled) {
  background-color: #35a372;
}

.demo-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.result {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.result h3 {
  margin-top: 0;
}

.result pre {
  background-color: #fff;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}

.sleep-time {
  margin-top: 1rem;
  font-size: 1.1rem;
}

.error {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #fee;
  border-radius: 4px;
  color: #c33;
}

.error h3 {
  margin-top: 0;
}
</style>
