<template>
  <div class="home-page">
    <div class="hero">
      <h2>Vue3 子应用首页</h2>
      <p class="desc">
        这是一个运行在 <code>localhost:3001</code> 的 Vue 3 子应用
      </p>
      <p class="env-hint" v-if="isMicroApp">
        🟢 当前运行在 <strong>micro-app 微前端环境</strong> 中
      </p>
      <p class="env-hint" v-else>
        🔵 当前<strong>独立运行</strong>模式
      </p>
    </div>

    <div class="nav-section">
      <h3>子应用内部导航</h3>
      <div class="links">
        <router-link to="/" class="nav-link">首页</router-link>
        <router-link to="/about" class="nav-link">关于页</router-link>
      </div>
    </div>

    <div class="info-card">
      <h4>路由信息</h4>
      <table>
        <tbody>
          <tr>
            <td>当前路径</td>
            <td><code>{{ $route.path }}</code></td>
          </tr>
          <tr>
            <td>baseroute</td>
            <td><code>{{ baseRoute }}</code></td>
          </tr>
          <tr>
            <td>应用名称</td>
            <td><code>{{ appName }}</code></td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 跨应用通信演示 -->
    <div class="comm-demo">
      <div class="comm-title">📡 跨应用通信</div>

      <div class="counter-section">
        <span class="counter-label">共享计数器</span>
        <span class="counter-value" :class="{ flash: counterFlash }">{{ count }}</span>
      </div>

      <div class="button-group">
        <button class="btn-send-main" @click="broadcastIncrement">
          📡 +1 并广播全局
        </button>
        <button class="btn-reset" @click="resetCount">
          🔄 归零（广播）
        </button>
      </div>

      <div class="comm-log">
        <div class="log-header">📋 通信日志（vue3-app 视角）</div>
        <div class="log-list" ref="logListRef">
          <div v-for="(log, i) in logs" :key="i" class="log-item" :class="log.type">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-msg">{{ log.msg }}</span>
          </div>
          <div v-if="logs.length === 0" class="log-empty">等待通信...</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'

const isMicroApp = computed(() => !!window.__MICRO_APP_ENVIRONMENT__)
const baseRoute = computed(() => window.__MICRO_APP_BASE_ROUTE__ || '/')
const appName = computed(() => window.__MICRO_APP_NAME__ || '独立运行')

// 通信相关
const count = ref(0)
const counterFlash = ref(false)
const logs = ref<Array<{ time: string; msg: string; type: string }>>([])
const logListRef = ref<HTMLElement | null>(null)

function flash() {
  counterFlash.value = true
  setTimeout(() => (counterFlash.value = false), 300)
}

function addLog(msg: string, type: 'receive' | 'send' | 'relay') {
  const now = new Date()
  const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  logs.value.push({ time, msg, type })
  if (logs.value.length > 30) logs.value.shift()
  nextTick(() => {
    if (logListRef.value) {
      logListRef.value.scrollTop = logListRef.value.scrollHeight
    }
  })
}

function broadcastIncrement() {
  count.value++
  flash()
  if (window.__MICRO_APP_ENVIRONMENT__) {
    window.microApp!.setGlobalData({ count: count.value, from: 'vue3-app' })
    addLog(`vue3 → globalData: 广播计数 ${count.value}（主应用 + vue2 均收到）`, 'send')
  } else {
    addLog(`[独立模式] +1 → ${count.value}`, 'send')
  }
}

function resetCount() {
  count.value = 0
  flash()
  if (window.__MICRO_APP_ENVIRONMENT__) {
    window.microApp!.setGlobalData({ count: 0, from: 'vue3-app' })
    addLog(`归零 → globalData（全应用同步）`, 'send')
  }
}

onMounted(() => {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    // globalData 监听 — autoTrigger: true 立即用当前值触发一次
    window.microApp?.addGlobalDataListener((data: any) => {
      if (data.count !== undefined) {
        const from = data.from || 'unknown'
        count.value = data.count
        flash()
        addLog(`globalData ← ${from}: 计数 ${data.count}`, 'receive')
      }
    }, true)
  }
})
</script>

<style scoped>
.home-page {
  max-width: 720px;
  margin: 0 auto;
  padding: 40px 24px;
}

.hero {
  text-align: center;
  padding: 32px 0;
}

.hero h2 {
  font-size: 24px;
  font-weight: 700;
  color: #42b883;
  margin-bottom: 8px;
}

.hero .desc {
  color: #666;
  font-size: 14px;
}

.hero code {
  background: #e8f5e9;
  color: #2e7d32;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.env-hint {
  margin-top: 16px;
  font-size: 14px;
  color: #555;
  padding: 8px 16px;
  background: #f0faf3;
  border-radius: 6px;
  display: inline-block;
}

.nav-section {
  margin-top: 32px;
  padding: 24px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.nav-section h3 {
  font-size: 16px;
  color: #444;
  margin-bottom: 16px;
}

.links {
  display: flex;
  gap: 12px;
}

.nav-link {
  padding: 8px 20px;
  background: #f5f5f5;
  border-radius: 6px;
  text-decoration: none;
  color: #555;
  font-size: 14px;
  transition: all 0.2s;
}

.nav-link:hover {
  background: #e8f5e9;
  color: #2e7d32;
}

.nav-link.router-link-active {
  background: #42b883;
  color: #fff;
}

.info-card {
  margin-top: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.info-card h4 {
  font-size: 16px;
  color: #444;
  margin-bottom: 12px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

td {
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

td:first-child {
  color: #999;
  width: 100px;
}

td code {
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 3px;
  font-size: 13px;
  color: #42b883;
}

/* ============================================
   跨应用通信演示
   ============================================ */
.comm-demo {
  margin-top: 24px;
  border: 2px solid #667eea;
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
}

.comm-title {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  padding: 10px 20px;
  font-weight: 700;
  font-size: 14px;
}

.counter-section {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8f9ff;
  border-bottom: 1px solid #e8e8f8;
}

.counter-label {
  font-size: 14px;
  font-weight: 600;
  color: #555;
}

.counter-value {
  font-size: 48px;
  font-weight: 800;
  color: #667eea;
  transition: transform 0.3s, color 0.3s;
}

.counter-value.flash {
  transform: scale(1.2);
  color: #ff6b35;
}

.button-group {
  display: flex;
  gap: 10px;
  padding: 16px 20px;
}

.button-group button {
  flex: 1;
  padding: 10px 8px;
  border: none;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  color: #fff;
}

.btn-send-main {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.btn-send-main:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 12px rgba(102, 126, 234, 0.3);
}

.btn-reset {
  background: #94a3b8;
}

.btn-reset:hover {
  background: #64748b;
  transform: translateY(-1px);
}

.comm-log {
  border-top: 1px solid #f0f0f0;
  padding: 12px 20px;
}

.log-header {
  font-size: 13px;
  font-weight: 600;
  color: #666;
  margin-bottom: 8px;
}

.log-list {
  max-height: 150px;
  overflow-y: auto;
  background: #fafafa;
  border-radius: 6px;
  padding: 8px 10px;
  border: 1px solid #f0f0f0;
}

.log-item {
  display: flex;
  gap: 10px;
  font-size: 12px;
  padding: 3px 0;
  border-bottom: 1px solid #f5f5f5;
  font-family: 'Consolas', 'Courier New', monospace;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #999;
  flex-shrink: 0;
}

.log-item.receive .log-msg {
  color: #667eea;
}

.log-item.send .log-msg {
  color: #16a34a;
}

.log-item.relay .log-msg {
  color: #f59e0b;
}

.log-empty {
  font-size: 12px;
  color: #ccc;
  text-align: center;
  padding: 12px 0;
}
</style>
