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

export const prerender = false;

let categories: Awaited<ReturnType<typeof api.getCategories>> = [];
let allPosts: Post[] = [];
const url = new URL(Astro.request.url);
const selectedCategoryParam = url.searchParams.get('category') || '';
const { t } = getI18n(Astro);

try {
  [categories, allPosts] = await Promise.all([
    api.getCategories(),
    api.getPosts(),
  ]);
} catch (error) {
  console.error('Failed to fetch categories:', error);
}

const selectedCategoryRecord = categories.find((category) => {
  const wanted = selectedCategoryParam.trim().toLowerCase();
  if (!wanted) return false;
  return [category.name, category.slug].some(
    (value) => (value || '').trim().toLowerCase() === wanted
  );
}) || null;
const selectedCategory = selectedCategoryRecord?.name || selectedCategoryParam;
const normalizedSelectedCategory = selectedCategory.trim().toLowerCase();
const filteredPosts = selectedCategory
  ? allPosts.filter((post) => (post.category || '').trim().toLowerCase() === normalizedSelectedCategory)
  : [];
const categoryPromptCommand = selectedCategory
  ? `grep -El "^category: ${selectedCategory}$" ./posts/*.md`
  : 'cut -d: -f2 ./categories.index | sort -u';
const resultsPromptCommand = selectedCategory
  ? `find ./posts -type f | xargs grep -il "^category: ${selectedCategory}$"`
  : 'find ./posts -type f | sort';
const categoryAccentMap = Object.fromEntries(
  categories.map((category) => [category.name.trim().toLowerCase(), getAccentVars(getCategoryTheme(category.name))])
);
const pageTitle = selectedCategoryRecord?.seoTitle || t('categories.pageTitle');
const pageDescription = selectedCategoryRecord?.seoDescription || selectedCategoryRecord?.description;
---

<BaseLayout
  title={`${pageTitle} - Termi`}
  description={pageDescription}
  ogImage={selectedCategoryRecord?.coverImage}
>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/categories" class="w-full">
      <div class="mb-6 px-4">
        <CommandPrompt command="find ./categories -maxdepth 1 -type d | sort" />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">content taxonomy</div>
          <div class="terminal-section-title mt-4">
            <span class="terminal-section-icon">
              <i class="fas fa-folder-open"></i>
            </span>
            <div>
              <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('categories.title')}</h1>
              <p class="mt-2 max-w-2xl text-sm leading-6 text-[var(--text-secondary)]">
                {t('categories.intro')}
              </p>
            </div>
          </div>
          <div class="mt-5 flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-layer-group text-[var(--primary)]"></i>
              <span>{t('common.categoriesCount', { count: categories.length })}</span>
            </span>
            <span class="terminal-stat-pill">
              <i class="fas fa-terminal text-[var(--primary)]"></i>
              <span>{t('categories.quickJump')}</span>
            </span>
            <span
              id="categories-current-pill"
              class:list={['terminal-stat-pill terminal-stat-pill--accent', !selectedCategory && 'hidden']}
              style={selectedCategory ? getAccentVars(getCategoryTheme(selectedCategory)) : undefined}
            >
              <i class="fas fa-folder-open"></i>
              <span id="categories-current-label">{selectedCategory}</span>
            </span>
          </div>
        </div>
      </div>

      <div class="px-4 space-y-6">
        <div class="ml-4">
          <CommandPrompt promptId="categories-filter-prompt" command={categoryPromptCommand} typing={false} />
          {categories.length > 0 ? (
            <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              <a
                href="/categories"
                data-category-filter=""
                class:list={[
                  'terminal-panel terminal-interactive-card group p-5',
                  !selectedCategory && 'is-active'
                ]}
              >
                <div class="flex items-start gap-4">
                  <div class="terminal-accent-icon shrink-0 flex h-12 w-12 items-center justify-center rounded-2xl border">
                    <i class="fas fa-layer-group text-lg"></i>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-start justify-between gap-3 mb-2">
                      <div>
                        <div class="text-[11px] uppercase tracking-[0.22em] text-[var(--text-tertiary)] mb-1">
                          all
                        </div>
                        <h2 class="font-bold text-[var(--title-color)] transition-colors text-lg">
                          {t('articlesPage.allCategories')}
                        </h2>
                      </div>
                      <span class="terminal-chip text-xs py-1 px-2.5">
                        <span>{t('common.postsCount', { count: allPosts.length })}</span>
                      </span>
                    </div>
                    <p class="text-sm leading-6 text-[var(--text-secondary)]">
                      {t('categories.allCategoriesDescription')}
                    </p>
                  </div>
                </div>
              </a>

              {categories.map((category) => (
                <a
                  href={`/categories?category=${encodeURIComponent(category.name)}`}
                  data-category-filter={category.name}
                  class:list={[
                    'terminal-panel terminal-panel-accent terminal-interactive-card group p-5',
                    normalizedSelectedCategory === category.name.trim().toLowerCase() && 'is-active'
                  ]}
                  style={getAccentVars(getCategoryTheme(category.name))}
                >
                  <div class="flex items-start gap-4">
                    <div class="terminal-accent-icon shrink-0 flex h-12 w-12 items-center justify-center rounded-2xl border">
                      <i class="fas fa-folder-open text-lg"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-start justify-between gap-3 mb-2">
                        <div>
                          <div class="text-[11px] uppercase tracking-[0.22em] text-[var(--text-tertiary)] mb-1">
                            {category.slug || category.name}
                          </div>
                          <h2 class="font-bold text-[var(--title-color)] group-hover:text-[var(--primary)] transition-colors text-lg">
                            {category.name}
                          </h2>
                        </div>
                        <span class="terminal-chip terminal-chip--accent text-xs py-1 px-2.5" style={getAccentVars(getCategoryTheme(category.name))}>
                          <span>{t('common.postsCount', { count: category.count })}</span>
                        </span>
                      </div>
                      <p class="text-sm leading-6 text-[var(--text-secondary)]">
                        {t('categories.categoryPosts', { name: category.name })}
                      </p>
                    </div>
                  </div>
                </a>
              ))}
            </div>
          ) : (
            <div class="terminal-empty mt-4">
              <i class="fas fa-inbox text-4xl mb-4 opacity-50 text-[var(--primary)]"></i>
              <p class="text-[var(--text-secondary)]">{t('categories.empty')}</p>
            </div>
          )}
        </div>

        <div id="categories-results-wrap" class:list={['ml-4', !selectedCategory && 'hidden']}>
          <CommandPrompt promptId="categories-results-prompt" command={resultsPromptCommand} typing={false} />
          <div class="mt-4 terminal-panel">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <p id="categories-selected-summary" class="text-sm leading-6 text-[var(--text-secondary)]">
                {selectedCategory ? t('categories.selectedSummary', { name: selectedCategory, count: filteredPosts.length }) : ''}
              </p>
              <a id="categories-clear-btn" href="/categories" class:list={['terminal-link-arrow', !selectedCategory && 'hidden']}>
                <span>{t('common.clearFilters')}</span>
                <i class="fas fa-rotate-left text-xs"></i>
              </a>
            </div>
            {selectedCategoryRecord && (selectedCategoryRecord.description || selectedCategoryRecord.coverImage) ? (
              <div class="mt-4 grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_280px]">
                <div class="space-y-3 text-sm leading-6 text-[var(--text-secondary)]">
                  {selectedCategoryRecord.description ? (
                    <p>{selectedCategoryRecord.description}</p>
                  ) : null}
                  {selectedCategoryRecord.accentColor ? (
                    <div class="flex items-center gap-3 text-xs uppercase tracking-[0.18em] text-[var(--text-tertiary)]">
                      <span class="inline-flex h-3 w-3 rounded-full border border-[var(--border-color)]" style={`background:${selectedCategoryRecord.accentColor}`}></span>
                      <span>{selectedCategoryRecord.accentColor}</span>
                    </div>
                  ) : null}
                </div>
                {selectedCategoryRecord.coverImage ? (
                  <img
                    src={selectedCategoryRecord.coverImage}
                    alt={selectedCategoryRecord.name}
                    class="h-full w-full rounded-2xl border border-[var(--border-color)] object-cover"
                  />
                ) : null}
              </div>
            ) : null}
          </div>
        </div>

        <div class="ml-4">
          {allPosts.length > 0 ? (
            <div id="categories-posts-list" class:list={['divide-y divide-[var(--border-color)]', !selectedCategory && 'hidden']}>
              {allPosts.map((post) => {
                const matchesInitial = selectedCategory
                  ? (post.category || '').trim().toLowerCase() === normalizedSelectedCategory
                  : false;

                return (
                  <div
                    data-category-post
                    data-category-name={(post.category || '').trim().toLowerCase()}
                    class:list={[!matchesInitial && 'hidden']}
                  >
                    <PostCard post={post} />
                  </div>
                );
              })}
            </div>
          ) : null}

          <div id="categories-empty-state" class:list={['terminal-empty', (!selectedCategory || filteredPosts.length > 0) && 'hidden']}>
            <i class="fas fa-search text-4xl mb-4 opacity-50 text-[var(--primary)]"></i>
            <p class="text-[var(--text-secondary)]">{t('categories.emptyPosts')}</p>
          </div>
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>

<script
  is:inline
  define:vars={{
    categoryAccentMap,
    initialSelectedCategory: selectedCategory,
  }}
>
  (function() {
    /** @type {Window['__termiCommandPrompt']} */
    let promptApi;

    const categoryButtons = Array.from(document.querySelectorAll('[data-category-filter]'));
    const postCards = Array.from(document.querySelectorAll('[data-category-post]'));
    const currentPill = document.getElementById('categories-current-pill');
    const currentLabel = document.getElementById('categories-current-label');
    const resultsWrap = document.getElementById('categories-results-wrap');
    const selectedSummary = document.getElementById('categories-selected-summary');
    const postsList = document.getElementById('categories-posts-list');
    const emptyState = document.getElementById('categories-empty-state');
    const clearBtn = document.getElementById('categories-clear-btn');
    const t = window.__termiTranslate;

    promptApi = window.__termiCommandPrompt;

    const state = {
      category: initialSelectedCategory || '',
    };

    function updatePrompts() {
      const filterCommand = state.category
        ? `grep -El "^category: ${state.category}$" ./posts/*.md`
        : 'cut -d: -f2 ./categories.index | sort -u';
      const resultsCommand = state.category
        ? `find ./posts -type f | xargs grep -il "^category: ${state.category}$"`
        : 'find ./posts -type f | sort';

      promptApi?.set?.('categories-filter-prompt', filterCommand, { typing: false });
      promptApi?.set?.('categories-results-prompt', resultsCommand, { typing: false });
    }

    function updateUrl() {
      const params = new URLSearchParams();
      if (state.category) params.set('category', state.category);
      const nextUrl = params.toString() ? `/categories?${params.toString()}` : '/categories';
      window.history.replaceState({}, '', nextUrl);
    }

    function syncButtons() {
      const activeValue = state.category.trim().toLowerCase();

      categoryButtons.forEach((button) => {
        const value = (button.getAttribute('data-category-filter') || '').trim().toLowerCase();
        const isActive = activeValue ? value === activeValue : value === '';
        button.classList.toggle('is-active', isActive);
      });
    }

    function applyCategoryFilter(pushHistory = true) {
      const activeValue = state.category.trim().toLowerCase();
      let visibleCount = 0;

      postCards.forEach((card) => {
        const value = (card.getAttribute('data-category-name') || '').trim().toLowerCase();
        const matches = Boolean(activeValue) && value === activeValue;
        card.classList.toggle('hidden', !matches);
        if (matches) {
          visibleCount += 1;
        }
      });

      syncButtons();
      updatePrompts();

      if (currentPill && currentLabel) {
        currentPill.classList.toggle('hidden', !state.category);
        if (state.category) {
          currentLabel.textContent = state.category;
          currentPill.setAttribute('style', categoryAccentMap[String(state.category).trim().toLowerCase()] || '');
        } else {
          currentLabel.textContent = '';
          currentPill.removeAttribute('style');
        }
      }

      resultsWrap?.classList.toggle('hidden', !state.category);
      postsList?.classList.toggle('hidden', !state.category);
      emptyState?.classList.toggle('hidden', !state.category || visibleCount > 0);
      clearBtn?.classList.toggle('hidden', !state.category);

      if (selectedSummary) {
        selectedSummary.textContent = state.category
          ? t('categories.selectedSummary', { name: state.category, count: visibleCount })
          : '';
      }

      if (pushHistory) {
        updateUrl();
      }
    }

    categoryButtons.forEach((button) => {
      button.addEventListener('click', (event) => {
        event.preventDefault();
        const nextValue = button.getAttribute('data-category-filter') || '';
        const normalizedCurrent = state.category.trim().toLowerCase();
        state.category = normalizedCurrent === nextValue.trim().toLowerCase() ? '' : nextValue;
        applyCategoryFilter();
      });
    });

    clearBtn?.addEventListener('click', (event) => {
      event.preventDefault();
      state.category = '';
      applyCategoryFilter();
    });

    applyCategoryFilter(false);
  })();
</script>
