<template>
  <div ref="scrollElement" :class="['app-view', flex && 'app-view--flex']">
    <div class="app-view__header">
      <div class="app-view__container">
        <slot name="header"></slot>
      </div>
    </div>
    <div class="app-view__main">
      <div class="app-view__container">
        <slot></slot>
      </div>
    </div>
    <div class="app-view__footer">
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onActivated, onMounted } from 'vue'
import { useRoute, onBeforeRouteLeave } from 'vue-router'

const emit = defineEmits(['ready']);

const route = useRoute();
const scrollElement = ref<HTMLDivElement>();
const scrollMap = new Map<string, number>();

defineProps({
  flex: {
    type: Boolean,
    default: false,
  }
})

onMounted(() => {
  emit('ready')
})

onActivated(() => {
  const el = scrollElement.value;
  if (el) {
    el.scrollTop = scrollMap.get(route.fullPath) ?? 0;
  }
})

onBeforeRouteLeave(() => {
  const el = scrollElement.value;
  if (el) {
    scrollMap.set(route.fullPath, el.scrollTop);
  }
})
</script>

<style lang="less">
@import './index.less';
</style>