<template>
  <section class="pro-block-shell" :class="[`is-${stage}`, { 'is-busy': isBusy, 'has-content': Boolean(displayContent) }]">
    <button
      v-if="isIdle"
      type="button"
      class="pro-block-capsule"
      :title="title"
      @mousedown.stop.prevent
      @click.stop="handleActivate"
    >
      <span class="pro-block-orbit" aria-hidden="true"></span>
      <span class="pro-block-badge">PRO</span>
      <span class="pro-block-label">{{ t('proStart') || '开始 Pro 生成' }}</span>
    </button>

    <div v-else class="pro-block-panel">
      <div class="pro-block-header">
        <div class="pro-block-heading">
          <span class="pro-block-orbit" aria-hidden="true"></span>
          <div>
            <h3>{{ title }}</h3>
            <p>{{ statusText }}</p>
          </div>
        </div>
        <div class="pro-block-status">
          <span v-if="isThinking" class="pro-thinking-pill">
            <span class="pro-spinner" aria-hidden="true"></span>
            {{ t('proThinking') || '思考中' }}
          </span>
          <span v-else-if="isBusy" class="pro-spinner" aria-hidden="true"></span>
        </div>
      </div>

      <div class="pro-instruction">
        <button type="button" class="pro-fold-btn" @mousedown.stop.prevent @click.stop="handleToggleInstruction">
          <span>{{ instructionExpanded ? (t('proHideInstruction') || '隐藏指令') : (t('proShowInstruction') || '查看指令') }}</span>
          <span class="pro-chevron" :class="{ open: instructionExpanded }">⌄</span>
        </button>
        <Transition name="pro-fold">
          <div v-if="instructionExpanded" class="pro-instruction-editor">
            <textarea
              :value="instruction"
              :disabled="isBusy"
              :placeholder="t('proInstructionPlaceholder') || '输入隐藏 Pro 指令'"
              @input="handleInstructionInput"
              @mousedown.stop
              @keydown.stop
            ></textarea>
          </div>
        </Transition>
      </div>

      <div ref="bodyRef" class="pro-block-body" @scroll="handleBodyScroll">
        <Transition name="pro-thinking-fade">
          <div v-if="isThinking" class="pro-thinking-row">
            <span class="pro-spinner" aria-hidden="true"></span>
            <span>{{ t('proThinking') || '思考中' }}</span>
          </div>
        </Transition>

        <div v-if="errorMessage" class="pro-error-box">
          {{ errorMessage }}
        </div>

        <div v-if="!displayContent" class="pro-block-placeholder">
          <strong>{{ placeholderTitle }}</strong>
          <span>{{ placeholderText }}</span>
        </div>
        <div v-else class="pro-block-preview">
          <MarkdownPreview :content="displayContent" />
        </div>
      </div>

      <div class="pro-block-footer">
        <div class="pro-version-controls" v-if="versionCount > 1">
          <button type="button" class="pro-icon-btn" :disabled="!canPrevVersion" @mousedown.stop.prevent @click.stop="handlePrevVersion">‹</button>
          <span>{{ activeVersion + 1 }} / {{ versionCount }}</span>
          <button type="button" class="pro-icon-btn" :disabled="!canNextVersion" @mousedown.stop.prevent @click.stop="handleNextVersion">›</button>
        </div>

        <div class="pro-block-actions">
          <button v-if="isBusy" type="button" class="pro-text-btn" @mousedown.stop.prevent @click.stop="handleCancel">{{ t('cancel') || '取消' }}</button>
          <button v-else type="button" class="pro-text-btn" @mousedown.stop.prevent @click.stop="handleDiscard">{{ t('discard') || '放弃' }}</button>
          <button
            v-if="!isBusy"
            type="button"
            class="pro-secondary-btn"
            @mousedown.stop.prevent
            @click.stop="handleRedo"
          >
            {{ t('proRetry') || '重试' }}
          </button>
          <button
            v-if="!isBusy"
            type="button"
            class="pro-primary-btn"
            :disabled="!canAccept"
            @mousedown.stop.prevent
            @click.stop="handleAccept"
          >
            {{ t('accept') || '接受' }}
          </button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import MarkdownPreview from './MarkdownPreview.vue'

const props = defineProps({
  stage: { type: String, default: 'idle' },
  previewContent: { type: String, default: '' },
  activeContent: { type: String, default: '' },
  errorMessage: { type: String, default: '' },
  isBusy: { type: Boolean, default: false },
  isThinking: { type: Boolean, default: false },
  title: { type: String, default: 'PRO 模式' },
  instruction: { type: String, default: '' },
  instructionExpanded: { type: Boolean, default: false },
  activeVersion: { type: Number, default: 0 },
  versionCount: { type: Number, default: 0 },
  canAccept: { type: Boolean, default: false },
  activateAction: { type: Function, default: null },
  cancelAction: { type: Function, default: null },
  discardAction: { type: Function, default: null },
  redoAction: { type: Function, default: null },
  acceptAction: { type: Function, default: null },
  prevVersionAction: { type: Function, default: null },
  nextVersionAction: { type: Function, default: null },
  toggleInstructionAction: { type: Function, default: null },
  updateInstructionAction: { type: Function, default: null },
  t: { type: Function, default: (key) => key },
})

const bodyRef = ref(null)
const shouldAutoScroll = ref(true)

const isIdle = computed(() => props.stage === 'idle' && !props.previewContent && !props.activeContent && !props.errorMessage)
const displayContent = computed(() => props.previewContent || props.activeContent || '')
const canPrevVersion = computed(() => props.activeVersion > 0)
const canNextVersion = computed(() => props.activeVersion < props.versionCount - 1)
const t = (key) => props.t?.(key)

const statusText = computed(() => {
  if (props.stage === 'queued') return t('proQueued') || '正在排队等待'
  if (props.stage === 'thinking') return t('proThinking') || '思考中'
  if (props.stage === 'streaming') return t('proStreaming') || '正在生成'
  if (props.stage === 'error') return t('proError') || '生成失败'
  if (props.stage === 'cancelled') return t('proCancelled') || '已取消，可接受当前草稿'
  return t('proDone') || '生成完成'
})

const placeholderTitle = computed(() => {
  if (props.stage === 'queued') return t('proQueued') || '正在排队'
  if (props.stage === 'thinking') return t('proThinking') || '思考中'
  if (props.stage === 'error') return t('proError') || '生成失败'
  return t('proWaiting') || '等待 Pro 生成'
})

const placeholderText = computed(() => {
  if (props.stage === 'queued') return t('proQueuedHint') || '轮到此请求后会自动开始。'
  if (props.stage === 'thinking') return t('proThinkingHint') || '模型正在思考，真实 thinking 内容已隐藏。'
  if (props.stage === 'error') return t('proRetryHint') || '请重试，或调整上下文和指令。'
  return t('proWaitingHint') || '点击开始生成，结果会在这里流式展开。'
})

const handleBodyScroll = () => {
  const el = bodyRef.value
  if (!el) return
  shouldAutoScroll.value = el.scrollTop + el.clientHeight >= el.scrollHeight - 24
}

watch(
  () => props.previewContent,
  async () => {
    if (!shouldAutoScroll.value) return
    await nextTick()
    const el = bodyRef.value
    if (el) el.scrollTop = el.scrollHeight
  }
)

const handleActivate = () => props.activateAction?.()
const handleCancel = () => props.cancelAction?.()
const handleDiscard = () => props.discardAction?.()
const handleRedo = () => props.redoAction?.()
const handleAccept = () => props.acceptAction?.()
const handlePrevVersion = () => props.prevVersionAction?.()
const handleNextVersion = () => props.nextVersionAction?.()
const handleToggleInstruction = () => props.toggleInstructionAction?.()
const handleInstructionInput = (event) => props.updateInstructionAction?.(event.target.value)
</script>

<style scoped>
.pro-block-shell {
  width: 100%;
  margin: 22px 0;
  color: var(--app-text);
}

.pro-block-capsule,
.pro-block-panel {
  position: relative;
  overflow: hidden;
  isolation: isolate;
}

.pro-block-capsule {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  padding: 11px 18px;
  border: 1px solid rgba(56, 189, 248, 0.58);
  border-radius: 999px;
  background: linear-gradient(135deg, #08111f 0%, #143a63 52%, #3b1d74 100%);
  color: #ffffff;
  box-shadow: 0 14px 32px rgba(14, 165, 233, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.14);
  cursor: pointer;
  touch-action: manipulation;
  transition: transform 0.18s ease, box-shadow 0.18s ease;
}

.pro-block-capsule:hover {
  transform: translateY(-1px);
  box-shadow: 0 20px 42px rgba(14, 165, 233, 0.28), inset 0 1px 0 rgba(255, 255, 255, 0.16);
}

.pro-block-panel {
  border: 1px solid rgba(148, 163, 184, 0.28);
  border-radius: 8px;
  background: color-mix(in srgb, var(--panel-bg) 96%, var(--app-bg) 4%);
  box-shadow: 0 16px 36px rgba(2, 8, 23, 0.12);
}

.pro-block-panel::before {
  content: none;
}

.pro-block-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding: 18px 18px 10px;
}

.pro-block-heading {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.pro-block-heading h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 750;
}

.pro-block-heading p {
  margin: 3px 0 0;
  color: var(--muted-text);
  font-size: 13px;
}

.pro-block-orbit {
  width: 20px;
  height: 20px;
  border-radius: 999px;
  background: conic-gradient(from 90deg, #38bdf8, #a855f7, #22c55e, #38bdf8);
  box-shadow: 0 0 18px rgba(56, 189, 248, 0.45);
  animation: pro-spin 1.8s linear infinite;
  flex: 0 0 auto;
}

.pro-block-badge {
  font-size: 12px;
  font-weight: 850;
  letter-spacing: 0.08em;
}

.pro-block-label {
  font-size: 14px;
  font-weight: 700;
}

.pro-block-status,
.pro-thinking-pill {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.pro-thinking-pill {
  padding: 6px 10px;
  border: 1px solid rgba(56, 189, 248, 0.22);
  border-radius: 999px;
  color: var(--app-text);
  background: rgba(56, 189, 248, 0.08);
  font-size: 12px;
}

.pro-spinner {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid rgba(56, 189, 248, 0.18);
  border-top-color: #38bdf8;
  animation: pro-spin 0.8s linear infinite;
  flex: 0 0 auto;
}

.pro-instruction {
  padding: 0 18px 10px;
}

.pro-fold-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  border: 0;
  padding: 5px 0;
  background: transparent;
  color: var(--muted-text);
  cursor: pointer;
  font-size: 12px;
}

.pro-chevron {
  transition: transform 0.16s ease;
}

.pro-chevron.open {
  transform: rotate(180deg);
}

.pro-instruction-editor textarea {
  width: 100%;
  min-height: 72px;
  resize: vertical;
  border: 1px solid rgba(56, 189, 248, 0.22);
  border-radius: 8px;
  padding: 10px 12px;
  background: color-mix(in srgb, var(--app-bg) 88%, transparent);
  color: var(--app-text);
  outline: none;
  font: inherit;
  -webkit-overflow-scrolling: touch;
}

.pro-block-body {
  max-height: min(52vh, 520px);
  overflow: auto;
  overflow-x: hidden;
  overscroll-behavior-y: contain;
  padding: 0 18px 14px;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

.pro-thinking-row,
.pro-error-box,
.pro-block-placeholder,
.pro-block-preview {
  border-radius: 8px;
  border: 1px solid rgba(148, 163, 184, 0.18);
  background: color-mix(in srgb, var(--app-bg) 82%, transparent);
}

.pro-thinking-row {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  padding: 8px 10px;
  color: var(--muted-text);
  font-size: 13px;
}

.pro-error-box {
  margin-bottom: 10px;
  padding: 10px 12px;
  border-color: rgba(239, 68, 68, 0.28);
  color: #dc2626;
}

.pro-block-placeholder {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 18px;
  color: var(--muted-text);
}

.pro-block-placeholder strong {
  color: var(--app-text);
}

.pro-block-preview {
  overflow: hidden;
}

.pro-block-preview :deep(.preview-container) {
  height: auto;
  min-height: 0;
  padding: 16px 18px;
  overflow: auto;
  overscroll-behavior-y: contain;
  background: transparent;
  color: var(--app-text);
}

.pro-block-preview :deep(.preview-container p),
.pro-block-preview :deep(.preview-container li),
.pro-block-preview :deep(.preview-container blockquote),
.pro-block-preview :deep(.preview-container td),
.pro-block-preview :deep(.preview-container th) {
  color: inherit;
}

.pro-block-preview :deep(.preview-container blockquote) {
  border-left-color: rgba(148, 163, 184, 0.5);
  color: var(--muted-text);
}

.pro-block-preview :deep(.preview-container code),
.pro-block-preview :deep(.preview-container pre) {
  background: color-mix(in srgb, var(--app-bg) 78%, var(--app-text) 8%);
  color: var(--app-text);
}

.pro-block-preview :deep(.preview-container th),
.pro-block-preview :deep(.preview-container td) {
  border-color: rgba(148, 163, 184, 0.35);
}

.pro-block-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 0 18px 18px;
}

.pro-version-controls,
.pro-block-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pro-version-controls {
  color: var(--muted-text);
  font-size: 12px;
}

.pro-icon-btn,
.pro-text-btn,
.pro-secondary-btn,
.pro-primary-btn {
  min-height: 34px;
  border-radius: 8px;
  border: 1px solid rgba(148, 163, 184, 0.24);
  background: color-mix(in srgb, var(--app-bg) 82%, transparent);
  color: var(--app-text);
  cursor: pointer;
  touch-action: manipulation;
  transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease;
}

.pro-icon-btn {
  width: 34px;
  font-size: 20px;
}

.pro-text-btn,
.pro-secondary-btn,
.pro-primary-btn {
  padding: 0 14px;
}

.pro-primary-btn {
  border-color: rgba(56, 189, 248, 0.58);
  background: linear-gradient(135deg, #0284c7, #7c3aed);
  color: #fff;
}

.pro-secondary-btn:hover:not(:disabled),
.pro-text-btn:hover:not(:disabled),
.pro-icon-btn:hover:not(:disabled),
.pro-primary-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  border-color: rgba(56, 189, 248, 0.5);
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.48;
}

.pro-fold-enter-active,
.pro-fold-leave-active,
.pro-thinking-fade-enter-active,
.pro-thinking-fade-leave-active {
  transition: opacity 0.18s ease, transform 0.18s ease;
}

.pro-fold-enter-from,
.pro-fold-leave-to,
.pro-thinking-fade-enter-from,
.pro-thinking-fade-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}

@keyframes pro-spin {
  to { transform: rotate(360deg); }
}

@keyframes pro-scan {
  0%, 40% { transform: translateX(-100%); opacity: 0; }
  55% { opacity: 1; }
  100% { transform: translateX(100%); opacity: 0; }
}

@media (max-width: 640px) {
  .pro-block-shell {
    margin: 14px 0;
  }

  .pro-block-capsule {
    width: 100%;
    justify-content: center;
    min-height: 48px;
  }

  .pro-block-panel {
    width: 100%;
  }

  .pro-block-header,
  .pro-block-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .pro-block-header {
    padding: 14px 14px 8px;
  }

  .pro-instruction {
    padding: 0 14px 8px;
  }

  .pro-instruction-editor textarea {
    min-height: 96px;
    font-size: 16px;
  }

  .pro-block-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    width: 100%;
  }

  .pro-block-body {
    max-height: 42vh;
    padding: 0 14px 12px;
  }

  .pro-block-preview :deep(.preview-container) {
    padding: 12px;
    overflow-wrap: anywhere;
  }

  .pro-block-footer {
    padding: 0 14px 14px;
  }

  .pro-version-controls {
    justify-content: center;
  }

  .pro-icon-btn,
  .pro-text-btn,
  .pro-secondary-btn,
  .pro-primary-btn {
    min-height: 44px;
    width: 100%;
  }

  .pro-text-btn {
    grid-column: span 1;
  }
}

@media (prefers-reduced-motion: reduce) {
  .pro-block-panel::before,
  .pro-block-orbit,
  .pro-spinner {
    animation: none;
  }

  .pro-block-capsule,
  .pro-icon-btn,
  .pro-text-btn,
  .pro-secondary-btn,
  .pro-primary-btn,
  .pro-chevron {
    transition: none;
  }

  .pro-block-body {
    scroll-behavior: auto;
  }
}
</style>
