<script setup lang="ts">
import { useIntersectionObserver } from '@vueuse/core';
import { ref } from 'vue';

function checkIsVisible(el: Element, root: Element | null = null) {
  if (!el) return false;

  const elRect = el.getBoundingClientRect();
  const rootRect = root
    ? root.getBoundingClientRect()
    : { top: 0, left: 0, bottom: window.innerHeight, right: window.innerWidth };

  return (
    elRect.bottom >= rootRect.top &&
    elRect.top <= rootRect.bottom &&
    elRect.right >= rootRect.left &&
    elRect.left <= rootRect.right
  );
}

interface Comment {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}
const list = ref<Comment[]>([]);

const loading = ref(false);
const page = ref(0);
const pageSize = 1;

const loadMore = async () => {
  if (loading.value) return;

  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/comments?_page=${++page.value}&_limit=${pageSize}`,
    );
    const data = await response.json();
    list.value.push(...data);
  } catch (error) {
    console.error('Failed to load comments:', error);
  } finally {
    loading.value = false;
  }
  await nextTick();
  if (checkIsVisible(target.value!)) {
    loadMore();
  }
};

const target = ref(null);
const isVisible = ref(false);

const { isActive, pause, resume, isSupported } = useIntersectionObserver(
  target,
  ([entry]) => {
    isVisible.value = entry?.isIntersecting || false;
    if (entry?.isIntersecting) {
      loadMore();
    }
  },
  // { threshold: 0.1 },
);
</script>

<template>
  <Card v-for="item in list" :key="item.id" class="mb-[16px]">
    <template #title>{{ item.name }}</template>
    <template #content>
      <p class="text-gray-600">{{ item.email }}</p>
      <p class="mt-[8px]">{{ item.body }}</p>
    </template>
  </Card>

  <div ref="target" class="border-[8px] border-blue-500 p-[16px]">
    <Button label="Load more" :loading="loading" fluid @click="loadMore" />
  </div>

  <ScrollTop />
  <div class="border-[1px] border-blue-500 fixed top-16 right-16 p-[4px] bg-white" flex="~ col" items-end>
    <label class="checkbox">
      <span mr="[8px]">isSupported: {{ isSupported }}</span>
      <input
        :checked="isActive"
        type="checkbox"
        name="enabled"
        @input="($event.target as HTMLInputElement)!.checked ? resume() : pause()"
      />
      <span>Enable</span>
    </label>
    <div>
      Element
      <span class="font-bold" :class="isVisible ? 'text-blue-500' : 'text-orange-400'">
        {{ isVisible ? 'inside' : 'outside' }}
      </span>
      the viewport
    </div>
  </div>
</template>
