<script setup>
import { ref, unref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { Readability } from '@mozilla/readability';
import Modal from './modal/AddUrl.vue';

const showMessage = ref(false)
const feeds = ref([]);
const message = ref('')
const showModal = ref(false)

async function getReadable(feed, index) {
  try {
    const response = await axios.post("feeds/read", {
      url: feed.url
    },
      {
        headers: {
          'Content-Type': 'application/json',
          'user-token': localStorage.getItem("user-token")
        }
      })

    const doc = new DOMParser().parseFromString(response.data.content, 'text/html');
    const article = new Readability(doc).parse();
    feeds.value[index].content = article.content;
  } catch (error) {
    console.error('Error fetching data:', error)
    showMessageForXSeconds(error, 5)
  }
}

async function markRead(id) {
  try {
    const response = await axios.put("feeds/read/" + id,
      null,
      {
        headers: {
          'Content-Type': 'application/json',
          'user-token': localStorage.getItem("user-token")
        }
      }
    )
    console.log(response.status)
  } catch (error) {
    console.log(error)
  }
}

function showMessageForXSeconds(text, seconds) {
  message.value = text;
  showMessage.value = true;

  // Set a timeout to hide the message after x seconds
  setTimeout(() => {
    showMessage.value = false;
    message.value = '';
  }, seconds * 1000); // Convert seconds to milliseconds
}

const fetchData = async () => {
  const user_id = localStorage.getItem("user-id")
  try {
    const response = await axios.get("feeds/get/" + user_id, {
      headers: {
        'Content-Type': 'application/json',
        'user-token': localStorage.getItem("user-token")
      }
    });
    response.data.feeds.forEach(feed => {
      feeds.value.push(...feed.items);
    });
    await nextTick();
    setupIntersectionObserver();
  } catch (error) {
    console.error('Error fetching data:', error)
    showMessageForXSeconds(error, 5)
  }
};

async function sync() {
  try {
    const response = await axios.post('feeds/sync', {
      user_id: parseInt(localStorage.getItem("user-id"))
    },
      {
        headers: {
          'Content-Type': 'application/json',
          'user-token': localStorage.getItem("user-token")
        }
      })

    if (response.status == 200) {
      showMessageForXSeconds('Sync successful.', 5)
    }
    fetchData();
  } catch (error) {
    console.error('Error sync', error)
    showMessageForXSeconds(error, 5)
  }
}

let observer; // Declare observer outside the setup function

function setupIntersectionObserver() {
  observer = new IntersectionObserver(handleIntersection, {
    root: null, // Use the viewport as the root
    rootMargin: '0px',
    // threshold: 0.5, // Fire the callback when at least 50% of the element is visible
  });

  const observedDivs = document.querySelectorAll(".observe");
  if (observedDivs.length > 0) {
    observedDivs.forEach(observedDiv => {
      observer.observe(observedDiv);
    })
  }
}

async function handleIntersection(entries) {
  // The callback function for when the target element enters or exits the viewport
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element is in sight');
    } else if (initialLoad === true) {
      console.log(entry.isIntersecting)
      // Element is out of sight
      if (entry.isVisible === false && entry.boundingClientRect.y < 0) {
        console.log('Element is out of sight ' + entry.intersectionRatio);
        //console.log(feeds.value[entry.target.id])
        markRead(feeds.value[entry.target.id].id).await
        removeFeed(entry.target.id)
        document.getElementById(0).scrollIntoView()
      }
    }
  })
}

function removeFeed(index) {
  const array = unref(feeds);
  array.splice(index, 1);
}

let initialLoad = false
onMounted(() => {
  initialLoad = false
  fetchData().await
  setTimeout(function () {
    initialLoad = true
    console.log('set to true')
  }, 2000);
});
</script>

<template>
  <header>
    <div class="wrapper">
      <nav>
        <p @click="sync">Sync</p>
        <!-- <p @click="updateShow(true)">Add RSS</p> -->
        <p @click="showModal = true">Add RSS</p>
        <!-- <RouterLink to="/">Home</RouterLink> -->
        <!-- <RouterLink to="/about">About</RouterLink> -->
        <!-- <RouterLink to="/feeds">Feeds</RouterLink> -->
      </nav>
    </div>
  </header>
  <Teleport to="body">
    <!-- use the modal component, pass in the prop -->
    <modal :show="showModal" @close="showModal = false">
      <template #header>
        <h3>Add RSS Feed</h3>
      </template>
    </modal>
  </Teleport>
  <div>
    <h1>Feeds</h1> <!-- <button @click="sync">{{ buttonText }}</button> -->
    <div v-if="showMessage" class="message">{{ message }}</div>
    <div id='article' class='article'>
      <p v-if="feeds.length == 0">No unread articles.</p>
      <template v-for="(   feed, index   ) in    feeds   ">
        <div v-bind:id="index" class="observe">
          <h2 @click="getReadable(feed, index)" class="feed-title">{{ feed.title }}</h2>
          <h3>{{ feed.timestamp }}</h3>
          <p class="feed-content" v-html='feed.content'></p>
        </div>
      </template>
    </div>
  </div>
</template>
