<template>
  <div class="pb-8">
    <!-- Article Detail View -->
    <ArticleDetail
      v-if="selectedArticleId"
      :article-id="selectedArticleId"
      @back="handleBack"
    />

    <!-- Article List View -->
    <div v-else>
      <!-- Header -->
      <div class="mb-6">
        <h1 class="text-xl md:text-2xl font-semibold text-content-primary">
          Artikel
        </h1>
        <p class="text-sm md:text-base text-content-secondary mb-6">
          Kelola dan jelajahi artikel sebagai sumber informasi resmi INAgov.
        </p>

        <!-- Category Filter -->
        <div class="mb-6">
          <Chip
            :options="categoryOptions"
            :selected="selectedCategory"
            :show-customization="false"
            variant="outline"
            size="medium"
            @select="handleCategoryChange"
          />
        </div>
      </div>

      <!-- Articles Grid - 3 columns on desktop -->
      <div
        class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 sm:gap-10 mb-6 md:mb-8 justify-items-center sm:justify-items-start"
      >
        <div
          v-for="article in currentArticles"
          :key="article.id"
          @click="handleArticleClick(article.id)"
          class="cursor-pointer w-full h-[330px] [&_.ina-card]:w-full [&_.ina-card]:h-full"
        >
          <Card
            variant="basic"
            media-position="top"
            :title="
              h(
                'span',
                {
                  class:
                    'text-base md:text-lg font-semibold text-content-secondary line-clamp-1',
                },
                article.title,
              )
            "
            :description="
              h(
                'span',
                {
                  class:
                    'text-sm md:text-base text-content-secondary line-clamp-2',
                },
                article.excerpt,
              )
            "
            :media-src="article.mediaSrc"
            :media-alt="article.title"
            :clickable="true"
            :hoverable="true"
          />
        </div>
      </div>

      <!-- Pagination -->
      <div v-if="totalPages > 0" class="mt-6 md:mt-8">
        <Pagination
          :model-value="currentPage"
          :total-pages="totalPages"
          :page-size="pageSize"
          :page-size-options="[12]"
          :full-width="true"
          @update:model-value="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { Card, Pagination, Chip } from '@idds/vue';
import ArticleDetail from './ArticleDetail.vue';
import {
  articles,
  categoryOptions,
  type ArticleCategory,
} from '../data/articlesData';

const currentPage = ref(1);
const pageSize = ref(12); // Fixed 12 items per page
const selectedCategory = ref<ArticleCategory>('Semua');
const selectedArticleId = ref<string | null>(null);

// Filter articles by category
const filteredArticles = computed(() => {
  if (selectedCategory.value === 'Semua') {
    return articles;
  }
  return articles.filter(
    (article) => article.category === selectedCategory.value,
  );
});

// Calculate pagination
const totalPages = computed(() =>
  Math.ceil(filteredArticles.value.length / pageSize.value),
);
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value);
const endIndex = computed(() => startIndex.value + pageSize.value);
const currentArticles = computed(() =>
  filteredArticles.value.slice(startIndex.value, endIndex.value),
);

const handlePageChange = (page: number) => {
  currentPage.value = page;
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

const handleCategoryChange = (category: string) => {
  selectedCategory.value = category as ArticleCategory;
  currentPage.value = 1; // Reset to first page when category changes
};

const handlePageSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  currentPage.value = 1; // Reset to first page when page size changes
};

const handleArticleClick = (articleId: string) => {
  selectedArticleId.value = articleId;
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

const handleBack = () => {
  selectedArticleId.value = null;
  window.scrollTo({ top: 0, behavior: 'smooth' });
};
</script>
