<template>
  <div class="mb-3">
    <div class="text-[10px] font-semibold text-[var(--text-weak)] uppercase tracking-[1.5px] mb-1 pl-0.5">壁纸</div>
    <div class="bg-[var(--card-bg)] border border-[var(--card-border)] rounded-lg">
      <!-- 类型选择 -->
      <div class="flex justify-between items-center px-3.5 py-2">
        <div class="text-xs font-medium text-[var(--text-muted)]">类型选择</div>
        <div class="flex gap-1">
          <button v-for="t in wpTypes" :key="t.value" @click="$emit('set-wp-type', t.value)"
            :class="s.wallpaperType === t.value
              ? 'bg-[var(--accent)] border-[var(--accent)] text-[var(--text-strong)]'
              : 'bg-[var(--input-bg)] border-[var(--input-border)] text-[var(--text)] hover:bg-[var(--card-border)]'"
            class="border rounded-md text-[11px] py-1 px-2.5 font-[inherit] cursor-pointer whitespace-nowrap transition-colors">{{ t.label }}</button>
        </div>
      </div>
    </div>

    <!-- 主题 -->
    <div v-if="s.wallpaperType === 'theme'" class="bg-[var(--card-bg)] border border-[var(--card-border)] rounded-lg mt-1.5">
      <div class="flex justify-between items-center px-3.5 py-2">
        <div class="text-xs font-medium text-[var(--text-muted)]">选择主题</div>
        <select v-model="s.theme" @change="go.saveWallpaperType('theme', s.theme)"
          class="bg-[var(--input-bg)] border border-[var(--input-border)] rounded-md text-[var(--text)] text-[11px] py-0.5 px-1.5 outline-none min-w-[80px] max-w-[160px] focus:border-[var(--input-border-focus)]">
          <option v-for="t in s.themes" :key="t.value" :value="t.value">{{ t.label }}</option>
        </select>
      </div>
      <div v-if="s.theme === 'text'" class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
        <div class="text-xs font-medium text-[var(--text-muted)]">自定义文字</div>
        <input type="text" v-model="s.wallpaperText" @input="debounced('wt', go.saveWallpaperText, s.wallpaperText)"
          placeholder="输入显示文字"
          class="bg-[var(--input-bg)] border border-[var(--input-border)] rounded-md text-[var(--text)] text-[11px] py-1 px-2 outline-none w-[140px] focus:border-[var(--input-border-focus)]">
      </div>
      <!-- 音频可视化设置 -->
      <template v-if="s.theme === 'audio-viz'">
        <div class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
          <div class="text-xs font-medium text-[var(--text-muted)]">可视化样式</div>
          <div class="flex flex-wrap gap-1 justify-end">
            <button v-for="st in audioVizStyles" :key="st.value"
              @click="s.audioVizStyle = st.value; go.saveAudioVizStyle(st.value)"
              :class="s.audioVizStyle === st.value
                ? 'bg-[var(--accent)] border-[var(--accent)] text-[var(--text-strong)]'
                : 'bg-[var(--input-bg)] border-[var(--input-border)] text-[var(--text)] hover:bg-[var(--card-border)]'"
              class="border rounded-md text-[11px] py-0.5 px-2 font-[inherit] cursor-pointer transition-colors">{{ st.label }}</button>
          </div>
        </div>
        <div class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
          <div class="text-xs font-medium text-[var(--text-muted)]">配色方案</div>
          <div class="flex gap-1">
            <button v-for="c in audioColors" :key="c.value"
              @click="s.audioColorScheme = c.value; go.saveAudioColorScheme(c.value)"
              :class="s.audioColorScheme === c.value
                ? 'bg-[var(--accent)] border-[var(--accent)] text-[var(--text-strong)]'
                : 'bg-[var(--input-bg)] border-[var(--input-border)] text-[var(--text)] hover:bg-[var(--card-border)]'"
              class="border rounded-md text-[11px] py-0.5 px-2 font-[inherit] cursor-pointer transition-colors">{{ c.label }}</button>
          </div>
        </div>
        <div class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
          <div class="text-xs font-medium text-[var(--text-muted)]">灵敏度</div>
          <input type="range" min="0.5" max="3" step="0.1" :value="s.audioSensitivity"
            @input="s.audioSensitivity = +($event.target as HTMLInputElement).value; debounced('as', go.saveAudioSensitivity, s.audioSensitivity)"
            class="w-[100px]">
        </div>
        <div class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
          <div class="text-xs font-medium text-[var(--text-muted)]">平滑度</div>
          <input type="range" min="0" max="0.95" step="0.05" :value="s.audioSmoothing"
            @input="s.audioSmoothing = +($event.target as HTMLInputElement).value; debounced('am', go.saveAudioSmoothing, s.audioSmoothing)"
            class="w-[100px]">
        </div>
      </template>
    </div>

    <!-- 本地图片 -->
    <div v-if="s.wallpaperType === 'image'" class="bg-[var(--card-bg)] border border-[var(--card-border)] rounded-lg mt-1.5">
      <div class="flex justify-between items-center px-3.5 py-2">
        <div class="text-[10px] text-[var(--text-weak)] truncate mr-2">{{ s.imagePath || '未选择图片' }}</div>
        <button class="btn" @click="onPickImage">选择图片</button>
      </div>
    </div>

    <!-- Bing -->
    <div v-if="s.wallpaperType === 'bing'" class="bg-[var(--card-bg)] border border-[var(--card-border)] rounded-lg mt-1.5">
      <div class="flex justify-between items-center px-3.5 py-2">
        <div class="flex items-center gap-2 min-w-0">
          <img v-if="bing.url" :src="bingThumb" class="w-16 h-10 object-cover rounded flex-shrink-0">
          <div class="min-w-0">
            <div class="text-xs font-medium text-[var(--text-muted)] truncate">{{ bing.copyright || 'Bing 每日壁纸' }}</div>
            <div class="text-[10px] text-[var(--text-weak)]">{{ bing.idx > 0 ? `${bing.idx} / ${bing.total}` : '' }}</div>
          </div>
        </div>
        <div class="flex gap-1 flex-shrink-0">
          <button class="btn-sm" @click="onBingPrev">&#9664;</button>
          <button class="btn-sm" @click="onBingNext">&#9654;</button>
          <button class="btn-sm" @click="onBingFav">{{ bing.fav ? '★' : '☆' }}</button>
        </div>
      </div>
      <div class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
        <div><div class="text-xs font-medium text-[var(--text-muted)]">定时切换</div><div class="text-[10px] text-[var(--text-weak)] mt-px">每小时自动切换壁纸</div></div>
        <ToggleSwitch v-model="s.bingAutoRefresh" />
      </div>
      <!-- 收藏列表 -->
      <div v-if="bingFavs.length" class="px-3.5 py-2 border-t border-[var(--card-divider)]">
        <div class="text-[10px] text-[var(--text-weak)] mb-1.5">收藏列表</div>
        <div class="grid grid-cols-4 gap-1.5">
          <div v-for="(f, i) in bingFavs" :key="i" class="cursor-pointer rounded overflow-hidden hover:opacity-80" @click="onBingSetByIdx(f.idx)">
            <img :src="f.thumb" class="w-full h-10 object-cover rounded">
          </div>
        </div>
      </div>
    </div>

    <!-- 纯色/渐变 -->
    <div v-if="s.wallpaperType === 'color'" class="bg-[var(--card-bg)] border border-[var(--card-border)] rounded-lg mt-1.5">
      <div class="flex justify-between items-center px-3.5 py-2">
        <div class="text-xs font-medium text-[var(--text-muted)]">选择颜色</div>
        <div class="flex gap-1">
          <button class="btn" @click="$emit('pick-solid')">纯色</button>
          <button class="btn" @click="$emit('pick-gradient')">渐变</button>
        </div>
      </div>
      <div v-if="currentColor.c1" class="flex justify-between items-center px-3.5 py-2 border-t border-[var(--card-divider)]">
        <div class="flex items-center gap-1.5">
          <span class="inline-block w-6 h-4 rounded-sm border border-[var(--input-border)]" :style="swatchStyle"></span>
          <span class="text-[10px] text-[var(--text-weak)]">当前颜色</span>
        </div>
        <button class="btn" @click="$emit('save-color')">收藏</button>
      </div>
    </div>
    <!-- 已收藏颜色 -->
    <div v-if="s.savedColors.length && s.wallpaperType === 'color'" class="flex flex-wrap gap-1.5 mt-1.5 px-0.5">
      <div v-for="(c, i) in s.savedColors" :key="i" class="color-swatch" :style="swatchOf(c)"
        @click="$emit('apply-color', i)" @contextmenu.prevent="$emit('remove-color', i)">
        <span class="del">&times;</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { go } from '../composables/useGoBridge'
import { debounced } from '../composables/useDebounce'
import ToggleSwitch from './ToggleSwitch.vue'
import type { SettingsData, BingState } from '@shared/types'

const props = defineProps<{
  s: SettingsData
  currentColor: { c1: string; c2: string; gradient: boolean }
}>()

defineEmits<{
  'set-wp-type': [type: string]
  'pick-solid': []
  'pick-gradient': []
  'save-color': []
  'apply-color': [idx: number]
  'remove-color': [idx: number]
}>()

const wpTypes = [
  { value: 'theme', label: '主题' },
  { value: 'image', label: '本地图片' },
  { value: 'bing', label: 'Bing' },
  { value: 'color', label: '纯色/渐变' },
]

const audioVizStyles = [
  { value: 'bars', label: '柱状' },
  { value: 'waveform', label: '波形' },
  { value: 'circular', label: '环形' },
  { value: 'particles', label: '粒子' },
  { value: 'ripples', label: '涟漪' },
  { value: 'text', label: '文字' },
  { value: 'stars', label: '星空' },
  { value: 'dna', label: 'DNA' },
  { value: 'matrix', label: '矩阵' },
  { value: 'jellyfish', label: '水母' },
  { value: 'aurora', label: '极光' },
]

const audioColors = [
  { value: 'neon', label: '霓虹' },
  { value: 'ocean', label: '海洋' },
  { value: 'fire', label: '火焰' },
  { value: 'rainbow', label: '彩虹' },
]

// Bing
const bing = ref<BingState>({ date: '', title: '', copyright: '', url: '', fav: false, idx: 0, total: 0 })
const bingThumb = ref('')
const bingFavs = ref<{ idx: number; thumb: string }[]>([])

async function loadBingInfo() {
  const raw = await go.getBingInfo()
  const st = JSON.parse(raw) as BingState
  bing.value = st
  if (st.url) {
    const t = st.url.replace('_1920x1080', '_400x240')
    bingThumb.value = t !== st.url ? t : await go.bingThumbDataURI(st.url.split('/').pop() || '')
  }
}

async function onBingPrev() { bing.value = JSON.parse(await go.bingPrev()) }
async function onBingNext() { bing.value = JSON.parse(await go.bingNext()) }
async function onBingFav() { bing.value = JSON.parse(await go.bingToggleFavorite()); await loadBingFavs() }
async function onBingSetByIdx(idx: number) { bing.value = JSON.parse(await go.bingSetByIdx(idx)) }

async function loadBingFavs() {
  const raw = await go.getBingFavorites()
  const list = JSON.parse(raw) as string[]
  bingFavs.value = await Promise.all(list.map(async f => ({
    idx: parseInt(f.match(/(\d+)/)?.[1] || '0', 10),
    thumb: await go.bingThumbDataURI(f)
  })))
}

watch(() => props.s.bingAutoRefresh, v => go.saveBingAutoRefresh(v))
watch(() => props.s.wallpaperType, t => {
  if (t === 'bing') { loadBingInfo(); loadBingFavs() }
}, { immediate: true })

async function onPickImage() {
  const p = await go.pickLocalImage()
  if (p) props.s.imagePath = p
}

// Color swatches
function gradientBg(c1: string, c2: string, gradient: boolean) {
  return { background: gradient && c2 ? `linear-gradient(135deg,${c1},${c2})` : c1 }
}
const swatchStyle = computed(() => props.currentColor.c1 ? gradientBg(props.currentColor.c1, props.currentColor.c2, props.currentColor.gradient) : {})
function swatchOf(c: { color1: string; color2: string; gradient: boolean }) { return gradientBg(c.color1, c.color2, c.gradient) }
</script>

<style scoped>
.btn {
  background: var(--input-bg); border: 1px solid var(--input-border);
  border-radius: 6px; color: var(--text); font-size: 11px; padding: 4px 10px;
  font-family: inherit; cursor: pointer; transition: background 0.15s; white-space: nowrap;
}
.btn:hover { background: var(--card-border); }
.btn-sm {
  background: var(--input-bg); border: 1px solid var(--input-border);
  border-radius: 6px; color: var(--text); font-size: 10px; padding: 3px 8px;
  font-family: inherit; cursor: pointer; white-space: nowrap;
}
.btn-sm:hover { background: var(--card-border); }
.color-swatch {
  width: 28px; height: 28px; border-radius: 6px; cursor: pointer;
  border: 2px solid transparent; transition: border-color 0.15s; position: relative;
}
.color-swatch:hover { border-color: var(--accent); }
.color-swatch .del {
  display: none; position: absolute; top: -6px; right: -6px;
  width: 14px; height: 14px; border-radius: 50%;
  background: #e53e3e; color: #fff; font-size: 9px; line-height: 14px;
  text-align: center; cursor: pointer;
}
.color-swatch:hover .del { display: block; }
</style>
