---
import BaseLayout from '../../layouts/BaseLayout.astro';
import TerminalWindow from '../../components/ui/TerminalWindow.astro';
import CommandPrompt from '../../components/ui/CommandPrompt.astro';
import FilterPill from '../../components/ui/FilterPill.astro';
import PostCard from '../../components/PostCard.astro';
import { api } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import type { Category, Post, Tag } from '../../lib/types';
import { getAccentVars, getCategoryTheme, getPostTypeTheme, getTagTheme } from '../../lib/utils';

export const prerender = false;

const url = new URL(Astro.request.url);
const selectedSearch = url.searchParams.get('search') || '';
const selectedType = url.searchParams.get('type') || 'all';
const selectedTag = url.searchParams.get('tag') || '';
const selectedCategory = url.searchParams.get('category') || '';
const requestedPage = Number.parseInt(url.searchParams.get('page') || '1', 10);
const postsPerPage = 10;
const { t } = getI18n(Astro);

let paginatedPosts: Post[] = [];
let allTags: Tag[] = [];
let allCategories: Category[] = [];
let totalPosts = 0;
let totalPages = 1;
let currentPage = Number.isFinite(requestedPage) && requestedPage > 0 ? requestedPage : 1;

try {
  const [pageResult, categories, rawTags] = await Promise.all([
    selectedSearch
      ? api.searchPostsPage({
          query: selectedSearch,
          page: currentPage,
          pageSize: postsPerPage,
          category: selectedCategory || undefined,
          tag: selectedTag || undefined,
          postType: selectedType !== 'all' ? selectedType : undefined,
        })
      : api.getPostsPage({
          page: currentPage,
          pageSize: postsPerPage,
          search: undefined,
          category: selectedCategory || undefined,
          tag: selectedTag || undefined,
          postType: selectedType !== 'all' ? selectedType : undefined,
        }),
    api.getCategories(),
    api.getTags(),
  ]);

  paginatedPosts = pageResult.items;
  totalPosts = pageResult.total;
  totalPages = pageResult.totalPages;
  currentPage = pageResult.page;
  allCategories = categories;

  const seenTagIds = new Set<string>();
  allTags = rawTags.filter((tag) => {
    const key = `${tag.slug}:${tag.name}`.toLowerCase();
    if (seenTagIds.has(key)) return false;
    seenTagIds.add(key);
    return true;
  });
} catch (error) {
  console.error('API Error:', error);
}

const normalizedSelectedTag = selectedTag.trim().toLowerCase();
const isSelectedTag = (tag: Tag) =>
  tag.name.trim().toLowerCase() === normalizedSelectedTag ||
  tag.slug.trim().toLowerCase() === normalizedSelectedTag;

const postTypeFilters = [
  { id: 'all', name: t('common.all'), icon: 'fa-stream' },
  { id: 'article', name: t('common.article'), icon: 'fa-file-alt' },
  { id: 'tweet', name: t('common.tweet'), icon: 'fa-comment-dots' },
];

const typePromptCommand =
  selectedType === 'all'
    ? `grep -E "^type: (article|tweet)$" ./posts/*.md`
    : `grep -E "^type: ${selectedType}$" ./posts/*.md`;
const categoryPromptCommand = selectedCategory
  ? `grep -El "^category: ${selectedCategory}$" ./posts/*.md`
  : `cut -d: -f2 ./categories.index | sort -u`;
const tagPromptCommand = selectedTag
  ? `grep -Ril "#${selectedTag}" ./posts`
  : `cut -d: -f2 ./tags.index | sort -u`;
const hasActiveFilters =
  Boolean(selectedSearch || selectedTag || selectedCategory || selectedType !== 'all' || currentPage > 1);
const canonicalUrl = hasActiveFilters ? '/articles' : undefined;

const buildArticlesUrl = ({
  type = selectedType,
  search = selectedSearch,
  tag = selectedTag,
  category = selectedCategory,
  page,
}: {
  type?: string;
  search?: string;
  tag?: string;
  category?: string;
  page?: number;
}) => {
  const params = new URLSearchParams();

  if (type && type !== 'all') params.set('type', type);
  if (search) params.set('search', search);
  if (tag) params.set('tag', tag);
  if (category) params.set('category', category);
  if (page && page > 1) params.set('page', String(page));

  const queryString = params.toString();
  return queryString ? `/articles?${queryString}` : '/articles';
};
---

<BaseLayout
  title={`${t('articlesPage.title')} - Termi`}
  canonical={canonicalUrl}
  noindex={hasActiveFilters}
>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/articles/index" class="w-full">
      <div class="px-4 pb-2">
        <CommandPrompt command="find ./posts -type f -name '*.md' | sort" />

        <div class="ml-4 mt-4 space-y-3">
          <h1 class="text-3xl font-bold tracking-tight text-[var(--title-color)]">{t('articlesPage.title')}</h1>
          <p class="max-w-2xl text-sm leading-7 text-[var(--text-secondary)]">
            {t('articlesPage.description')}
          </p>
          <div class="flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-file-lines text-[var(--primary)]"></i>
              <span>{t('articlesPage.totalPosts', { count: totalPosts })}</span>
            </span>
            {selectedSearch && (
              <span class="terminal-stat-pill">
                <i class="fas fa-magnifying-glass text-[var(--primary)]"></i>
                grep: {selectedSearch}
              </span>
            )}
            {selectedCategory && (
              <span
                class="terminal-stat-pill terminal-stat-pill--accent"
                style={getAccentVars(getCategoryTheme(selectedCategory))}
              >
                <i class="fas fa-folder-open"></i>
                <span>{selectedCategory}</span>
              </span>
            )}
            {selectedTag && (
              <span
                class="terminal-stat-pill terminal-stat-pill--accent"
                style={getAccentVars(getTagTheme(selectedTag))}
              >
                <i class="fas fa-hashtag"></i>
                <span>{selectedTag}</span>
              </span>
            )}
          </div>
        </div>
      </div>

      <div class="px-4 pb-2 space-y-4">
        <div class="ml-4">
          <CommandPrompt promptId="articles-type-prompt" command={typePromptCommand} typing={false} />
          <div class="mt-3 flex flex-wrap gap-3">
            {postTypeFilters.map((filter) => (
              <FilterPill
                href={buildArticlesUrl({ type: filter.id, page: 1 })}
                tone={filter.id === 'all' ? 'neutral' : 'accent'}
                active={selectedType === filter.id}
                style={filter.id === 'all' ? undefined : getAccentVars(getPostTypeTheme(filter.id))}
              >
                <i class={`fas ${filter.icon}`}></i>
                <span class="font-medium">{filter.name}</span>
              </FilterPill>
            ))}
          </div>
        </div>

        {allCategories.length > 0 && (
          <div class="ml-4">
            <CommandPrompt promptId="articles-category-prompt" command={categoryPromptCommand} typing={false} />
            <div class="mt-3 flex flex-wrap gap-3">
              <FilterPill href={buildArticlesUrl({ category: '', page: 1 })} tone="amber" active={!selectedCategory}>
                <i class="fas fa-folder-tree"></i>
                <span class="font-medium">{t('articlesPage.allCategories')}</span>
              </FilterPill>
              {allCategories.map((category) => (
                <FilterPill
                  href={buildArticlesUrl({ category: category.name, page: 1 })}
                  tone="accent"
                  active={selectedCategory.toLowerCase() === category.name.toLowerCase()}
                  style={getAccentVars(getCategoryTheme(category.name))}
                >
                  <i class="fas fa-folder-open"></i>
                  <span class="font-medium">{category.name}</span>
                  <span class="text-xs text-[var(--text-tertiary)]">{category.count}</span>
                </FilterPill>
              ))}
            </div>
          </div>
        )}

        {allTags.length > 0 && (
          <div class="ml-4">
            <CommandPrompt promptId="articles-tag-prompt" command={tagPromptCommand} typing={false} />
            <div class="mt-3 flex flex-wrap gap-3">
              <FilterPill href={buildArticlesUrl({ tag: '', page: 1 })} tone="teal" active={!selectedTag}>
                <i class="fas fa-hashtag"></i>
                <span class="font-medium">{t('articlesPage.allTags')}</span>
              </FilterPill>
              {allTags.map((tag) => (
                <FilterPill
                  href={buildArticlesUrl({ tag: tag.slug || tag.name, page: 1 })}
                  tone="accent"
                  active={isSelectedTag(tag)}
                  style={getAccentVars(getTagTheme(tag.name))}
                >
                  <i class="fas fa-hashtag"></i>
                  <span class="font-medium">{tag.name}</span>
                </FilterPill>
              ))}
            </div>
          </div>
        )}
      </div>

      <div class="px-4">
        {paginatedPosts.length > 0 ? (
          <div class="ml-4 mt-4 space-y-4">
            {paginatedPosts.map((post) => (
              <PostCard post={post} selectedTag={selectedTag} highlightTerm={selectedSearch} />
            ))}
          </div>
        ) : null}
        <div class:list={['terminal-empty ml-4 mt-4', totalPosts > 0 && 'hidden']}>
          <div class="mx-auto flex max-w-md flex-col items-center gap-3">
            <span class="terminal-section-icon">
              <i class="fas fa-folder-open"></i>
            </span>
            <h2 class="text-xl font-semibold text-[var(--title-color)]">{t('articlesPage.emptyTitle')}</h2>
            <p class="text-sm leading-7 text-[var(--text-secondary)]">
              {t('articlesPage.emptyDescription')}
            </p>
            <a href="/articles" class="terminal-action-button terminal-action-button-primary">
              <i class="fas fa-rotate-left"></i>
              <span>{t('common.resetFilters')}</span>
            </a>
          </div>
        </div>
      </div>

      <div class="px-4 py-6">
        <div class:list={['terminal-panel-muted ml-4 mt-4 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between', totalPages <= 1 && 'hidden']}>
          <span class="text-sm text-[var(--text-secondary)]">
            {t('articlesPage.pageSummary', { current: currentPage, total: totalPages, count: totalPosts })}
          </span>
          <div class="flex flex-wrap gap-2">
            {currentPage > 1 && (
              <a href={buildArticlesUrl({ page: currentPage - 1 })} class="terminal-action-button">
                <i class="fas fa-chevron-left"></i>
                <span>{t('articlesPage.previous')}</span>
              </a>
            )}
            {currentPage < totalPages && (
              <a href={buildArticlesUrl({ page: currentPage + 1 })} class="terminal-action-button terminal-action-button-primary">
                <span>{t('articlesPage.next')}</span>
                <i class="fas fa-chevron-right"></i>
              </a>
            )}
          </div>
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
