/**
 * Settings View - System Configuration
 */

const Settings = {
  setup() {
    const { ref, onMounted } = Vue;
    const activeTab = ref('site');
    const loading = ref(true);
    const configs = ref({});
    const saving = ref(false);

    const tabs = [
      { id: 'site', name: '站点配置', icon: 'fas fa-globe' },
      { id: 'subscribe', name: '订阅配置', icon: 'fas fa-rss' },
      { id: 'invite', name: '邀请配置', icon: 'fas fa-user-plus' },
      { id: 'frontend', name: '外观设置', icon: 'fas fa-palette' },
      { id: 'server', name: '服务端', icon: 'fas fa-server' },
      { id: 'safe', name: '安全设置', icon: 'fas fa-shield-alt' }
    ];

    const fetchConfigs = async () => {
      loading.value = true;
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const response = await fetch(`/api/v2/${adminPath}/config/fetch`);
        const result = await response.json();
        if (result.data) {
          configs.value = result.data;
        }
      } catch (err) {
        console.error('Failed to fetch configs', err);
      } finally {
        loading.value = false;
      }
    };

    const handleSave = async () => {
      saving.value = true;
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const payload = { ...configs.value[activeTab.value] };
        
        const response = await fetch(`/api/v2/${adminPath}/config/save`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        
        const result = await response.json();
        if (result.data) {
          alert('保存成功');
        } else {
          alert('保存失败: ' + result.message);
        }
      } catch (err) {
        alert('保存错误');
      } finally {
        saving.value = false;
      }
    };

    onMounted(fetchConfigs);

    return {
      activeTab,
      tabs,
      configs,
      loading,
      saving,
      handleSave
    };
  },
  template: `
    <div class="settings-view">
      <div class="settings-sidebar">
        <div 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="['tab-item', { active: activeTab === tab.id }]"
          @click="activeTab = tab.id"
        >
          <i :class="tab.icon"></i>
          <span>{{ tab.name }}</span>
        </div>
      </div>

      <div class="settings-content" v-if="!loading">
        <div class="section-card animate-in">
          <div class="card-header">
            <h3>{{ tabs.find(t => t.id === activeTab).name }}</h3>
            <button class="btn btn-primary" @click="handleSave" :disabled="saving">
              <i class="fas fa-save"></i> {{ saving ? '保存中...' : '保存设置' }}
            </button>
          </div>
          
          <div class="card-body">
            <!-- Dynamic Form based on activeTab -->
            <div class="form-grid">
              <template v-for="(val, key) in configs[activeTab]">
                <div class="form-group">
                  <label>{{ key }}</label>
                  
                  <!-- Boolean (Checkbox/Switch) -->
                  <div v-if="typeof val === 'boolean'" class="switch-container">
                    <input type="checkbox" v-model="configs[activeTab][key]" :id="'check-' + key">
                    <label :for="'check-' + key" class="switch-slider"></label>
                  </div>
                  
                  <!-- Number -->
                  <input v-else-if="typeof val === 'number'" type="number" v-model.number="configs[activeTab][key]" class="form-input">
                  
                  <!-- String -->
                  <input v-else type="text" v-model="configs[activeTab][key]" class="form-input">
                  
                  <small class="form-help">设置项标识: {{ key }}</small>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="loading-state">
        <div class="spinner"></div>
        <p>加载配置中...</p>
      </div>
    </div>
  `
};

export default Settings;
