<template>
  <el-dialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="780px"
    align-center
    destroy-on-close
    class="proj-browse-dialog"
    @update:model-value="(v: boolean) => emit('update:modelValue', v)"
    @open="onOpen"
  >
    <div class="proj-browse">
      <!-- 顶栏：路径 + 快捷跳转 -->
      <div class="proj-browse-toolbar">
        <button class="proj-icon-btn" :disabled="!parent" title="返回上级" @click="goUp">
          <span class="proj-icon">←</span>
        </button>
        <button class="proj-icon-btn" title="刷新" @click="refresh">
          <span class="proj-icon">⟳</span>
        </button>
        <button class="proj-icon-btn" title="SimpleLite 主目录" @click="goCwd">
          <span class="proj-icon">⌂</span>
        </button>
        <el-input
          v-model="dir"
          size="small"
          spellcheck="false"
          class="proj-path-input"
          placeholder="输入或粘贴目录路径，回车跳转"
          @keyup.enter="refresh"
        >
          <template #prefix>
            <span class="proj-path-prefix">📁</span>
          </template>
        </el-input>
      </div>

      <el-alert
        v-if="error"
        type="error"
        :title="error"
        :closable="false"
        show-icon
        class="proj-error"
      />

      <!-- 双栏：左目录 / 右文件 -->
      <div class="proj-browse-body">
        <!-- 左栏：子目录 + 主目录 -->
        <div class="proj-browse-side">
          <div class="proj-side-title">服务端目录</div>
          <el-scrollbar class="proj-side-scroll">
            <button class="proj-side-btn proj-side-cwd" @click="goCwd">
              <span class="proj-side-icon">🏠</span>
              <span class="proj-side-text">SimpleLite 主目录</span>
            </button>
            <div v-if="parent" class="proj-side-section">
              <button class="proj-side-btn" @click="goUp">
                <span class="proj-side-icon">↑</span>
                <span class="proj-side-text">返回上级</span>
              </button>
            </div>
            <div class="proj-side-section">
              <div class="proj-side-section-title">子文件夹</div>
              <button
                v-for="d in subdirs"
                :key="d.fullPath"
                class="proj-side-btn"
                :class="{ 'proj-side-btn--active': false }"
                @dblclick="enterDir(d.fullPath)"
                @click="enterDir(d.fullPath)"
              >
                <span class="proj-side-icon">📁</span>
                <span class="proj-side-text" :title="d.name">{{ d.name }}</span>
              </button>
              <div v-if="subdirs.length === 0" class="proj-side-empty">无子文件夹</div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 右栏：JSON 文件列表 -->
        <div class="proj-browse-main">
          <el-table
            v-loading="loading"
            :data="jsons"
            size="small"
            height="380"
            highlight-current-row
            class="proj-browse-table"
            empty-text="该目录下没有 JSON 项目文件"
            @current-change="onRowSelect"
            @row-dblclick="onRowDbl"
          >
            <el-table-column width="36">
              <template #default>
                <span class="proj-file-icon">📄</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" min-width="220">
              <template #default="{ row }">
                <span class="proj-file-name">{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="大小" width="100">
              <template #default="{ row }">
                <span class="proj-mute">{{ formatSize(row.sizeBytes) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="modified" label="修改时间" width="160">
              <template #default="{ row }">
                <span class="proj-mute">{{ row.modified }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 底栏：文件名输入框 + 类型筛选 -->
      <div class="proj-browse-footer">
        <span class="proj-footer-label">{{ mode === 'load' ? '选中文件' : '保存为' }}</span>
        <el-input
          v-model="manualPath"
          size="small"
          :placeholder="mode === 'load'
            ? '在右侧选择 JSON 文件，或直接输入绝对路径'
            : '输入文件名（不写绝对路径则保存到当前目录）'"
          spellcheck="false"
          class="proj-manual-input"
        />
        <span class="proj-footer-type">JSON (*.json)</span>
      </div>
    </div>

    <template #footer>
      <div class="proj-footer-bar">
        <span class="proj-footer-tip">{{ footerTip }}</span>
        <span class="proj-footer-actions">
          <el-button @click="emit('update:modelValue', false)">取消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            :disabled="!canConfirm"
            @click="onConfirm"
          >
            {{ mode === 'load' ? '加载此文件' : '保存到此文件' }}
          </el-button>
        </span>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { mapEditApi } from '@/api/mapEdit'

interface BrowseRow {
  kind: 'dir' | 'file'
  name: string
  fullPath: string
  sizeBytes?: number
  modified?: string
}

const props = defineProps<{
  modelValue: boolean
  /** 'load' 用于「加载文件」对话框；'save' 用于「另存为」对话框（可选中 .json 或新建文件名）。 */
  mode: 'load' | 'save'
  /** 上次记住的路径，用于打开时初始定位。空字符串则用 SimpleLite CWD。 */
  initialPath?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', v: boolean): void
  (e: 'confirm', path: string): void
}>()

const dir = ref('')
const parent = ref<string | null>(null)
const subdirs = ref<BrowseRow[]>([])
const jsons = ref<BrowseRow[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const selected = ref<BrowseRow | null>(null)
const manualPath = ref('')
const cwdRoot = ref('')

const dialogTitle = computed(() =>
  props.mode === 'load' ? '加载项目（服务端目录）' : '保存项目（服务端目录）')

const canConfirm = computed(() => {
  if (manualPath.value.trim()) return true
  if (selected.value?.kind === 'file') return true
  if (props.mode === 'save' && dir.value) return true
  return false
})

const footerTip = computed(() => {
  if (props.mode === 'save')
    return manualPath.value
      ? `将保存到：${resolveSavePath()}`
      : `当前目录：${dir.value}`
  return selected.value
    ? `已选：${selected.value.fullPath}`
    : '请在右侧选中一个 JSON 文件，或输入绝对路径'
})

async function refresh() {
  loading.value = true
  error.value = null
  try {
    const r = await mapEditApi.projectBrowse(dir.value || undefined)
    dir.value = r.dir
    parent.value = r.parent
    subdirs.value = r.subdirs.map((d) => ({ kind: 'dir' as const, name: d.name, fullPath: d.fullPath }))
    jsons.value = r.jsons.map((f) => ({
      kind: 'file' as const,
      name: f.name,
      fullPath: f.fullPath,
      sizeBytes: f.sizeBytes,
      modified: f.modified
    }))
    if (!cwdRoot.value) cwdRoot.value = r.dir
    selected.value = null
  } catch (err) {
    error.value = (err as Error).message
  } finally {
    loading.value = false
  }
}

function goUp() {
  if (!parent.value) return
  dir.value = parent.value
  refresh()
}

function goCwd() {
  dir.value = ''
  refresh()
}

function enterDir(full: string) {
  dir.value = full
  refresh()
}

function onRowSelect(row: BrowseRow | null) {
  selected.value = row
  if (row?.kind === 'file') manualPath.value = row.fullPath
}

function onRowDbl(row: BrowseRow) {
  if (row.kind === 'file') onConfirm()
}

function resolveSavePath() {
  const m = manualPath.value.trim()
  if (!m) return `${dir.value}/project.current.json`
  // 如果用户写的是完整路径，直接用；否则当作 dir + filename。
  if (/^([A-Za-z]:[\\/]|\\\\|\/)/.test(m)) return m
  return `${dir.value.replace(/[\\/]+$/, '')}/${m.endsWith('.json') ? m : m + '.json'}`
}

function onConfirm() {
  if (props.mode === 'save') {
    const path = resolveSavePath()
    if (!path) {
      ElMessage.warning('请输入文件名或选中目标')
      return
    }
    emit('confirm', path)
    emit('update:modelValue', false)
    return
  }

  const path = manualPath.value.trim() || (selected.value?.kind === 'file' ? selected.value.fullPath : '')
  if (!path) {
    ElMessage.warning('请先选中一个 .json 文件，或直接输入路径')
    return
  }
  emit('confirm', path)
  emit('update:modelValue', false)
}

function onOpen() {
  selected.value = null
  manualPath.value = ''
  dir.value = props.initialPath ?? ''
  refresh()
}

function formatSize(bytes: number | undefined) {
  if (bytes == null) return '—'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}

watch(() => props.modelValue, (v) => {
  if (v) onOpen()
})
</script>

<style scoped>
.proj-browse-dialog :deep(.el-dialog__header) {
  padding: 14px 20px;
  margin-right: 0;
  border-bottom: 1px solid rgba(170, 110, 250, 0.15);
}
.proj-browse-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 14px;
  color: rgba(60, 30, 110, 0.95);
}
.proj-browse-dialog :deep(.el-dialog__body) {
  padding: 12px 16px 8px;
}

.proj-browse {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.proj-browse-toolbar {
  display: flex;
  gap: 6px;
  align-items: center;
}
.proj-icon-btn {
  appearance: none;
  border: 1px solid rgba(170, 110, 250, 0.25);
  background: rgba(245, 235, 255, 0.65);
  color: rgba(80, 40, 130, 0.85);
  width: 30px; height: 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex; align-items: center; justify-content: center;
  transition: background .14s, border-color .14s, color .14s;
}
.proj-icon-btn:hover:not(:disabled) {
  background: rgba(170, 110, 250, 0.20);
  border-color: rgba(170, 110, 250, 0.55);
  color: rgba(40, 10, 90, 0.95);
}
.proj-icon-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.proj-icon { font-size: 14px; line-height: 1; }
.proj-path-input { flex: 1; }
.proj-path-prefix { font-size: 12px; color: rgba(120, 80, 180, 0.7); }
.proj-error { margin: 0; }

.proj-browse-body {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 10px;
  height: 400px;
  border: 1px solid rgba(170, 110, 250, 0.18);
  border-radius: 8px;
  overflow: hidden;
  background: rgba(250, 245, 255, 0.50);
}

.proj-browse-side {
  display: flex; flex-direction: column;
  border-right: 1px solid rgba(170, 110, 250, 0.15);
  background: rgba(245, 238, 255, 0.65);
}
.proj-side-title {
  font-size: 11px;
  letter-spacing: 1px;
  color: rgba(120, 80, 180, 0.85);
  font-weight: 600;
  text-transform: uppercase;
  padding: 8px 10px;
  border-bottom: 1px solid rgba(170, 110, 250, 0.10);
  background: rgba(255, 255, 255, 0.45);
}
.proj-side-scroll { flex: 1; }
.proj-side-section { margin-top: 10px; padding: 0 6px; }
.proj-side-section:first-child { margin-top: 0; }
.proj-side-section-title {
  font-size: 10.5px;
  color: rgba(120, 80, 180, 0.7);
  padding: 6px 6px 2px;
  letter-spacing: 0.5px;
}
.proj-side-btn {
  appearance: none;
  border: 0;
  background: transparent;
  width: 100%;
  display: flex; align-items: center; gap: 6px;
  padding: 6px 8px;
  border-radius: 5px;
  font-size: 12.5px;
  color: rgba(60, 30, 110, 0.92);
  cursor: pointer;
  text-align: left;
  transition: background .12s;
}
.proj-side-btn:hover { background: rgba(170, 110, 250, 0.18); }
.proj-side-btn--active { background: rgba(170, 110, 250, 0.32); color: #fff; }
.proj-side-cwd {
  margin: 6px;
  background: rgba(170, 110, 250, 0.14);
  border: 1px solid rgba(170, 110, 250, 0.30);
}
.proj-side-cwd:hover { background: rgba(170, 110, 250, 0.28); }
.proj-side-icon { width: 16px; flex: none; text-align: center; }
.proj-side-text {
  flex: 1;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.proj-side-empty {
  font-size: 11.5px;
  color: rgba(120, 90, 160, 0.55);
  padding: 8px 12px;
  text-align: center;
}

.proj-browse-main { padding: 0; overflow: hidden; }
.proj-browse-table { width: 100%; }
.proj-file-icon { font-size: 14px; }
.proj-file-name {
  color: rgba(40, 10, 90, 0.95);
  font-weight: 500;
  font-size: 12.5px;
}
.proj-mute { color: rgba(120, 90, 160, 0.7); font-size: 11.5px; }

.proj-browse-footer {
  display: flex; align-items: center; gap: 8px;
  padding: 4px 0;
}
.proj-footer-label {
  font-size: 12px;
  color: rgba(80, 40, 130, 0.85);
  font-weight: 500;
  flex: none;
  min-width: 64px;
}
.proj-manual-input { flex: 1; }
.proj-footer-type {
  font-size: 11.5px;
  color: rgba(120, 90, 160, 0.7);
  flex: none;
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}

.proj-footer-bar {
  display: flex; align-items: center; justify-content: space-between;
}
.proj-footer-tip {
  font-size: 11.5px;
  color: rgba(120, 90, 160, 0.7);
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  max-width: 460px;
}
</style>
