<template>
  <div class="setup-wizard-container">
    <div v-if="translationsLoaded" class="setup-wizard-card">
      <div class="wizard-header">
        <h1>{{ t('Welcome to Jingrow') }}</h1>
        <p>{{ t('Let\'s set up your system in a few simple steps') }}</p>
      </div>

      <n-steps v-if="dynamicSlidesLoaded" :current="currentStep" :status="stepStatus">
        <n-step :title="t('Region & Language')" />
        <n-step :title="t('Account Setup')" />
        <n-step v-for="slide in dynamicSlides" :key="slide.name" :title="t(slide.title)" />
        <n-step :title="t('Complete')" />
      </n-steps>
      <n-skeleton v-else text :repeat="2" />

      <div class="wizard-content">
        <!-- Step 1: Region & Language -->
        <div v-if="currentStep === 1" class="step-content">
          <n-form ref="step1FormRef" :model="formData" :rules="step1Rules" label-placement="top">
            <n-form-item :label="t('Language')" path="language">
              <n-select v-model:value="formData.language" :options="languageOptions" @update:value="onLanguageChange" />
            </n-form-item>

            <n-form-item :label="t('Country')" path="country">
              <n-select v-model:value="formData.country" :options="countryOptions" filterable @update:value="onCountryChange" />
            </n-form-item>

            <n-grid :cols="2" :x-gap="16">
              <n-gi>
                <n-form-item :label="t('Time Zone')" path="timezone">
                  <n-select v-model:value="formData.timezone" :options="timezoneOptions" filterable />
                </n-form-item>
              </n-gi>
              <n-gi>
                <n-form-item :label="t('Currency')" path="currency">
                  <n-select v-model:value="formData.currency" :options="currencyOptions" filterable />
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
        </div>

        <!-- Dynamic Slides (from hooks) -->
        <div v-for="(slide, index) in dynamicSlides" :key="slide.name">
          <div v-if="currentStep === 3 + index" class="step-content">
            <n-form :ref="(el: any) => setDynamicFormRef(el, index)" :model="formData" label-placement="top">
              <template v-for="(field, fIndex) in slide.fields" :key="field.fieldname">
                <!-- Skip hidden fields -->
                <template v-if="!field.hidden">
                  <!-- Column Break -->
                  <template v-if="field.fieldtype === 'Column Break'">
                    <!-- Handled by grid layout below -->
                  </template>
                  <!-- Section Break -->
                  <template v-else-if="field.fieldtype === 'Section Break'">
                    <n-divider />
                  </template>
                  <!-- Data/Text Input -->
                  <template v-else-if="field.fieldtype === 'Data'">
                    <n-form-item 
                      :label="t(field.label)" 
                      :path="field.fieldname"
                      :required="!!field.reqd"
                    >
                      <n-input 
                        v-model:value="(formData as any)[field.fieldname]" 
                        :placeholder="''"
                        :maxlength="field.maxlength"
                        @update:value="handleFieldChange(field, slide)"
                      />
                    </n-form-item>
                  </template>
                  <!-- Select/Dropdown -->
                  <template v-else-if="field.fieldtype === 'Select'">
                    <n-form-item 
                      :label="t(field.label)" 
                      :path="field.fieldname"
                      :required="!!field.reqd"
                    >
                      <n-select 
                        v-model:value="(formData as any)[field.fieldname]" 
                        :options="getDynamicFieldOptions(field)"
                        :placeholder="''"
                      />
                    </n-form-item>
                  </template>
                  <!-- Date Picker -->
                  <template v-else-if="field.fieldtype === 'Date'">
                    <n-form-item 
                      :label="t(field.label)" 
                      :path="field.fieldname"
                      :required="!!field.reqd"
                    >
                      <n-date-picker 
                        v-model:value="(formData as any)[field.fieldname]" 
                        type="date" 
                        style="width: 100%"
                        :placeholder="''"
                      />
                    </n-form-item>
                  </template>
                  <!-- Check/Checkbox -->
                  <template v-else-if="field.fieldtype === 'Check'">
                    <n-form-item :path="field.fieldname">
                      <n-checkbox v-model:checked="(formData as any)[field.fieldname]">
                        {{ t(field.label) }}
                      </n-checkbox>
                    </n-form-item>
                  </template>
                </template>
              </template>
            </n-form>
          </div>
        </div>

        <!-- Step: Account Setup -->
        <div v-if="currentStep === getAccountSetupStep()" class="step-content">
          <n-form ref="step2FormRef" :model="formData" :rules="step2Rules" label-placement="top">
            <n-form-item :label="t('Username')" path="username">
              <n-input v-model:value="formData.username" :placeholder="t('Enter your username')" />
            </n-form-item>

            <n-form-item :label="t('Email')" path="email">
              <n-input v-model:value="formData.email" :placeholder="t('Enter your email')" type="text" />
            </n-form-item>

            <n-form-item :label="t('Password')" path="password">
              <n-input v-model:value="formData.password" :placeholder="t('Enter your password')" type="password" show-password-on="click" />
            </n-form-item>
          </n-form>
        </div>

        <!-- Step: Complete -->
        <div v-if="currentStep === getCompleteStep()" class="step-content complete-step">
          <div v-if="!setupComplete" class="setup-progress">
            <n-spin size="large">
              <template #description>
                <div class="progress-text">{{ setupMessage }}</div>
              </template>
            </n-spin>
            <n-progress type="line" :percentage="progressPercentage" :show-indicator="false" />
          </div>

          <div v-else class="setup-success">
            <div class="success-icon">
              <n-icon size="64" color="#18a058">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
              </n-icon>
            </div>
            <h2>{{ t('Setup Complete!') }}</h2>
            <p>{{ t('Your system is ready. Redirecting to dashboard...') }}</p>
          </div>
        </div>
      </div>

      <div class="wizard-actions">
        <n-button v-if="currentStep > 1 && currentStep < getTotalSteps()" @click="prevStep">
          {{ t('Previous') }}
        </n-button>
        <div style="flex: 1"></div>
        <n-button v-if="currentStep < getCompleteStep() - 1" type="primary" @click="nextStep">
          {{ t('Next') }}
        </n-button>
        <n-button v-if="currentStep === getCompleteStep() - 1" type="primary" :loading="isSubmitting" @click="completeSetup">
          {{ t('Complete Setup') }}
        </n-button>
      </div>
    </div>
    <div v-else class="setup-wizard-card" style="display: flex; align-items: center; justify-content: center; min-height: 400px;">
      <n-spin size="large" />
    </div>
  </div>
</template>

<script setup lang="ts">

import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { t } from '../../shared/i18n'
import { api } from '../../shared/api/common'
import { 
  loadLanguages as loadLanguagesAPI, 
  getTranslatedCountries,
  type LanguageData,
  type TranslatedCountries
} from '../../shared/api/translations'
import { useRealtime } from '../../shared/composables/useRealtime'

// Types for dynamic slides
interface SlideField {
  fieldname: string
  label: string
  fieldtype: 'Data' | 'Select' | 'Date' | 'Check' | 'Section Break' | 'Column Break'
  reqd?: number
  hidden?: number
  maxlength?: number
  options?: string
  options_method?: string
  options_method_args?: Record<string, any>
  description?: string
  default?: string
}

interface SlideConfig {
  name: string
  title: string
  icon?: string
  fields: SlideField[]
  onload?: Record<string, any>
  validation?: Record<string, any>
  auto_actions?: Array<{source: string; target: string; action: string}>
}

const router = useRouter()
const message = useMessage()

const currentStep = ref(1)
const stepStatus = ref<'process' | 'finish' | 'error' | 'wait'>('process')
const isSubmitting = ref(false)
const setupComplete = ref(false)
const setupMessage = ref('')
const progressPercentage = ref(0)

const step1FormRef = ref<any>(null)
const step2FormRef = ref<any>(null)

// Realtime for setup progress
const realtime = useRealtime()
let setupTaskUnsubscribe: (() => void) | null = null

// Dynamic slides loaded from backend via hooks
const dynamicSlides = ref<SlideConfig[]>([])
const dynamicSlidesLoaded = ref(false)
const translationsLoaded = ref(false)
const dynamicFormRefs = ref<any[]>([])
const dynamicFieldOptions = ref<Record<string, Array<{label: string; value: string}>>>({})

// Helper functions for dynamic step calculation
function getTotalSteps(): number {
  // 1 (Region) + 1 (Account) + dynamicSlides + 1 (Complete)
  return 3 + dynamicSlides.value.length
}

function getAccountSetupStep(): number {
  // Account setup is always step 2 (after Region)
  return 2
}

function getCompleteStep(): number {
  return getTotalSteps()
}

// Set dynamic form ref
function setDynamicFormRef(el: any, index: number) {
  if (el) {
    dynamicFormRefs.value[index] = el
  }
}

// Get options for dynamic select fields
function getDynamicFieldOptions(field: SlideField): Array<{label: string; value: string}> {
  return dynamicFieldOptions.value[field.fieldname] || []
}

// Form data - base fields only, dynamic fields added on slide load
const formData = reactive<Record<string, any>>({
  language: '',
  country: 'China',
  timezone: 'Asia/Shanghai',
  currency: 'CNY',
  username: '',
  email: '',
  password: ''
})

// Options
const languageOptions = ref<Array<{ label: string; value: string }>>([])
const countryOptions = ref<Array<{ label: string; value: string }>>([])
const timezoneOptions = ref<Array<{ label: string; value: string }>>([])
const currencyOptions = ref<Array<{ label: string; value: string }>>([])

// Translation caches - fetched from backend
const translatedCountries = ref<TranslatedCountries>({})
const languageData = ref<LanguageData | null>(null)

// Validation rules - use dynamic validators for i18n support
const step1Rules = {
  language: { 
    required: true, 
    trigger: 'change',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please select a language'))
      return true
    }
  },
  country: { 
    required: true, 
    trigger: 'change',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please select a country'))
      return true
    }
  },
  timezone: { 
    required: true, 
    trigger: 'change',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please select a timezone'))
      return true
    }
  },
  currency: { 
    required: true, 
    trigger: 'change',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please select a currency'))
      return true
    }
  }
}

const step2Rules = {
  username: { 
    required: true, 
    trigger: 'blur',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please enter a username'))
      return true
    }
  },
  email: { 
    required: true, 
    trigger: 'blur',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please enter a valid email'))
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(value)) return new Error(t('Please enter a valid email'))
      return true
    }
  },
  password: { 
    required: true, 
    trigger: 'blur',
    validator: (_rule: any, value: string) => {
      if (!value) return new Error(t('Please enter a password'))
      if (value.length < 6) return new Error(t('Password must be at least 6 characters'))
      return true
    }
  }
}

// Load dynamic slides from backend hooks
async function loadDynamicSlides() {
  try {
    const response = await api.call('jingrow.desk.page.setup_wizard.setup_wizard.get_setup_wizard_slides')
    
    // jingrow API returns { message: <data> } format
    const slides = response?.message || response
    
    if (slides && Array.isArray(slides)) {
      dynamicSlides.value = slides
      
      // Initialize form data for dynamic fields
      for (const slide of slides) {
        for (const field of slide.fields) {
          if (field.fieldname && !(field.fieldname in formData)) {
            // Use backend-provided default if available
            if (field.default !== undefined && field.default !== null) {
              if (field.fieldtype === 'Date') {
                // Convert date string to timestamp for n-date-picker
                formData[field.fieldname] = new Date(field.default).getTime()
              } else {
                formData[field.fieldname] = field.default
              }
            } else if (field.fieldtype === 'Check') {
              formData[field.fieldname] = false
            } else if (field.fieldtype === 'Date') {
              formData[field.fieldname] = null
            } else {
              formData[field.fieldname] = ''
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('Failed to load dynamic slides:', error)
    // Continue without dynamic slides
  } finally {
    dynamicSlidesLoaded.value = true
  }
}

// Load options for dynamic select fields
async function loadDynamicFieldOptions(field: SlideField) {
  if (!field.options_method) return
  
  try {
    const args = {
      country: formData.country,
      ...field.options_method_args
    }
    const response = await api.call(field.options_method, args)
    
    // jingrow API returns { message: <data> } format
    const options = response?.message || response
    
    if (options && Array.isArray(options)) {
      dynamicFieldOptions.value[field.fieldname] = options.map((item: string) => ({
        label: t(item),
        value: item
      }))
    }
  } catch (error) {
    console.error(`Failed to load options for ${field.fieldname}:`, error)
  }
}

// Handle field change for auto actions
function handleFieldChange(field: SlideField, slide: SlideConfig) {
  if (!slide.auto_actions) return
  
  for (const action of slide.auto_actions) {
    if (action.source === field.fieldname) {
      if (action.action === 'generate_abbr') {
        // Auto-generate abbreviation from company name
        const parts = (formData[field.fieldname] || '').split(' ')
        const abbr = parts.map((p: string) => p ? p.charAt(0) : '').join('').toUpperCase().slice(0, 10)
        formData[action.target] = abbr
      }
    }
  }
}

// Validate dynamic slide
async function validateDynamicSlide(slideIndex: number): Promise<boolean> {
  const formRef = dynamicFormRefs.value[slideIndex]
  if (!formRef) return true
  
  try {
    await formRef.validate()
    return true
  } catch {
    return false
  }
}

// Load regional data
async function loadRegionalData() {
  try {
    // Load country timezone info and translated countries in parallel
    const [countryTimeZoneResponse, translatedCountriesData] = await Promise.all([
      api.call('jingrow.geo.country_info.get_country_timezone_info'),
      getTranslatedCountries()
    ])

    const data = countryTimeZoneResponse.message
    translatedCountries.value = translatedCountriesData

    // Set country options with translations from backend (Babel)
    const countries = Object.keys(data.country_info).sort().map(country => {
      const translatedName = translatedCountries.value[country]
      return {
        label: translatedName 
          ? `${translatedName} (${country})`  // e.g., "中国 (China)"
          : country,  // Fallback to English name if no translation
        value: country
      }
    })
    countryOptions.value = countries

    // Set timezone options (keep original)
    timezoneOptions.value = data.all_timezones.map((tz: string) => ({
      label: tz,
      value: tz
    }))

    // Set currency options (keep original)
    const currencies = Array.from(new Set(
      Object.values(data.country_info).map((info: any) => info.currency)
    )).sort()
    currencyOptions.value = currencies.map((currency: any) => ({
      label: currency,
      value: currency
    }))

    // Load default country if available
    if (data.default_country) {
      formData.country = data.default_country
      await updateCountryDefaults(data.default_country, data.country_info)
    }
  } catch (error) {
    console.error('Failed to load regional data:', error)
    message.error(t('Failed to load regional data'))
  }
}

// Load languages and set default based on browser language
async function loadLanguages() {
  try {
    const data = await loadLanguagesAPI()
    languageData.value = data
    
    // Create language options with native language names
    // The backend returns language names already in their native form
    languageOptions.value = data.languages.map((lang: string) => ({
      label: lang,  // e.g., "简体中文", "English", "日本語"
      value: lang
    }))
    
    // Set default language based on browser language or backend default
    if (!formData.language && data.languages.length > 0) {
      const browserLang = navigator.language.toLowerCase()
      const codesToNames = data.codes_to_names || {}
      
      // Try to match browser language code (e.g., 'zh-cn' -> 'zh')
      let defaultLang = codesToNames[browserLang] || codesToNames[browserLang.split('-')[0]]
      
      // Check if detected language is available
      if (defaultLang && data.languages.includes(defaultLang)) {
        formData.language = defaultLang
      } else {
        // Fallback to backend default (already considers user's locale)
        formData.language = data.default_language || data.languages[0]
      }
    }
  } catch (error) {
    console.error('Failed to load languages:', error)
    message.error(t('Failed to load languages'))
  }
}

// Update country defaults
async function updateCountryDefaults(country: string, countryInfo: any) {
  if (countryInfo[country]) {
    const info = countryInfo[country]
    if (info.currency) formData.currency = info.currency
    if (info.timezones && info.timezones.length > 0) {
      formData.timezone = info.timezones[0]
    }
  }
  
  // Load dynamic field options that depend on country
  await loadDynamicOptionsForCountry()
}

// Load dynamic field options that depend on country
async function loadDynamicOptionsForCountry() {
  for (const slide of dynamicSlides.value) {
    for (const field of slide.fields) {
      if (field.options_method) {
        await loadDynamicFieldOptions(field)
      }
    }
  }
}

// Handle language change
async function onLanguageChange(lang: string) {
  try {
    // Load translations for the new language
    const langResponse = await api.call('jingrow.desk.page.setup_wizard.setup_wizard.load_messages', {
      language: lang
    })
    
    // Update window.jingrow._messages with translations from response
    if ((langResponse as any).__messages) {
      if (!window.jingrow) {
        (window as any).jingrow = {}
      }
      window.jingrow._messages = (langResponse as any).__messages
    }
    
    // Reload translated countries with new language
    const newTranslatedCountries = await getTranslatedCountries()
    translatedCountries.value = newTranslatedCountries
    
    // Update country options with new translations
    const currentCountryInfo = countryOptions.value.reduce((acc, opt) => {
      acc[opt.value] = opt
      return acc
    }, {} as Record<string, any>)
    
    countryOptions.value = countryOptions.value.map(opt => {
      const translatedName = translatedCountries.value[opt.value]
      return {
        ...opt,
        label: translatedName 
          ? `${translatedName} (${opt.value})`
          : opt.value
      }
    })
    
    message.success(t('Language updated successfully'))
  } catch (error) {
    console.error('Failed to load language messages:', error)
    message.error(t('Failed to update language'))
  }
}

// Handle country change
async function onCountryChange(country: string) {
  // Update timezone and currency based on country
  await loadRegionalData()
}

// Navigation
async function nextStep() {
  if (currentStep.value === 1) {
    try {
      await step1FormRef.value?.validate()
      // Load dynamic field options for next slides
      await loadDynamicOptionsForCountry()
      currentStep.value = 2
    } catch (error) {
      // Validation failed
    }
  } else if (currentStep.value === 2) {
    // Account setup step - validate and move to dynamic slides
    try {
      await step2FormRef.value?.validate()
      currentStep.value = 3
    } catch (error) {
      // Validation failed
    }
  } else {
    // Check if current step is a dynamic slide (step 3+)
    const dynamicSlideIndex = currentStep.value - 3
    if (dynamicSlideIndex >= 0 && dynamicSlideIndex < dynamicSlides.value.length) {
      try {
        const isValid = await validateDynamicSlide(dynamicSlideIndex)
        if (isValid) {
          currentStep.value++
        }
      } catch (error) {
        // Validation failed
      }
    }
  }
}

function prevStep() {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

// Complete setup
async function completeSetup() {
  try {
    // Validate the last dynamic slide if exists
    const lastDynamicSlideIndex = dynamicSlides.value.length - 1
    if (lastDynamicSlideIndex >= 0) {
      const isValid = await validateDynamicSlide(lastDynamicSlideIndex)
      if (!isValid) return
    }
    
    isSubmitting.value = true
    currentStep.value = getCompleteStep()
    setupMessage.value = t('Starting setup...')
    progressPercentage.value = 5

    // Build args object with all form data
    const args: Record<string, any> = {
      language: formData.language,
      country: formData.country,
      timezone: formData.timezone,
      currency: formData.currency,
      username: formData.username,
      email: formData.email,
      password: formData.password
    }
    
    // Add all dynamic slide fields
    for (const slide of dynamicSlides.value) {
      for (const field of slide.fields) {
        if (field.fieldname && formData[field.fieldname] !== undefined) {
          // Handle special types
          if (field.fieldtype === 'Date' && formData[field.fieldname]) {
            const date = new Date(formData[field.fieldname])
            args[field.fieldname] = date.toISOString().split('T')[0]
          } else if (field.fieldtype === 'Check') {
            args[field.fieldname] = formData[field.fieldname] ? 1 : 0
          } else {
            args[field.fieldname] = formData[field.fieldname]
          }
        }
      }
    }
    
    // Auto-calculate fy_end_date from fy_start_date (start + 1 year - 1 day)
    if (args.fy_start_date && !args.fy_end_date) {
      const startDate = new Date(args.fy_start_date)
      const endDate = new Date(startDate)
      endDate.setFullYear(endDate.getFullYear() + 1)
      endDate.setDate(endDate.getDate() - 1)
      args.fy_end_date = endDate.toISOString().split('T')[0]
    }

    // Setup realtime listener for progress events
    setupTaskUnsubscribe = realtime.subscribe('setup_task', (data: any) => {
      if (data.progress) {
        // Progress update: data.progress = [current_stage, total_stages]
        const [current, total] = data.progress
        progressPercentage.value = Math.round(((current + 1) / total) * 100)
        if (data.stage_status) {
          const translatedMsg = (window as any).jingrow?._messages?.[data.stage_status] || data.stage_status
          setupMessage.value = translatedMsg
        }
      }
      if (data.status === 'ok') {
        progressPercentage.value = 100
        setupComplete.value = true
        setupMessage.value = t('Setup completed successfully!')
        if ((window as any).jingrow?.boot) {
          (window as any).jingrow.boot.setup_complete = true
        }
        setTimeout(() => {
          window.location.href = '/'
        }, 1500)
      }
      if (data.fail_msg) {
        message.error(data.fail_msg)
        stepStatus.value = 'error'
        currentStep.value = getCompleteStep() - 1
      }
    })

    // Ensure socket is connected before calling API
    realtime.ensureConnected()
    await new Promise(resolve => setTimeout(resolve, 300))

    const response = await api.call('jingrow.desk.page.setup_wizard.setup_wizard.setup_complete', { args })

    if (response.message.status === 'ok') {
      // Sync mode: ensure progress shows 100% before redirect
      progressPercentage.value = 100
      setupMessage.value = t('Setup completed successfully!')
      // Wait a moment to show 100% progress before redirect
      await new Promise(resolve => setTimeout(resolve, 500))
      setupComplete.value = true
      if ((window as any).jingrow?.boot) {
        (window as any).jingrow.boot.setup_complete = true
      }
      setTimeout(() => {
        window.location.href = '/'
      }, 1000)
    } else if (response.message.status === 'registered') {
      setupMessage.value = t('Setting up your system...')
    }
  } catch (error: any) {
    message.error(error.message || t('Setup failed. Please try again.'))
    stepStatus.value = 'error'
    currentStep.value = getCompleteStep() - 1
  } finally {
    isSubmitting.value = false
  }
}

// Cleanup on unmount
onUnmounted(() => {
  if (setupTaskUnsubscribe) {
    setupTaskUnsubscribe()
    setupTaskUnsubscribe = null
  }
})

onMounted(async () => {
  // Load dynamic slides from hooks first
  await loadDynamicSlides()

  // Load languages first to determine browser language
  await loadLanguages()
  
  // Load translations for detected/default language
  if (formData.language) {
    try {
      const langResponse = await api.call('jingrow.desk.page.setup_wizard.setup_wizard.load_messages', {
        language: formData.language
      })
      // Update window.jingrow._messages with translations from response
      const messages = (langResponse as any).__messages
      if (messages && Object.keys(messages).length > 0) {
        if (!window.jingrow) {
          (window as any).jingrow = {}
        }
        window.jingrow._messages = messages
      }
    } catch (error) {
      console.error('Failed to load initial translations:', error)
    }
  }

  // Translations ready - allow UI to render
  translationsLoaded.value = true

  await loadRegionalData()
})
</script>

<style scoped>
.setup-wizard-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  padding: 20px;
}

.setup-wizard-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 40px;
  max-width: 800px;
  width: 100%;
}

.wizard-header {
  text-align: center;
  margin-bottom: 40px;
}

.wizard-header h1 {
  font-size: 32px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.wizard-header p {
  font-size: 16px;
  color: #666;
}

.wizard-content {
  margin: 40px 0;
  min-height: 400px;
}

.step-content {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.wizard-actions {
  display: flex;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.complete-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 40px 0;
}

.setup-progress {
  width: 100%;
  max-width: 400px;
}

.progress-text {
  margin-top: 20px;
  font-size: 16px;
  color: #666;
}

.setup-success {
  animation: scaleIn 0.5s ease-in-out;
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.success-icon {
  margin-bottom: 20px;
}

.setup-success h2 {
  font-size: 28px;
  font-weight: 600;
  color: #18a058;
  margin-bottom: 12px;
}

.setup-success p {
  font-size: 16px;
  color: #666;
}

.form-item-hint {
  font-size: 12px;
  color: #999;
  margin-top: -8px;
  margin-left: 2px;
}
</style>
