<script setup>
import { computed } from 'vue'

const props = defineProps({
  node: { type: Object, default: null },
  breadcrumb: { type: Array, default: () => [] },
  rootNodes: { type: Array, default: () => [] },
  getFileIcon: { type: Function, default: () => 'file' }
})

const emit = defineEmits(['navigate'])

const fileExt = computed(() => {
  if (!props.node || props.node.type !== 'file') return ''
  const parts = props.node.name.split('.')
  return parts.length > 1 ? parts.pop().toLowerCase() : ''
})

const isMarkdown = computed(() => {
  return fileExt.value === 'md' || fileExt.value === 'markdown'
})

const isText = computed(() => {
  const textExts = ['txt', 'json', 'js', 'ts', 'css', 'html', 'py', 'vue', 'xml', 'yaml', 'yml', 'csv', 'log', 'sql', 'toml', 'ini', 'cfg', 'conf', 'sh', 'bat']
  return textExts.includes(fileExt.value) || isMarkdown.value
})

const isRoot = computed(() => !props.node)
const isFolder = computed(() => props.node && props.node.type === 'folder')

const folderItems = computed(() => {
  if (!isRoot.value && !isFolder.value) return []
  const items = isRoot.value ? props.rootNodes : (props.node.children || [])
  return [...items].sort((a, b) => {
    if (a.type !== b.type) return a.type === 'folder' ? -1 : 1
    return a.name.localeCompare(b.name)
  })
})

function navigateTo(id) {
  emit('navigate', id)
}

function navigateUp() {
  if (isRoot.value) return
  emit('navigate', props.node.parentId || null)
}

function formatDate(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const diff = Date.now() - date.getTime()
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff/60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff/3600000)}小时前`
  if (diff < 30 * 86400000) return `${Math.floor(diff/86400000)}天前`
  return date.toLocaleDateString()
}
</script>

<template>
  <div class="file-content">
    <div v-if="breadcrumb.length > 0" class="breadcrumb">
      <template v-for="(item, index) in breadcrumb" :key="item.id">
        <span
          v-if="item.type === 'folder'"
          class="breadcrumb-item"
          @click="navigateTo(item.id)"
        >{{ item.name }}</span>
        <span v-else class="breadcrumb-item breadcrumb-current">{{ item.name }}</span>
        <span v-if="index < breadcrumb.length - 1" class="breadcrumb-sep">/</span>
      </template>
    </div>

    <div v-if="isRoot || isFolder" class="content-directory-view">
      <div class="directory-list">
        <div class="directory-header">
          <div class="col-name">名称</div>
          <div class="col-date">更新时间</div>
        </div>
        
        <div v-if="!isRoot" class="directory-row" @click="navigateUp">
          <span class="col-icon">
            <span class="icon-folder"></span>
          </span>
          <div class="col-name name-folder">..</div>
          <div class="col-date"></div>
        </div>
        
        <div 
          v-for="item in folderItems" 
          :key="item.id" 
          class="directory-row"
          @click="navigateTo(item.id)"
        >
          <span class="col-icon">
            <span v-if="item.type==='folder'" class="icon-folder"></span>
            <span v-else :class="['icon-file', `icon-${getFileIcon(item.name)}`]"></span>
          </span>
          <div class="col-name" :class="item.type === 'folder' ? 'name-folder' : 'name-file'">{{ item.name }}</div>
          <div class="col-date" :title="new Date(item.updatedAt).toLocaleString()">{{ formatDate(item.updatedAt) }}</div>
        </div>
        
        <div v-if="folderItems.length === 0" class="directory-empty">
          <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
          </svg>
          <p>此文件夹为空</p>
        </div>
      </div>
    </div>

    <div v-else-if="isMarkdown" class="content-markdown">
      <div class="markdown-body" v-html="renderMarkdown(node.content || '')"></div>
    </div>

    <div v-else-if="isText" class="content-text">
      <pre class="text-content">{{ node.content || '' }}</pre>
    </div>

    <div v-else class="content-unsupported">
      <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"></circle>
        <line x1="12" y1="8" x2="12" y2="12"></line>
        <line x1="12" y1="16" x2="12.01" y2="16"></line>
      </svg>
      <p>暂不支持预览此文件类型</p>
      <p class="file-ext">.{{ fileExt }}</p>
    </div>
  </div>
</template>

<script>
function renderMarkdown(text) {
  if (!text) return ''
  let html = text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/^### (.+)$/gm, '<h3>$1</h3>')
    .replace(/^## (.+)$/gm, '<h2>$1</h2>')
    .replace(/^# (.+)$/gm, '<h1>$1</h1>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/`(.+?)`/g, '<code>$1</code>')
    .replace(/^\> (.+)$/gm, '<blockquote>$1</blockquote>')
    .replace(/^\- (.+)$/gm, '<li>$1</li>')
    .replace(/^(\d+)\. (.+)$/gm, '<li>$1. $2</li>')
    .replace(/\n\n/g, '</p><p>')
    .replace(/\n/g, '<br>')
  return `<p>${html}</p>`
}
</script>

<style scoped>
.file-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  font-size: 13px;
  color: var(--muted-text);
  border-bottom: 1px solid var(--panel-border);
  flex-shrink: 0;
}

.breadcrumb-item {
  cursor: pointer;
  color: var(--focus-ring);
}

.breadcrumb-item:hover {
  text-decoration: underline;
}

.breadcrumb-current {
  color: var(--app-text);
  cursor: default;
}

.breadcrumb-current:hover {
  text-decoration: none;
}

.breadcrumb-sep {
  color: var(--muted-text);
}

.content-unsupported {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--muted-text);
  padding: 32px;
}

.content-unsupported svg {
  opacity: 0.4;
}

.content-directory-view {
  flex: 1;
  padding: 24px 32px;
  overflow-y: auto;
  background: var(--app-bg);
}

.directory-list {
  max-width: 900px;
  margin: 0 auto;
  border: 1px solid var(--panel-border);
  border-radius: 8px;
  overflow: hidden;
  background: var(--panel-bg);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.directory-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: var(--ghost-code-bg);
  border-bottom: 1px solid var(--panel-border);
  font-size: 13px;
  font-weight: 600;
  color: var(--muted-text);
}

.directory-row {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  border-bottom: 1px solid var(--panel-border);
  cursor: pointer;
  transition: background 0.15s ease;
  font-size: 14px;
}

.directory-row:last-child {
  border-bottom: none;
}

.directory-row:hover {
  background: var(--ghost-code-bg);
}

.col-icon {
  width: 24px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.col-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--app-text);
}

.name-folder {
  font-weight: 500;
  color: var(--focus-ring);
}

.directory-row:hover .name-folder {
  text-decoration: underline;
}

.col-date {
  width: 120px;
  flex-shrink: 0;
  text-align: right;
  color: var(--muted-text);
  font-size: 13px;
}

.directory-empty {
  padding: 48px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  color: var(--muted-text);
  font-size: 14px;
}

.directory-empty svg {
  opacity: 0.3;
}

/* File Icons (Reused from FileTree) */
.icon-file,
.icon-folder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

.icon-folder::before {
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  background: url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%2354aeff' d='M0 2.5A1.5 1.5 0 011.5 1h2.793a.5.5 0 01.353.146l1.5 1.5a.5.5 0 00.354.146H13.5A1.5 1.5 0 0115 4.5v7.5a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 011 12v-9.5z'/%3E%3C/svg%3E") no-repeat center;
  background-size: contain;
}

[data-theme='dark'] .icon-folder::before {
  background: url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%2358a6ff' d='M0 2.5A1.5 1.5 0 011.5 1h2.793a.5.5 0 01.353.146l1.5 1.5a.5.5 0 00.354.146H13.5A1.5 1.5 0 0115 4.5v7.5a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 011 12v-9.5z'/%3E%3C/svg%3E") no-repeat center;
  background-size: contain;
}

.icon-markdown::before {
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  background: url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%236e7781' d='M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15V4.15C16 3.52 15.48 3 14.85 3zM9 11H7.5V8.5L6.25 10l-1.25-1.5V11H3.5V5H5l1.25 1.5L7.5 5H9v6zm4-2.5c0 .28-.22.5-.5.5h-1v1c0 .28-.22.5-.5.5s-.5-.22-.5-.5v-1h-1c-.28 0-.5-.22-.5-.5s.22-.5.5-.5h1v-1c0-.28.22-.5.5-.5s.5.22.5.5v1h1c.28 0 .5.22.5.5z'/%3E%3C/svg%3E") no-repeat center;
  background-size: contain;
}

.icon-text::before,
.icon-json::before,
.icon-file::before {
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  background: url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%236e7781' d='M3.75 1.5a.25.25 0 00-.25.25v12.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V4.664a.25.25 0 00-.073-.177l-2.914-2.914a.25.25 0 00-.177-.073H3.75zM3 1.75C3 .784 3.784 0 4.75 0h5.339c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0113 16H4.75A1.75 1.75 0 013 14.25V1.75z'/%3E%3C/svg%3E") no-repeat center;
  background-size: contain;
}

.file-ext {
  font-family: monospace;
  font-size: 0.85rem;
  background: var(--ghost-code-bg);
  padding: 4px 8px;
  border-radius: 4px;
}

.content-markdown {
  flex: 1;
  overflow-y: auto;
  padding: 24px 32px;
}

.markdown-body {
  max-width: 800px;
  margin: 0 auto;
  line-height: 1.7;
  color: var(--app-text);
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3 {
  margin-top: 24px;
  margin-bottom: 12px;
  font-weight: 600;
  line-height: 1.3;
}

.markdown-body h1 { font-size: 1.75rem; border-bottom: 1px solid var(--panel-border); padding-bottom: 8px; }
.markdown-body h2 { font-size: 1.4rem; border-bottom: 1px solid var(--panel-border); padding-bottom: 6px; }
.markdown-body h3 { font-size: 1.15rem; }

.markdown-body strong { font-weight: 600; }
.markdown-body em { font-style: italic; }

.markdown-body code {
  background: var(--code-inline-bg);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.9em;
  font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
  color: var(--code-text);
}

.markdown-body blockquote {
  border-left: 3px solid var(--focus-ring);
  padding-left: 16px;
  margin: 12px 0;
  color: var(--muted-text);
}

.markdown-body li {
  margin-left: 20px;
  list-style: disc;
}

.content-text {
  flex: 1;
  overflow: auto;
  padding: 16px;
}

.text-content {
  margin: 0;
  padding: 16px;
  background: var(--code-block-bg);
  border: 1px solid var(--code-block-border);
  border-radius: 8px;
  font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.6;
  color: var(--code-text);
  white-space: pre-wrap;
  word-break: break-word;
  overflow: auto;
  max-width: 100%;
}

.content-markdown::-webkit-scrollbar,
.content-text::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.content-markdown::-webkit-scrollbar-thumb,
.content-text::-webkit-scrollbar-thumb {
  background: var(--scrollbar-thumb);
  border-radius: 4px;
}

.content-markdown::-webkit-scrollbar-thumb:hover,
.content-text::-webkit-scrollbar-thumb:hover {
  background: var(--scrollbar-thumb-hover);
}
</style>
