<template>
  <scroll-view
    class="log-panel"
    scroll-y
    :scroll-into-view="scrollToId"
    :scroll-with-animation="true"
    :scroll-top="scrollTop"
  >
    <view
      v-for="log in logs"
      :key="log.id"
      class="log-item"
      :class="`log-item--${log.type}`"
      :id="'log-' + log.id"
    >
      <text class="log-item__time">[{{ log.time }}]</text>
      <text class="log-item__message">{{ log.message }}</text>
    </view>
    <view :id="'log-anchor-' + lastLogId" class="log-anchor"></view>
  </scroll-view>
</template>

<script setup>
import { computed, watch, nextTick, ref } from 'vue'
import { useGameStore } from '@/store/game'

const game = useGameStore()
const scrollToId = ref('')
const scrollTop = ref(0)

const logs = computed(() => game.logs)

const lastLogId = computed(() => {
  return logs.value.length > 0 ? logs.value[logs.value.length - 1].id : 0
})

watch(lastLogId, (newId) => {
  if (newId) {
    nextTick(() => {
      scrollToId.value = 'log-anchor-' + newId
      // 重置scrollToId以允许下次滚动
      setTimeout(() => {
        scrollToId.value = ''
      }, 100)
    })
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.log-panel {
  height: 100%;
  padding: 16rpx;
  background-color: $bg-primary;
}

.log-item {
  display: flex;
  flex-wrap: wrap;
  padding: 8rpx 0;
  border-bottom: 1rpx solid $bg-tertiary;

  &__time {
    color: $text-muted;
    font-size: 22rpx;
    margin-right: 8rpx;
    flex-shrink: 0;
  }

  &__message {
    color: $text-primary;
    font-size: 26rpx;
    line-height: 1.5;
    flex: 1;
  }

  // 不同类型的日志样式
  &--combat {
    .log-item__message {
      color: $danger;
    }
  }

  &--system {
    .log-item__message {
      color: $accent;
      font-weight: bold;
    }
  }

  &--reward {
    .log-item__message {
      color: $warning;
    }
  }

  &--info {
    .log-item__message {
      color: $text-secondary;
    }
  }

  &--warning {
    .log-item__message {
      color: $warning;
    }
  }

  &--error {
    .log-item__message {
      color: $danger;
    }
  }

  &--success {
    .log-item__message {
      color: $success;
    }
  }
}

.log-anchor {
  height: 1rpx;
}
</style>
