<template>
  <!-- ═══ 高级设置(AI 自动执行范围 / 日志级别)═══ -->
  <section class="panel">
    <div class="panel-header">
      <h2>{{ $t('settings.sectionAdvanced') }}</h2>
    </div>
    <div class="general-settings">
      <!-- ═══ 应用数据目录(运行期确定,跨平台) ═══ -->
      <SettingRow :label="$t('settings.labelDataDir')" :desc="$t('settings.descDataDir')">
        <span class="data-dir-path" :title="dataDir">{{ dataDir || $t('settings.loading') }}</span>
      </SettingRow>

      <!-- F-#97:三档 low/medium/all。low=仅低风险自动(等价旧 autoExecute=false);
           medium=含中风险自动;all=全自动无审批(完全 AI 接管,选时二次确认) -->
      <SettingRow ref="rowAutoExecute" :label="$t('settings.labelAutoExecute')" :desc="$t('settings.descAutoExecute')">
        <select v-model="settings.autoExecuteMode" class="setting-select" @change="onAutoModeChange">
          <option value="low">{{ $t('settings.autoModeLow') }}</option>
          <option value="medium">{{ $t('settings.autoModeMedium') }}</option>
          <option value="all">{{ $t('settings.autoModeAll') }}</option>
        </select>
      </SettingRow>
      <SettingRow ref="rowLogLevel" :label="$t('settings.labelLogLevel')" :desc="$t('settings.descLogLevel')">
        <select v-model="settings.logLevel" class="setting-select" @change="onLogLevelChange">
          <option value="error">Error</option>
          <option value="warn">Warning</option>
          <option value="info">Info</option>
          <option value="debug">Debug</option>
        </select>
      </SettingRow>

      <!-- 审批超时:用户未处理审批弹窗时的自动拒绝阅值;0 表示不限时(对齐旧默认) -->
      <SettingRow ref="rowApprovalTimeout" :label="$t('settings.labelApprovalTimeout')" :desc="$t('settings.descApprovalTimeout')">
        <select v-model="settings.approvalTimeout" class="setting-select" @change="onApprovalTimeoutChange">
          <option :value="0">{{ $t('settings.approvalTimeoutUnlimited') }}</option>
          <option :value="300000">{{ $t('settings.approvalTimeout5m') }}</option>
          <option :value="900000">{{ $t('settings.approvalTimeout15m') }}</option>
          <option :value="1800000">{{ $t('settings.approvalTimeout30m') }}</option>
          <option :value="3600000">{{ $t('settings.approvalTimeout60m') }}</option>
        </select>
      </SettingRow>
      <!-- 自定义提示词:注入到 AI 系统 prompt 末尾,用户可自定义 AI 行为偏好 -->
      <SettingRow ref="rowCustomPrompt" :label="$t('settings.labelCustomPrompt')" :desc="$t('settings.descCustomPrompt')">
        <textarea
          v-model="customPrompt"
          class="setting-textarea"
          :placeholder="$t('settings.placeholderCustomPrompt')"
          rows="4"
          @change="onCustomPromptChange"
        />
      </SettingRow>
    </div>

    <!-- all 二次确认弹层(独立,不与 Settings 壳层共用:壳层按钮写死「删除」不适合「确认接管」) -->
    <Transition name="confirm">
      <div v-if="confirmState.visible" class="confirm-mask" @click.self="answerConfirm(false)">
        <div class="confirm-box">
          <div class="confirm-msg">{{ confirmState.msg }}</div>
          <div class="confirm-actions">
            <button class="btn btn-ghost btn-sm" @click="answerConfirm(false)">{{ $t('common.cancel') }}</button>
            <button class="btn btn-danger btn-sm" @click="answerConfirm(true)">{{ confirmState.dangerLabel || $t('common.confirm') }}</button>
          </div>
        </div>
      </div>
    </Transition>
  </section>
</template>

<script setup lang="ts">
import { ref, reactive, watch, useTemplateRef, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfirm } from '@/composables/useConfirm'
import { useAppSettingsStore } from '@/stores/appSettings'
import { settingsApi } from '@/api'
import SettingRow from './SettingRow.vue'

// ============================================================
// 高级域 — AI 自动执行范围(三档) / 日志级别
// F-#97(2026-06-22):原 autoExecute boolean checkbox → autoExecuteMode select 三档
// (low/medium/all),KV 持久化 df-ai-auto-execute-mode,默认 low。
// low 必须等价旧行为(autoExecute=false 仅 Low 风险自动):后端 audit/mod.rs 按 mode
// 判定 Med/High 是否走自动分支,low 时 Med/High 仍进审批块,行为与旧完全一致。
// all(完全接管)选时二次确认:防误选致无审批全自动执行高危操作。
// ============================================================
const { t } = useI18n()
const appSettings = useAppSettingsStore()

// 应用数据目录(运行期确定,跨平台)
const dataDir = ref('')
onMounted(async () => {
  try {
    dataDir.value = await settingsApi.getDataDir()
  } catch { /* 静默 */ }
})
// useConfirm 真实 API:返回 { confirmState, confirmDialog(msg, dangerLabel), answerConfirm(ok) }
// confirmDialog 返回 Promise<boolean>(true=确认,false=取消),无 title/content/confirmText/cancelText
// 字段。此处用 msg 拼标题+内容,dangerLabel 作确认按钮文案,自渲染独立弹层(上方模板)。
const { confirmState, confirmDialog, answerConfirm } = useConfirm()

// 审批超时合法选项白名单(对齐 <select> option);脏值回退默认 15min。
// 必须在 settings reactive 之前定义,防打包后初始化顺序导致 TDZ。
const VALID_APPROVAL_TIMEOUTS = [0, 300_000, 900_000, 1_800_000, 3_600_000]
function clampApprovalTimeout(raw: number): number {
  return VALID_APPROVAL_TIMEOUTS.includes(raw) ? raw : 900_000
}

// 三档合法值 + 脏值白名单兜底
const VALID_MODES = ['low', 'medium', 'all'] as const
type AutoMode = (typeof VALID_MODES)[number]
function clampMode(raw: string): AutoMode {
  return (VALID_MODES as readonly string[]).includes(raw) ? (raw as AutoMode) : 'low'
}

// M15: logLevel 合法值白名单(对齐 <select> option)+ 脏值兜底(默认 info)。
// 防 KV 里历史脏值(手改/旧版本/导入备份)落到 select 显示空。
const VALID_LOG_LEVELS = ['error', 'warn', 'info', 'debug'] as const
type LogLevel = (typeof VALID_LOG_LEVELS)[number]
function clampLogLevel(raw: string): LogLevel {
  return (VALID_LOG_LEVELS as readonly string[]).includes(raw) ? (raw as LogLevel) : 'info'
}

const settings = reactive({
  // 三档 low/medium/all,默认 low(=旧 autoExecute=false 现状),KV 持久化 df-ai-auto-execute-mode。
  // clampMode 兜底脏值。
  autoExecuteMode: clampMode(appSettings.get<string>('df-ai-auto-execute-mode', 'low')),
  // M15: logLevel 真持久化——从 KV 读回(默认 info),onLogLevelChange 写回 KV。
  // 原 bug:仅 reactive 内存态,刷新即失,@change 显「已保存」是假成功。
  logLevel: clampLogLevel(appSettings.get<string>('df-log-level', 'info')),
  // 审批超时(ms):0=不限时,缺省 900000(15min);仅固定合法选项,脏值回退默认
  approvalTimeout: clampApprovalTimeout(appSettings.get<number>('df-approval-timeout', 900000)),
})
const customPrompt = ref(appSettings.get<string>('custom_prompt', ''))

const rowAutoExecute = useTemplateRef<InstanceType<typeof SettingRow>>('rowAutoExecute')
const rowLogLevel = useTemplateRef<InstanceType<typeof SettingRow>>('rowLogLevel')
const rowCustomPrompt = useTemplateRef<InstanceType<typeof SettingRow>>('rowCustomPrompt')
const rowApprovalTimeout = useTemplateRef<InstanceType<typeof SettingRow>>('rowApprovalTimeout')

// 上一次确认生效的档位:all 二次确认取消时恢复此值(非写死 low),避免 medium 用户误选 all
// 取消后被强制降级 low。初始化 = 当前有效值;每次确认成功(含非 all 切换)更新。
let lastConfirmedMode: AutoMode = settings.autoExecuteMode

// all(完全接管)二次确认:防误选致无审批全自动执行高危操作(删文件/执行任意命令)
// 选 all → 弹确认 → 确认落 KV + markSaved + 更新 lastConfirmedMode;取消恢复 lastConfirmedMode(不落 KV)。
// 非 all 切换:直接落 KV + 更新 lastConfirmedMode(watch 兜底同值无副作用)。
async function onAutoModeChange() {
  if (settings.autoExecuteMode === 'all') {
    const msg = t('settings.autoModeAllConfirmTitle') + '\n\n' + t('settings.autoModeAllConfirmContent')
    const ok = await confirmDialog(msg, t('common.confirm'))
    if (!ok) {
      settings.autoExecuteMode = lastConfirmedMode // 取消恢复原档位(非写死 low)
      return
    }
  }
  appSettings.set('df-ai-auto-execute-mode', settings.autoExecuteMode)
  lastConfirmedMode = settings.autoExecuteMode
  rowAutoExecute.value?.markSaved()
}

// watch 兜底:非 all 切换直接落 KV + 更新 lastConfirmedMode(all 走 onAutoModeChange 确认后落,
// 避免 watch 抢先持久化未确认的 all 值)。onAutoModeChange 已落 KV 时此 watch 重复 set 同值无副作用。
watch(
  () => settings.autoExecuteMode,
  (v) => {
    if (v !== 'all') {
      appSettings.set('df-ai-auto-execute-mode', v)
      lastConfirmedMode = v
    }
  },
)

// M15: logLevel 真持久化——@change 写 KV(df-log-level)+ 显「已保存」反馈。
// 原 bug:仅 reactive session 态,markSaved 显「已保存」是假成功(刷新即失)。
// 注:仅持久化偏好值;运行时日志过滤器是否实时读此值取决于后端日志初始化策略
// (本任务范围只修「假保存」,运行时生效链路另行评估,不擅自扩展)。
function onLogLevelChange() {
  void appSettings.set('df-log-level', settings.logLevel)
  rowLogLevel.value?.markSaved()
}

// 下一笔发起的审批即生效(aiShared.startApprovalTimer 每次实时读),已在跑的计时器沿用旧值。
function onCustomPromptChange() {
  appSettings.set('custom_prompt', customPrompt.value)
  rowCustomPrompt.value?.markSaved()
}

function onApprovalTimeoutChange() {
  appSettings.set('df-approval-timeout', settings.approvalTimeout)
  rowApprovalTimeout.value?.markSaved()
}
</script>

<style scoped>
/* 阶段5 UX 重构:复用 settings.css 全局 .panel/.panel-header/.general-settings/
   .setting-select/.setting-textarea + SettingRow(封装 .setting-row/.setting-info/.setting-label/
   .setting-desc/.setting-control)。本 Section 仅保留 all 二次确认弹层特有 scoped 样式。

   F-#97 all 二次确认弹层:复用 Settings.vue 壳层 confirm 弹层同款样式(mask/box/msg/
   actions/transition),此处独立持有 useConfirm 状态(不与壳层共用,壳层按钮写死「删除」)。 */
.data-dir-path {
  font-size: 12px;
  color: var(--df-text-dim);
  word-break: break-all;
}
.confirm-mask {
  position: fixed;
  inset: 0;
  z-index: 1100;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.confirm-box {
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
  padding: 20px;
  min-width: 280px;
  max-width: 420px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.4);
}
.confirm-msg { font-size: 13px; color: var(--df-text); line-height: 1.5; margin-bottom: 16px; white-space: pre-line; }
.confirm-actions { display: flex; justify-content: flex-end; gap: 8px; }
.btn-danger { background: var(--df-danger); color: #fff; }
.btn-danger:hover { filter: brightness(1.1); }
.confirm-enter-active, .confirm-leave-active { transition: opacity 0.15s; }
.confirm-enter-from, .confirm-leave-to { opacity: 0; }
</style>
