<template>
  <div>
    <!-- Empty State -->
    <div v-if="news.articles.length === 0" class="text-center py-12">
      <svg class="mx-auto h-12 w-12 text-gray-400 dark:text-gray-500" fill="none"
           stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h4"/>
      </svg>
      <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-white">No articles found</h3>
      <p class="mt-2 text-gray-500 dark:text-gray-400">Try adjusting your filters to see more
        results.</p>
    </div>

    <!-- Articles Grid -->
    <div v-else class="grid gap-4 sm:gap-6 md:grid-cols-2 xl:grid-cols-3">
      <article
        v-for="article in news.articles"
        :key="article.id"
        class="flex flex-col h-full bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 hover:shadow-md dark:hover:shadow-lg dark:hover:shadow-gray-800/50 transition-all duration-200 overflow-hidden group"
      >
        <!-- Article Header -->
        <div class="flex-1 p-4 sm:p-6">
          <div class="flex items-start justify-between mb-3">
            <span
              class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200">
              {{ article.country }}
            </span>
            <time
              :datetime="new Date(article.published * 1000).toISOString()"
              :title="new Date(article.published * 1000).toLocaleString(userLocale.value, {
                dateStyle: 'full',
                timeStyle: 'long'
              })"
              class="text-xs text-gray-500 flex-shrink-0 ml-2 cursor-help hover:text-green-600 dark:hover:text-green-400 transition-colors relative group"
            >
              {{ formatDate(article.published) }}
            </time>
          </div>

          <!-- Title -->
          <h3
            class="text-base sm:text-lg font-semibold text-gray-900 dark:text-white mb-3 line-clamp-2 group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
            <a :href="article.url" target="_blank" rel="noopener noreferrer">
              {{ article.title }}
            </a>
          </h3>

          <!-- Summary -->
          <p
            class="text-sm sm:text-base text-gray-700 dark:text-gray-300 line-clamp-5 leading-relaxed">
            {{ article.summary }}
          </p>
        </div>

        <!-- Article Footer -->
        <div
          class="flex justify-between items-center gap-4 p-4 sm:p-6">
          <button
            @click="openModal(article)"
            class="flex-1 inline-flex items-center justify-center cursor-pointer px-4 py-2 text-sm font-medium rounded-lg bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50 transition-colors"
          >
            Full summary
            <svg class="ml-1 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
            </svg>
          </button>

          <a
            :href="article.url"
            target="_blank"
            rel="noopener noreferrer"
            class="flex-1 inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50 transition-colors"
          >
            Full article
            <svg class="ml-1 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/>
            </svg>
          </a>
        </div>
      </article>
    </div>

    <!-- Loading State & Load More Trigger -->
    <div v-if="news.articles.length > 0" class="text-center mt-8" ref="loadMoreTrigger">
      <p v-if="loading" class="text-sm text-gray-500">
        Loading more articles...
      </p>
      <p v-else-if="!news.hasMore" class="text-sm text-gray-500">
        No more articles to load
      </p>
      <p v-else class="text-sm text-gray-500">
        Showing {{ news.articles.length }} of {{ news.allArticles.length }} articles
      </p>
    </div>

    <!-- Article Modal -->
    <ArticleModal
      :is-open="isModalOpen"
      :article="selectedArticle"
      @close="closeModal"
    />
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onUnmounted, watch, computed} from 'vue';
import {useNews} from '../stores/useNews';
import ArticleModal from './ArticleModal.vue';

const userLocale = computed(() => news.clientLocale || 'en-US');

const news = useNews();
const loading = ref(false);

const loadMoreArticles = async () => {
  if (loading.value || !news.hasMore) return;
  loading.value = true;
  try {
    await news.loadMore();
  } catch (error) {
    console.error('Error loading more articles:', error);
  } finally {
    loading.value = false;
  }
};

const observer = ref<IntersectionObserver | null>(null);
const loadMoreTrigger = ref<HTMLElement | null>(null);

onMounted(() => {
  observer.value = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        loadMoreArticles();
      }
    },
    {threshold: 0.5}
  );

  if (loadMoreTrigger.value) {
    observer.value.observe(loadMoreTrigger.value);
  }
});

onUnmounted(() => {
  if (observer.value) {
    observer.value.disconnect();
  }
});

// Watch for changes to the loadMoreTrigger element
watch(loadMoreTrigger, (newEl, oldEl) => {
  if (observer.value) {
    // Disconnect from old element if it exists
    if (oldEl) {
      observer.value.unobserve(oldEl);
    }

    // Observe new element if it exists
    if (newEl) {
      observer.value.observe(newEl);
    }
  }
});

// Modal state
const isModalOpen = ref(false);
const selectedArticle = ref<{
  id: number;
  title: string;
  summary: string;
  url: string;
  published: number;
  country: string;
  created_at: number;
} | null>(null);

// Modal functions
const openModal = (article: typeof selectedArticle.value) => {
  selectedArticle.value = article;
  isModalOpen.value = true;
};

const closeModal = () => {
  isModalOpen.value = false;
  selectedArticle.value = null;
};

function formatDate(timestamp: number): string {
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60));

  if (diffInHours < 1) {
    return 'Just now';
  } else if (diffInHours < 24) {
    return `${diffInHours}h ago`;
  } else if (diffInHours < 48) {
    return 'Yesterday';
  } else {
    return date.toLocaleDateString(userLocale.value, {
      month: 'short',
      day: 'numeric',
      year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined
    });
  }
}
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
