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

export const prerender = false;

let siteSettings = DEFAULT_SITE_SETTINGS;
let posts: Post[] = [];
const { locale, t } = getI18n(Astro);

try {
  [siteSettings, posts] = await Promise.all([
    api.getSiteSettings(),
    api.getPosts(),
  ]);
} catch (error) {
  console.error('Failed to load timeline:', error);
}

const groupedByYear = posts.reduce((acc: Record<number, Post[]>, post) => {
  const year = new Date(post.date).getFullYear();
  if (!acc[year]) acc[year] = [];
  acc[year].push(post);
  return acc;
}, {});

const years = Object.keys(groupedByYear).sort((a, b) => Number(b) - Number(a));
const latestYear = years[0] || 'all';
---

<Layout title={`${t('timeline.pageTitle')} | ${siteSettings.siteShortName}`} description={t('timeline.pageDescription', { ownerName: siteSettings.ownerName })}>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/timeline" class="w-full">
      <div class="px-4 py-4 space-y-6">
        <div>
          <CommandPrompt command="tail -n +1 ~/timeline.log" path="~" />
          <div class="terminal-panel ml-4 mt-4">
            <div class="terminal-kicker">activity trace</div>
            <div class="terminal-section-title mt-4">
              <span class="terminal-section-icon">
              <i class="fas fa-stream"></i>
            </span>
            <div>
                <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('timeline.title')}</h1>
                <p class="mt-2 text-sm leading-6 text-[var(--text-secondary)]">
                  {t('timeline.subtitle', { count: posts.length, ownerName: siteSettings.ownerName })}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div>
          <CommandPrompt promptId="timeline-filter-prompt" command="cut -d'-' -f1 timeline.log | sort -ru" path="~/timeline" />
          <div class="ml-4 mt-4 flex flex-wrap gap-2">
            <FilterPill
              class="timeline-filter"
              tone="neutral"
              data-year="all"
              active={false}
            >
              {t('timeline.allYears')}
            </FilterPill>
            {years.map(year => (
              <FilterPill
                class="timeline-filter"
                tone="blue"
                data-year={year}
                active={year === latestYear}
              >
                <i class="fas fa-calendar-alt"></i>
                {year}
                <span class="ml-1 text-[var(--text-tertiary)]">[{groupedByYear[Number(year)].length}]</span>
              </FilterPill>
            ))}
          </div>
        </div>

        <div>
          <CommandPrompt promptId="timeline-log-prompt" command="git log --oneline --date=short --all" path="~/timeline" />
          <div class="ml-4 mt-2 space-y-8">
            {years.map(year => (
              <div class="timeline-year-group relative" data-year={year}>
                <div class="sticky top-20 z-10 mb-4">
                  <div class="inline-flex items-center gap-2 rounded-xl border border-[var(--border-color)] bg-[var(--terminal-bg)] px-4 py-2 font-mono text-sm">
                    <i class="fas fa-calendar-alt text-[var(--primary)]"></i>
                    <span class="font-bold text-[var(--text)]">{year}</span>
                  </div>
                </div>

                <div class="relative pl-8 space-y-4">
                  <div class="absolute left-3 top-0 bottom-0 w-px" style="background: linear-gradient(180deg, color-mix(in oklab, var(--primary) 60%, transparent), var(--border-color), transparent);"></div>

                  {groupedByYear[Number(year)].map(post => (
                    <div class="relative group">
                      <div class="absolute -left-[1.625rem] top-4 h-3.5 w-3.5 rounded-full bg-[var(--bg)] border-2 border-[var(--primary)] z-10 group-hover:bg-[var(--primary)] group-hover:scale-125 transition-all"></div>

                      <a
                        href={`/articles/${post.slug}`}
                        class="terminal-panel terminal-panel-accent group flex items-start gap-4 p-4 hover:translate-x-2 transition-all"
                        style={getAccentVars(getPostTypeTheme(post.type))}
                      >
                        <div class="terminal-panel-muted shrink-0 min-w-[72px] text-center py-3">
                          <div class="text-[11px] uppercase tracking-[0.2em] text-[var(--text-tertiary)]">
                            {new Date(post.date).toLocaleDateString(locale, { month: 'short' })}
                          </div>
                          <div class="mt-1 text-2xl font-bold text-[var(--primary)]">
                            {new Date(post.date).getDate()}
                          </div>
                        </div>

                        <div class="flex-1 min-w-0">
                          <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>
                            <h2 class="font-bold text-[var(--title-color)] group-hover:text-[var(--primary)] transition-colors truncate text-lg">
                              {post.title}
                            </h2>
                          </div>
                          <p class="text-sm text-[var(--text-secondary)] line-clamp-2 leading-6">{post.description}</p>
                          <div class="flex items-center gap-2 mt-2 flex-wrap">
                            <span class="terminal-chip terminal-chip--accent text-xs py-1 px-2.5" style={getAccentVars(getCategoryTheme(post.category))}>
                              {post.category}
                            </span>
                            <span class="terminal-chip text-xs py-1 px-2.5">
                              {formatReadTime(locale, post.readTime, t)}
                            </span>
                          </div>
                        </div>
                      </a>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div class="pt-4 border-t border-[var(--border-color)]">
          <a href="/" class="terminal-subtle-link">
            <i class="fas fa-chevron-left"></i>
            <span class="font-mono">cd ~</span>
          </a>
        </div>
      </div>
    </TerminalWindow>
  </div>
</Layout>

<script>
  declare global {
    interface Window {
      __termiCommandPrompt?: {
        set?: (promptId: string, command: string, options?: { typing?: boolean }) => void;
      };
    }
  }

  const filterButtons = document.querySelectorAll('.timeline-filter');
  const yearGroups = document.querySelectorAll('.timeline-year-group');
  const promptApi = window.__termiCommandPrompt;

  function applyTimelineFilter(year: string | null, updateUi = true) {
    const selectedYear = year || 'all';
    const filterCommand = selectedYear === 'all'
      ? "cut -d'-' -f1 timeline.log | sort -ru"
      : `grep '^${selectedYear}-' timeline.log`;
    const logCommand = selectedYear === 'all'
      ? 'git log --oneline --date=short --all'
      : `git log --oneline --date=short --since '${selectedYear}-01-01' --until '${selectedYear}-12-31'`;

    if (updateUi) {
      filterButtons.forEach((item) => {
        item.classList.toggle('is-active', item.getAttribute('data-year') === selectedYear);
      });

      yearGroups.forEach((group) => {
        const matches = selectedYear === 'all' || group.getAttribute('data-year') === selectedYear;
        group.classList.toggle('hidden', !matches);
      });
    }

    promptApi?.set?.('timeline-filter-prompt', filterCommand, { typing: false });
    promptApi?.set?.('timeline-log-prompt', logCommand, { typing: false });
  }

  filterButtons.forEach(button => {
    button.addEventListener('click', () => {
      const year = button.getAttribute('data-year');
      applyTimelineFilter(year);
    });
  });

  const initialActiveYear =
    document.querySelector('.timeline-filter.is-active')?.getAttribute('data-year') ||
    new URL(window.location.href).searchParams.get('year') ||
    'all';
  applyTimelineFilter(initialActiveYear);
</script>
