<template>
  <div
    class="insight-panel-shell"
    :class="{ collapsed: !ui.showInsightPanel }"
    :aria-hidden="(!ui.showInsightPanel).toString()"
  >
    <aside class="insight-panel">
    <div
      v-if="!ui.isKnowledgeSession"
      class="insight-head"
      :class="{ 'review-mode': ui.activeReviewPayload || ui.isReviewFlowDrawer }"
    >
      <div>
        <div v-if="!ui.activeReviewPayload && !ui.isReviewFlowDrawer" class="insight-head-eyebrow">
          <span class="intent-pill" :class="ui.currentInsight.intent">{{ ui.currentIntentLabel }}</span>
        </div>
        <div v-else class="review-insight-title-row">
          <div class="review-insight-title-copy">
            <i v-if="!ui.activeReviewPayload && ui.isReviewFlowDrawer" :class="ui.reviewFlowDrawerIcon" class="title-icon"></i>
            <h3>{{ ui.reviewDrawerTitle }}</h3>
          </div>
        </div>
        <h3 v-if="!ui.activeReviewPayload && !ui.isReviewFlowDrawer">{{ ui.currentInsight.title }}</h3>
        <p v-if="!ui.activeReviewPayload && !ui.isReviewFlowDrawer">{{ ui.currentInsight.summary }}</p>
      </div>

      <div v-if="ui.activeReviewPayload" class="review-insight-tools">
        <button
          v-if="ui.activeReviewPayload && ui.reviewOverviewDrawerAvailable"
          type="button"
          class="review-insight-switch-icon-btn"
          :class="{
            available: true,
            active: ui.isReviewOverviewDrawer
          }"
          :disabled="ui.submitting || ui.reviewActionBusy"
          title="报销识别核对"
          aria-label="报销识别核对"
          @click="ui.switchToReviewOverviewDrawer"
        >
          <i :class="ui.isReviewOverviewDrawer ? 'mdi mdi-clipboard-check' : 'mdi mdi-clipboard-check-outline'"></i>
        </button>

        <button
          v-if="ui.activeReviewPayload && ui.reviewDocumentDrawerAvailable"
          type="button"
          class="review-insight-switch-icon-btn"
          :class="{
            available: ui.reviewDocumentDrawerAvailable,
            active: ui.reviewDocumentDrawerAvailable && ui.isReviewDocumentDrawer
          }"
          :disabled="ui.submitting || ui.reviewActionBusy"
          title="单据识别"
          aria-label="单据识别"
          @click="ui.toggleReviewDocumentDrawer"
        >
          <i :class="ui.reviewDocumentDrawerIcon"></i>
        </button>

        <button
          v-if="ui.activeReviewPayload && ui.reviewRiskDrawerAvailable"
          type="button"
          class="review-insight-switch-icon-btn risk"
          :class="{
            available: ui.reviewRiskDrawerAvailable,
            active: ui.reviewRiskDrawerAvailable && ui.isReviewRiskDrawer
          }"
          :disabled="ui.submitting || ui.reviewActionBusy"
          title="显示风险"
          aria-label="显示风险"
          @click="ui.toggleReviewRiskDrawer"
        >
          <i :class="ui.reviewRiskDrawerIcon"></i>
        </button>

        <button
          type="button"
          class="review-insight-switch-icon-btn flow"
          :class="{
            available: ui.reviewFlowDrawerAvailable,
            active: ui.reviewFlowDrawerAvailable && ui.isReviewFlowDrawer,
            running: ui.flowOverallStatusTone === 'running'
          }"
          :disabled="!ui.reviewFlowDrawerAvailable || ui.submitting || ui.reviewActionBusy"
          title="调用流程"
          aria-label="调用流程"
          @click="ui.toggleReviewFlowDrawer"
        >
          <i :class="ui.reviewFlowDrawerIcon"></i>
        </button>
      </div>

      <div class="confidence-card" v-if="!ui.activeReviewPayload && !ui.isReviewFlowDrawer">
        <span>{{ ui.currentInsight.metricLabel }}</span>
        <strong>{{ ui.currentInsight.metricValue }}</strong>
      </div>
    </div>

    <Transition name="insight-switch" mode="out-in">
      <div
        :key="`${ui.activeSessionType}-${ui.currentInsight.intent}-${ui.currentInsight.title}-${ui.reviewDrawerMode}`"
        class="insight-body"
        :class="{ 'document-review-body': ui.isReviewDocumentDrawer }"
      >
        <template v-if="ui.isKnowledgeSession">
          <section class="insight-card knowledge-hot-card">
            <div class="card-head">
              <h4>热门问题 Top 10</h4>
            </div>
            <div class="knowledge-question-list">
              <button
                v-for="(item, index) in ui.hotKnowledgeQuestions"
                :key="item"
                type="button"
                class="knowledge-question-btn"
                :disabled="ui.submitting || ui.reviewActionBusy || ui.deleteSessionBusy || ui.sessionSwitchBusy"
                @click="ui.askHotKnowledgeQuestion(item)"
              >
                <span
                  class="knowledge-question-index"
                  :class="ui.resolveKnowledgeRankTone(index)"
                >
                  {{ ui.resolveKnowledgeRankLabel(index) }}
                </span>
                <span class="knowledge-question-copy">{{ item }}</span>
                <i class="mdi mdi-arrow-top-right"></i>
              </button>
            </div>
          </section>
        </template>

        <template v-else-if="ui.isReviewFlowDrawer">
          <section class="review-flow-panel">
            <div class="review-flow-summary">
              <span class="flow-status-chip" :class="ui.flowOverallStatusTone">{{ ui.flowOverallStatusText }}</span>
              <span>总耗时 {{ ui.flowTotalDurationText }}</span>
              <button
                type="button"
                class="flow-icon-btn"
                :disabled="!ui.flowRunId || ui.flowRefreshBusy"
                title="刷新流程"
                aria-label="刷新流程"
                @click="ui.refreshFlowRunDetail"
              >
                <i :class="ui.flowRefreshBusy ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-refresh'"></i>
              </button>
            </div>

            <TransitionGroup
              v-if="(ui.visibleFlowSteps || ui.flowSteps).length"
              name="el-fade-in-linear"
              tag="div"
              class="review-flow-list"
            >
              <article
                v-for="(step, index) in (ui.visibleFlowSteps || ui.flowSteps)"
                :key="step.key"
                class="flow-step-item"
                :class="step.status"
                :style="resolveFlowStepStyle(index)"
              >
                <div class="flow-step-rail">
                  <span>{{ index + 1 }}</span>
                </div>

                <div class="flow-step-card">
                  <header>
                    <strong>{{ step.title }}</strong>
                    <div class="flow-step-side">
                      <time>{{ ui.formatFlowStepDuration(step) }}</time>
                    </div>
                  </header>
                  <p class="flow-step-detail">{{ ui.resolveFlowStepDetail(step) }}</p>
                  <p v-if="step.error" class="flow-step-error">{{ step.error }}</p>
                </div>
              </article>
            </TransitionGroup>

            <div v-else class="flow-empty-state compact">
              <i class="mdi mdi-timeline-question-outline"></i>
              <strong>暂无识别流程</strong>
              <p>发起识别后，这里会显示调用步骤和耗时。</p>
            </div>
          </section>
        </template>

        <template v-else-if="ui.currentInsight.intent === 'agent' && ui.currentInsight.agent">
          <template v-if="ui.activeReviewPayload">
            <template v-if="ui.reviewOverviewDrawerAvailable && !ui.isReviewDocumentDrawer && !ui.isReviewRiskDrawer && !ui.isReviewFlowDrawer">
              <section class="review-side-card review-side-overview-card">
                <div class="review-side-intent-row">
                  <i class="mdi mdi-account-outline"></i>
                  <span>用户意图：</span>
                  <strong>{{ ui.reviewIntentText }}</strong>
                </div>
                <section class="review-side-grid compact">
                  <article
                    v-for="item in ui.reviewFactCards"
                    :key="item.key"
                    class="review-side-metric-card"
                    :class="{
                      editable: item.editor,
                      editing: ui.reviewInlineEditorKey === item.key,
                      invalid: Boolean(ui.reviewInlineErrors[item.key]),
                      wide: item.wide
                    }"
                    @click="ui.openInlineReviewEditor(item.key)"
                  >
                    <span class="review-side-metric-icon">
                      <i :class="item.icon"></i>
                    </span>
                    <div class="review-side-metric-copy">
                      <small>{{ item.label }}</small>
                      <template v-if="ui.reviewInlineEditorKey === item.key && item.editor === 'date'">
                        <input
                          v-model="ui.reviewInlineForm[item.modelKey]"
                          class="review-inline-input"
                          :class="{ invalid: Boolean(ui.reviewInlineErrors[item.key]) }"
                          type="text"
                          :placeholder="`仅支持 ${ui.DATE_INPUT_FORMAT}`"
                          @click.stop
                          @input="ui.clearInlineReviewFieldError(item.key)"
                          @blur="ui.commitInlineReviewEditor"
                          @keydown.enter.prevent="ui.commitInlineReviewEditor"
                        />
                      </template>
                      <template v-else-if="ui.reviewInlineEditorKey === item.key && item.editor === 'amount'">
                        <input
                          v-model="ui.reviewInlineForm[item.modelKey]"
                          class="review-inline-input"
                          :class="{ invalid: Boolean(ui.reviewInlineErrors[item.key]) }"
                          type="text"
                          :placeholder="item.placeholder"
                          @click.stop
                          @input="ui.clearInlineReviewFieldError(item.key)"
                          @blur="ui.commitInlineReviewEditor"
                          @keydown.enter.prevent="ui.commitInlineReviewEditor"
                        />
                      </template>
                      <template v-else-if="ui.reviewInlineEditorKey === item.key && item.editor === 'text'">
                        <input
                          v-model="ui.reviewInlineForm[item.modelKey]"
                          class="review-inline-input"
                          :class="{ invalid: Boolean(ui.reviewInlineErrors[item.key]) }"
                          type="text"
                          :placeholder="item.placeholder"
                          @click.stop
                          @input="ui.clearInlineReviewFieldError(item.key)"
                          @blur="ui.commitInlineReviewEditor"
                          @keydown.enter.prevent="ui.commitInlineReviewEditor"
                        />
                      </template>
                      <template v-else-if="ui.reviewInlineEditorKey === item.key && item.editor === 'textarea'">
                        <textarea
                          v-model="ui.reviewInlineForm[item.modelKey]"
                          class="review-inline-input review-inline-textarea"
                          :class="{ invalid: Boolean(ui.reviewInlineErrors[item.key]) }"
                          :placeholder="item.placeholder"
                          rows="3"
                          @click.stop
                          @input="ui.clearInlineReviewFieldError(item.key)"
                          @blur="ui.commitInlineReviewEditor"
                          @keydown.enter.stop
                        ></textarea>
                      </template>
                      <template v-else-if="ui.reviewInlineEditorKey === item.key && item.editor === 'select'">
                        <div class="review-inline-select-list" @click.stop>
                          <button
                            v-for="scene in ui.REVIEW_SCENE_OPTIONS"
                            :key="scene"
                            type="button"
                            class="review-inline-select-option"
                            :class="{ active: ui.reviewInlineForm.scene_label === scene }"
                            @click.stop="ui.selectInlineScene(scene)"
                          >
                            {{ scene }}
                          </button>
                          <input
                            v-if="ui.reviewInlineForm.scene_label === ui.REVIEW_SCENE_OTHER_OPTION"
                            v-model="ui.reviewInlineForm.reason_value"
                            class="review-inline-input review-inline-select-custom"
                            :class="{ invalid: Boolean(ui.reviewInlineErrors[item.key]) }"
                            type="text"
                            placeholder="请输入具体事由"
                            @click.stop
                            @input="ui.clearInlineReviewFieldError(item.key)"
                            @blur="ui.commitInlineReviewEditor"
                            @keydown.enter.prevent="ui.commitInlineReviewEditor"
                          />
                        </div>
                      </template>
                      <strong v-else :title="item.value">{{ item.value }}</strong>
                      <span v-if="ui.reviewInlineErrors[item.key]" class="review-inline-error">
                        {{ ui.reviewInlineErrors[item.key] }}
                      </span>
                    </div>
                    <span v-if="item.key !== 'attachments'" class="review-side-edit-hint">修改</span>
                    <span v-else class="review-side-edit-hint upload">{{ ui.reviewInlinePendingFiles.length ? '已选择' : '上传' }}</span>
                  </article>
                </section>
              </section>

              <section class="review-side-card">
                <div class="review-side-head">
                  <strong>报销分类</strong>
                  <span class="review-side-confidence">置信度 {{ ui.reviewPanelConfidence }}</span>
                </div>
                <div class="review-side-category-grid">
                  <button
                    v-for="item in ui.reviewCategoryOptions"
                    :key="item.key"
                    type="button"
                    class="review-side-category-card"
                    :class="{ active: item.active }"
                    @click="ui.selectReviewCategory(item)"
                  >
                    <div class="review-side-category-copy">
                      <strong>{{ item.label }}</strong>
                      <p>{{ item.is_other && ui.reviewSelectedOtherCategory ? ui.reviewSelectedOtherCategory : item.caption }}</p>
                    </div>
                    <i v-if="item.active" class="mdi mdi-check-circle review-side-group-check"></i>
                  </button>
                </div>
                <div v-if="ui.reviewOtherCategoryOpen" class="review-other-category-popover">
                  <button
                    v-for="item in ui.reviewOtherCategoryOptions"
                    :key="item.key"
                    type="button"
                    class="review-other-category-option"
                    :class="{ active: ui.reviewSelectedOtherCategory === item.label }"
                    @click="ui.selectReviewOtherCategory(item)"
                  >
                    {{ item.label }} · {{ item.confidenceLabel }}
                  </button>
                </div>
              </section>

            </template>

            <template v-else-if="ui.isReviewFlowDrawer">
              <section class="review-flow-panel">
                <div class="review-flow-summary">
                  <span class="flow-status-chip" :class="ui.flowOverallStatusTone">{{ ui.flowOverallStatusText }}</span>
                  <span>总耗时 {{ ui.flowTotalDurationText }}</span>
                  <button
                    type="button"
                    class="flow-icon-btn"
                    :disabled="!ui.flowRunId || ui.flowRefreshBusy"
                    title="刷新流程"
                    aria-label="刷新流程"
                    @click="ui.refreshFlowRunDetail"
                  >
                    <i :class="ui.flowRefreshBusy ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-refresh'"></i>
                  </button>
                </div>

                <TransitionGroup
                  v-if="(ui.visibleFlowSteps || ui.flowSteps).length"
                  name="el-fade-in-linear"
                  tag="div"
                  class="review-flow-list"
                >
                  <article
                    v-for="(step, index) in (ui.visibleFlowSteps || ui.flowSteps)"
                    :key="step.key"
                    class="flow-step-item"
                    :class="step.status"
                    :style="resolveFlowStepStyle(index)"
                  >
                    <div class="flow-step-rail">
                      <span>{{ index + 1 }}</span>
                    </div>

                    <div class="flow-step-card">
                      <header>
                        <strong>{{ step.title }}</strong>
                        <div class="flow-step-side">
                          <time>{{ ui.formatFlowStepDuration(step) }}</time>
                        </div>
                      </header>
                      <p class="flow-step-detail">{{ ui.resolveFlowStepDetail(step) }}</p>
                      <p v-if="step.error" class="flow-step-error">{{ step.error }}</p>
                    </div>
                  </article>
                </TransitionGroup>

                <div v-else class="flow-empty-state compact">
                  <i class="mdi mdi-timeline-question-outline"></i>
                  <strong>暂无识别流程</strong>
                  <p>发起识别后，这里会显示调用步骤和耗时。</p>
                </div>
              </section>
            </template>

            <template v-else-if="ui.isReviewDocumentDrawer">
              <section class="review-side-card review-document-switch-card review-ticket-drawer">
                <div class="review-side-head review-document-switch-head">
                  <div class="review-side-head-copy">
                    <strong>票据识别结果卡片</strong>
                    <p>逐张查看 OCR 结果，可直接修正后再切回核对滑窗。</p>
                  </div>
                  <div class="review-document-nav">
                    <button
                      type="button"
                      class="review-document-nav-btn"
                      :disabled="ui.activeReviewDocumentIndex === 0"
                      aria-label="上一张票据"
                      @click="ui.goReviewDocument(-1)"
                    >
                      <i class="mdi mdi-chevron-left"></i>
                    </button>
                    <span>{{ ui.activeReviewDocumentIndex + 1 }} / {{ ui.reviewDocumentCount }}</span>
                    <button
                      type="button"
                      class="review-document-nav-btn"
                      :disabled="ui.activeReviewDocumentIndex >= ui.reviewDocumentCount - 1"
                      aria-label="下一张票据"
                      @click="ui.goReviewDocument(1)"
                    >
                      <i class="mdi mdi-chevron-right"></i>
                    </button>
                  </div>
                </div>

                <div v-if="ui.activeReviewDocument" class="review-document-stage">
                  <div class="review-document-stage-head">
                    <div class="review-document-stage-copy">
                      <strong :title="ui.activeReviewDocument.filename">{{ ui.activeReviewDocument.filename }}</strong>
                    </div>
                  </div>

                  <div class="review-document-meta-chip-row">
                    <span class="review-document-meta-chip">{{ ui.activeReviewDocument.documentTypeLabel }}</span>
                    <span class="review-document-meta-chip">{{ ui.activeReviewDocument.expenseTypeLabel }}</span>
                    <span class="review-document-meta-chip confidence">{{ ui.activeReviewDocument.confidenceLabel }}</span>
                  </div>

                  <div class="review-document-scroll">
                    <div
                      class="review-document-preview-card"
                      :class="[
                        ui.activeReviewDocumentPreview?.kind || 'file',
                        { clickable: ui.canPreviewActiveReviewDocument }
                      ]"
                      :role="ui.canPreviewActiveReviewDocument ? 'button' : null"
                      :tabindex="ui.canPreviewActiveReviewDocument ? 0 : null"
                      @click="ui.canPreviewActiveReviewDocument ? ui.openActiveReviewDocumentPreview() : null"
                      @keydown.enter.prevent="ui.canPreviewActiveReviewDocument ? ui.openActiveReviewDocumentPreview() : null"
                      @keydown.space.prevent="ui.canPreviewActiveReviewDocument ? ui.openActiveReviewDocumentPreview() : null"
                    >
                      <img
                        v-if="ui.activeReviewDocumentPreview?.kind === 'image' && ui.activeReviewDocumentPreview?.url"
                        :src="ui.activeReviewDocumentPreview.url"
                        :alt="ui.activeReviewDocument.filename"
                      />
                      <div v-else-if="ui.activeReviewDocumentPreview?.kind === 'pdf'" class="review-document-preview-placeholder">
                        <i class="mdi mdi-file-pdf-box"></i>
                        <strong>PDF 票据文件</strong>
                        <p>当前文件还没有生成图片预览，可先核对下方识别字段。</p>
                      </div>
                      <div v-else class="review-document-preview-placeholder">
                        <i class="mdi mdi-file-search-outline"></i>
                        <strong>当前无可预览票据</strong>
                        <p>这张票据还没有可用预览，可先核对下方识别字段。</p>
                      </div>
                    </div>

                    <label class="review-document-edit-field summary">
                      <span>票据摘要</span>
                      <textarea
                        v-model="ui.activeReviewDocument.summary"
                        rows="3"
                        :disabled="ui.submitting || ui.reviewActionBusy"
                        placeholder="可根据票据图片修正 OCR 摘要"
                      ></textarea>
                    </label>

                    <label class="review-document-edit-field">
                      <span>票据场景</span>
                      <input
                        v-model="ui.activeReviewDocument.scene_label"
                        type="text"
                        :disabled="ui.submitting || ui.reviewActionBusy"
                        placeholder="例如：出租车/网约车票据 / 火车/高铁票"
                      />
                    </label>

                    <div v-if="ui.activeReviewDocument.fields.length" class="review-document-edit-grid">
                      <label
                        v-for="field in ui.activeReviewDocument.fields"
                        :key="`${ui.activeReviewDocument.filename}-${field.label}`"
                        class="review-document-edit-field"
                      >
                        <span>{{ field.label }}</span>
                        <input
                          v-model="field.value"
                          type="text"
                          :disabled="ui.submitting || ui.reviewActionBusy"
                          :placeholder="`修正 ${field.label}`"
                        />
                      </label>
                    </div>
                    <div v-else class="review-side-empty compact">
                      <span class="review-side-empty-icon">
                        <i class="mdi mdi-text-recognition"></i>
                      </span>
                      <strong>暂无结构化字段</strong>
                      <p>当前只返回了摘要信息，您仍然可以直接修改上面的票据摘要。</p>
                    </div>

                    <div v-if="ui.activeReviewDocument.warnings?.length" class="review-document-warning-list">
                      <article
                        v-for="warning in ui.activeReviewDocument.warnings"
                        :key="`${ui.activeReviewDocument.filename}-${warning}`"
                        class="review-document-warning-item"
                      >
                        <i class="mdi mdi-alert-circle-outline"></i>
                        <span>{{ warning }}</span>
                      </article>
                    </div>
                  </div>
                </div>
              </section>
            </template>

            <template v-else-if="ui.isReviewRiskDrawer">
              <section class="review-side-card review-side-risk-card">
                <div class="review-side-head">
                  <div class="review-side-head-copy">
                    <strong>差旅合规提示</strong>
                    <p>结合票据识别结果与差旅规则，逐项查看需要处理的风险点。</p>
                  </div>
                </div>
                <p class="review-side-risk-summary">{{ ui.reviewRiskSummary }}</p>
                <div v-if="ui.reviewRiskItems.length" class="review-side-risk-list">
                  <button
                    v-for="item in ui.reviewRiskItems"
                    :key="item.key"
                    type="button"
                    class="review-side-risk-item"
                    :class="item.level"
                    @click="ui.appendReviewRiskBriefToConversation(item)"
                  >
                    <span class="review-side-risk-icon" :title="item.levelLabel">
                      <i :class="item.icon"></i>
                    </span>
                    <span class="review-side-risk-copy">
                      <strong>{{ item.title }}</strong>
                      <p>{{ item.summary }}</p>
                    </span>
                    <span class="review-side-risk-meta">
                      <i class="mdi mdi-chevron-right"></i>
                    </span>
                  </button>
                </div>
                <div v-else-if="ui.reviewRiskEmpty" class="review-side-empty">
                  <span class="review-side-empty-icon">
                    <i class="mdi mdi-shield-check-outline"></i>
                  </span>
                  <strong>暂无风险提示</strong>
                  <p>当前没有需要额外处理的结构化风险点。</p>
                </div>
              </section>
            </template>

            <button
              v-if="ui.reviewHasUnsavedChanges"
              type="button"
              class="review-side-save-pill"
              :disabled="ui.reviewActionBusy || ui.submitting"
              @click="ui.saveInlineReviewChanges"
            >
              <i class="mdi mdi-content-save-outline"></i>
              保存右侧修改
            </button>
          </template>

          <section v-if="ui.currentInsight.agent.citations?.length && !ui.currentInsight.agent.queryPayload && !ui.activeReviewPayload" class="insight-card">
            <div class="card-head">
              <h4>制度依据</h4>
            </div>
            <div class="citation-stack">
              <article v-for="item in ui.currentInsight.agent.citations" :key="item.code" class="citation-card">
                <header>
                  <strong>{{ item.title }}</strong>
                  <span>{{ item.version || item.source_type }}</span>
                </header>
                <p>{{ item.excerpt || item.code }}</p>
              </article>
            </div>
          </section>

          <template v-if="!ui.activeReviewPayload">
            <section class="insight-card primary">
              <div class="card-head">
                <h4>识别结果</h4>
              </div>
              <div class="note-block">
                <strong>{{ ui.currentInsight.title }}</strong>
                <p>{{ ui.currentInsight.summary }}</p>
              </div>
            </section>

            <section v-if="ui.currentInsight.agent.riskFlags?.length" class="insight-card">
              <div class="card-head">
                <h4>风险标签</h4>
              </div>
              <div class="capability-chip-row">
                <span v-for="item in ui.currentInsight.agent.riskFlags" :key="item" class="risk-chip">{{ item }}</span>
              </div>
            </section>
          </template>
        </template>
      </div>
    </Transition>
    </aside>
  </div>
</template>

<script>
export default {
  name: 'TravelReimbursementInsightPanel',
  props: {
    ui: {
      type: Object,
      required: true
    }
  },
  methods: {
    resolveFlowStepStyle(index) {
      return {
        transitionDelay: `${500 + Math.min(Number(index) || 0, 5) * 80}ms`
      }
    }
  }
}
</script>

<style scoped src="../../assets/styles/components/travel-reimbursement-insight-panel.css"></style>
