<script lang="ts">
// eslint-disable-next-line unicorn/prefer-structured-clone
const structuredClone = globalThis.structuredClone || ((object) => JSON.parse(JSON.stringify(object)));

const K_INITIAL_STATE = deepFreeze({
  complete: false,
  error: null as unknown,
  list: [] as Record<string, never>[],
  loading: false,
  page: 0,
});

let page3ShouldError = true;
const state = shallowReactive(structuredClone(K_INITIAL_STATE));
</script>

<script setup lang="ts">
defineOptions({
  beforeRouteEnter: (to, from) => {
    if (from.name !== 'UIComponentsInfiniteLoadingDetail') {
      Object.assign(state, structuredClone(K_INITIAL_STATE));
    }
  },
  beforeRouteLeave: (to, from) => {
    if (to.name !== 'UIComponentsInfiniteLoadingDetail') {
      Object.assign(state, structuredClone(K_INITIAL_STATE));
    }
  },
});
const refresh = () => {
  state.list.splice(0);
  state.page = 0;
  state.complete = false;
  loadMore();
};

type CurrentUse = 'use-intersection-observer-infinite-loading' | 'van-list';

async function loadMore() {
  if (state.loading) return;

  try {
    state.loading = true;
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/comments?_page=${++state.page}&_limit=1&timestamp=${Date.now()}`,
    ).then((res) => {
      if (state.page === 3 && page3ShouldError) {
        page3ShouldError = false;
        throw new Error('test error');
      } else {
        return res;
      }
    });
    const data = await response.json();
    state.list = [...state.list, ...data];
    if ($__DEV__) await new Promise((resolve) => setTimeout(resolve, 500));
    state.complete = state.list.length >= 5;
  } catch (error) {
    state.error = error;
    state.page--;
  } finally {
    state.loading = false;
  }
}
const currentUse = ref<CurrentUse>((sessionStorage.getItem('currentUse') as CurrentUse) || 'van-list');
watchEffect(() => {
  sessionStorage.setItem('currentUse', currentUse.value);
});
</script>

<template>
  <div mb-4 class="flex justify-end gap-4 flex-wrap items-start">
    <Button label="刷新" @click="refresh" />
    <Button
      label="push"
      @click="state.list.push({ id: state.list.length + 1, name: 'name', body: 'body', email: 'email' } as any)"
    />
    <Button
      :label="currentUse"
      @click="currentUse = currentUse === 'van-list' ? 'use-intersection-observer-infinite-loading' : 'van-list'"
      class="mb-4"
    />
  </div>
  <template v-if="currentUse === 'van-list'">
    <VanList
      @load="loadMore"
      :loading="state.loading"
      :error="!!state.error"
      :error-text="`${state.error}`"
      :onUpdate:error="() => (state.error = null)"
      :finished="state.complete"
    >
      <template v-for="item in state.list" :key="item.id">
        <div
          class="border p-4 mb-[16px]"
          @click="$router.push({ name: 'UIComponentsInfiniteLoadingDetail', query: { id: item.id } })"
        >
          <div>id:{{ item.id }}</div>
        </div>
      </template>
    </VanList>
  </template>

  <template v-if="currentUse === 'use-intersection-observer-infinite-loading'">
    <Card
      v-for="item in state.list"
      :key="item.id"
      class="mb-[16px]"
      @click="$router.push({ name: 'UIComponentsInfiniteLoadingDetail', query: { id: item.id } })"
    >
      <template #title>{{ item.name }}</template>
      <template #content>
        <p class="mt-[8px]">{{ item.body }}</p>
      </template>
      <template #subtitle>id:{{ item.id }} </template>
      <template #footer>{{ item.email }}</template>
    </Card>
    <UseIntersectionObserverInfiniteLoading
      @load="loadMore"
      :loading="state.loading"
      :error="!!state.error"
      :error-text="`${state.error}`"
      @clickError="state.error = null"
      :complete="state.complete"
    />
    <div border="1 px solid red rounded-lg" class="p-4 mb-[16px]">
      {{ { 'list.length': state.list.length } }}
    </div>
  </template>
  <ScrollTop />
</template>
