---
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 { apiClient } from '../../lib/api/client';
import { getI18n, formatReadTime } from '../../lib/i18n';
import type { Post, Tag } from '../../lib/types';
import { getAccentVars, getCategoryTheme, getPostTypeTheme, getTagTheme } from '../../lib/utils';

export const prerender = false;

// Fetch tags from backend
let tags: Tag[] = [];
let allPosts: Post[] = [];
const { locale, t } = getI18n(Astro);

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

// Get URL params
const url = new URL(Astro.request.url);
const selectedTagParam = url.searchParams.get('tag') || '';
const selectedTagRecord = tags.find((tag) => {
  const wanted = selectedTagParam.trim().toLowerCase();
  if (!wanted) return false;
  return [tag.name, tag.slug].some((value) => (value || '').trim().toLowerCase() === wanted);
}) || null;
const selectedTag = selectedTagRecord?.name || selectedTagParam;
const selectedTagToken = selectedTag.trim().toLowerCase();
const selectedTagTheme = getTagTheme(selectedTag);
const isSelectedTag = (tag: Tag) =>
  tag.name.trim().toLowerCase() === selectedTagToken || tag.slug.trim().toLowerCase() === selectedTagToken;

const filteredPosts = selectedTag
  ? allPosts.filter((post) => post.tags?.some((tag) => (tag || '').trim().toLowerCase() === selectedTagToken))
  : [];
const tagAccentMap = Object.fromEntries(
  tags.map((tag) => [String(tag.slug || tag.name).toLowerCase(), getAccentVars(getTagTheme(tag.name))])
);
const pageTitle = selectedTagRecord?.seoTitle || t('tags.pageTitle');
const pageDescription = selectedTagRecord?.seoDescription || selectedTagRecord?.description;
---

<BaseLayout
  title={`${pageTitle} - Termi`}
  description={pageDescription}
  ogImage={selectedTagRecord?.coverImage}
>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/tags" class="w-full">
      <div class="mb-6 px-4">
        <CommandPrompt command="cut -d',' -f1 tags.index | sort -u" />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">tag index</div>
          <div class="terminal-section-title mt-4">
            <span class="terminal-section-icon">
              <i class="fas fa-hashtag"></i>
            </span>
            <div>
              <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('tags.title')}</h1>
              <p class="mt-2 max-w-2xl text-sm leading-6 text-[var(--text-secondary)]">
                {t('tags.intro')}
              </p>
            </div>
          </div>
          <div class="mt-5 flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-tags text-[var(--primary)]"></i>
              <span>{t('common.tagsCount', { count: tags.length })}</span>
            </span>
            <span
              id="tags-current-pill"
              class:list={['terminal-stat-pill terminal-stat-pill--accent', !selectedTag && 'hidden']}
              style={selectedTag ? getAccentVars(selectedTagTheme) : undefined}
            >
              <i class="fas fa-filter"></i>
              <span id="tags-current-label">{selectedTag ? t('tags.currentTag', { tag: selectedTag }) : ''}</span>
            </span>
          </div>
        </div>
      </div>

        <div id="tags-summary-section" class:list={['mb-6 px-4', !selectedTag && 'hidden']}>
          <CommandPrompt promptId="tags-match-prompt" command={selectedTag ? `grep -Ril "#${selectedTag}" ./posts` : 'grep -Ril "#tag" ./posts'} />
          <div class="terminal-panel ml-4 mt-4">
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
              <p id="tags-selected-summary" class="text-[var(--text-secondary)] leading-6">
                {t('tags.selectedSummary', { tag: selectedTag, count: filteredPosts.length })}
              </p>
              <a id="tags-clear-btn" href="/tags" class="ui-filter-pill ui-filter-pill--teal">
                <i class="fas fa-times"></i>
                <span>{t('common.clearFilters')}</span>
              </a>
            </div>
            {selectedTagRecord && (selectedTagRecord.description || selectedTagRecord.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)]">
                  {selectedTagRecord.description ? <p>{selectedTagRecord.description}</p> : null}
                  {selectedTagRecord.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:${selectedTagRecord.accentColor}`}></span>
                      <span>{selectedTagRecord.accentColor}</span>
                    </div>
                  ) : null}
                </div>
                {selectedTagRecord.coverImage ? (
                  <img
                    src={selectedTagRecord.coverImage}
                    alt={selectedTagRecord.name}
                    class="h-full w-full rounded-2xl border border-[var(--border-color)] object-cover"
                  />
                ) : null}
              </div>
            ) : null}
          </div>
        </div>

      <div class="px-4 mb-8">
        <div class="terminal-panel ml-4 mt-4">
          <div class="text-[11px] uppercase tracking-[0.22em] text-[var(--text-tertiary)] mb-4">
            {t('tags.browseTags')}
          </div>
          <div class="flex flex-wrap gap-2">
          {tags.length === 0 ? (
              <div class="terminal-empty w-full">
                {t('tags.emptyTags')}
              </div>
            ) : (
              tags.map(tag => (
                <FilterPill
                  tone="accent"
                  active={isSelectedTag(tag)}
                  href={`/tags?tag=${encodeURIComponent(tag.slug || tag.name || '')}`}
                  data-tag-filter={tag.slug || tag.name || ''}
                  style={getAccentVars(getTagTheme(tag.name))}
                >
                  <i class="fas fa-hashtag"></i>
                  <span>{tag.name}</span>
                </FilterPill>
              ))
            )}
          </div>
        </div>
      </div>

        <div class="px-4">
          <div id="tags-results-section" class:list={['border-t border-[var(--border-color)] pt-6', !selectedTag && 'hidden']}>
            <CommandPrompt promptId="tags-results-prompt" command={selectedTag ? `find ./posts -type f | xargs grep -il "#${selectedTag}"` : "find ./posts -type f | sort"} />
            <div class="ml-4 mt-4 space-y-4">
              {allPosts.map((post) => {
                const matchesInitial = selectedTag
                  ? post.tags?.some((tag) => (tag || '').trim().toLowerCase() === selectedTagToken)
                  : false;

                return (
                  <a
                    href={`/articles/${post.slug}`}
                    data-tag-post
                    data-tags={post.tags.map((tag) => (tag || '').trim().toLowerCase()).join('|')}
                    class:list={[
                      'terminal-panel terminal-panel-accent terminal-interactive-card block p-5',
                      !matchesInitial && 'hidden'
                    ]}
                    style={getAccentVars(getPostTypeTheme(post.type))}
                  >
                    <div class="flex flex-wrap items-center gap-2 mb-2">
                      <span class="terminal-chip terminal-chip--accent text-[10px] py-1 px-2" style={getAccentVars(getPostTypeTheme(post.type))}>
                        {post.type === 'article' ? t('common.article') : t('common.tweet')}
                      </span>
                      <h3 class="font-bold text-[var(--title-color)] text-lg">{post.title}</h3>
                      <span class="terminal-chip terminal-chip--accent text-xs py-1 px-2.5" style={getAccentVars(getCategoryTheme(post.category))}>
                        <span>{post.category}</span>
                      </span>
                    </div>
                    <p class="text-sm text-[var(--text-secondary)]">{post.date} | {formatReadTime(locale, post.readTime, t)}</p>
                    <p class="text-sm text-[var(--text-secondary)] mt-3 leading-6">{post.description}</p>
                    <div class="mt-4 terminal-link-arrow">
                      <span>{t('common.viewArticle')}</span>
                      <i class="fas fa-arrow-right text-xs"></i>
                    </div>
                  </a>
                );
              })}
            </div>
          </div>
        </div>

        <div class="px-4">
          <div id="tags-empty-wrap" class:list={['border-t border-[var(--border-color)] pt-6', (!selectedTag || filteredPosts.length > 0) && 'hidden']}>
            <div id="tags-empty-state" class="terminal-empty ml-4 mt-4">
              <i class="fas fa-search text-4xl text-[var(--text-tertiary)] mb-4"></i>
              <p class="text-[var(--text-secondary)]">{t('tags.emptyPosts')}</p>
            </div>
          </div>
        </div>
    </TerminalWindow>
  </div>
</BaseLayout>

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

    const tagButtons = Array.from(document.querySelectorAll('[data-tag-filter]'));
    const tagPosts = Array.from(document.querySelectorAll('[data-tag-post]'));
    const currentPill = document.getElementById('tags-current-pill');
    const currentLabel = document.getElementById('tags-current-label');
    const summarySection = document.getElementById('tags-summary-section');
    const selectedSummary = document.getElementById('tags-selected-summary');
    const resultsSection = document.getElementById('tags-results-section');
    const emptyWrap = document.getElementById('tags-empty-wrap');
    const clearBtn = document.getElementById('tags-clear-btn');
    const t = window.__termiTranslate;

    promptApi = window.__termiCommandPrompt;

    const state = {
      tag: initialSelectedTag || '',
    };

    function syncTagButtons() {
      tagButtons.forEach((button) => {
        const value = (button.getAttribute('data-tag-filter') || '').trim().toLowerCase();
        button.classList.toggle('is-active', Boolean(state.tag) && value === state.tag.toLowerCase());
      });
    }

    function updateTagPrompts() {
      const matchCommand = state.tag
        ? `grep -Ril "#${state.tag}" ./posts`
        : 'grep -Ril "#tag" ./posts';
      const resultCommand = state.tag
        ? `find ./posts -type f | xargs grep -il "#${state.tag}"`
        : "find ./posts -type f | sort";

      promptApi?.set?.('tags-match-prompt', matchCommand, { typing: false });
      promptApi?.set?.('tags-results-prompt', resultCommand, { typing: false });
    }

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

    function applyTagFilter(pushHistory = true) {
      const normalizedTag = state.tag.trim().toLowerCase();
      let visibleCount = 0;

      tagPosts.forEach((post) => {
        const tags = `|${(post.getAttribute('data-tags') || '').toLowerCase()}|`;
        const matches = normalizedTag ? tags.includes(`|${normalizedTag}|`) : false;
        post.classList.toggle('hidden', !matches);
        if (matches) {
          visibleCount += 1;
        }
      });

      syncTagButtons();
      updateTagPrompts();

      if (currentPill && currentLabel) {
        currentPill.classList.toggle('hidden', !state.tag);
        if (state.tag) {
          currentLabel.textContent = t('tags.currentTag', { tag: state.tag });
          currentPill.setAttribute('style', tagAccentMap[String(state.tag).toLowerCase()] || '');
        } else {
          currentLabel.textContent = '';
          currentPill.removeAttribute('style');
        }
      }

      if (summarySection) {
        summarySection.classList.toggle('hidden', !state.tag);
      }
      if (resultsSection) {
        resultsSection.classList.toggle('hidden', !state.tag);
      }
      if (selectedSummary) {
        selectedSummary.textContent = state.tag
          ? t('tags.selectedSummary', { tag: state.tag, count: visibleCount })
          : '';
      }
      if (emptyWrap) {
        emptyWrap.classList.toggle('hidden', !state.tag || visibleCount > 0);
      }
      if (clearBtn) {
        clearBtn.classList.toggle('hidden', !state.tag);
      }

      if (pushHistory) {
        updateTagUrl();
      }
    }

    tagButtons.forEach((button) => {
      button.addEventListener('click', (event) => {
        event.preventDefault();
        state.tag = button.getAttribute('data-tag-filter') || '';
        applyTagFilter();
      });
    });

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

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