---
import { getCollection } from 'astro:content';
import transport from '../data/transport.json';
import partners from '../data/partners.json';
import ads from '../data/ads.json';
import { plural } from '../consts';

const allPosts = await getCollection('posts');

// Категории с подсчётом — но без "main" (это псевдо-флаг «попадает на главную»).
const catCount = new Map<string, { slug: string; name: string; count: number }>();
for (const p of allPosts) {
  p.data.categorySlugs.forEach((slug, i) => {
    if (slug === 'main') return;
    const name = p.data.categories[i] ?? slug;
    if (!catCount.has(slug)) catCount.set(slug, { slug, name, count: 0 });
    catCount.get(slug)!.count++;
  });
}
const categories = [...catCount.values()].sort((a, b) => b.count - a.count);
---

<aside class="sidebar">
  <section class="box">
    <h3>Транспорт</h3>
    <ul>
      {transport.trains.map((t: { label: string; url: string }) => (
        <li><a href={t.url} target="_blank" rel="noopener noreferrer">{t.label}</a></li>
      ))}
      {transport.buses.map((b: { label: string; url: string }) => (
        <li><a href={b.url} target="_blank" rel="noopener noreferrer">{b.label}</a></li>
      ))}
    </ul>
  </section>

  {categories.length > 0 && (
    <section class="box">
      <h3>Рубрики</h3>
      <ul>
        {categories.map((c) => (
          <li>
            <a href={`/cat/${c.slug}/`}>
              <span>{c.name}</span>
              <span class="cat-count">{c.count}&nbsp;{plural(c.count, ['запись', 'записи', 'записей'])}</span>
            </a>
          </li>
        ))}
      </ul>
    </section>
  )}

  {partners.length > 0 && (
    <section class="box">
      <h3>Наши партнёры</h3>
      <ul>
        {partners.map((p: { name: string; url: string; note: string }) => (
          <li>
            {p.url ? <a href={p.url} target="_blank" rel="noopener noreferrer">{p.name}</a> : <span>{p.name}</span>}
            {p.note && <span class="note"> — {p.note}</span>}
          </li>
        ))}
      </ul>
    </section>
  )}

  {ads.length > 0 && (
    <section class="box">
      <h3>Объявления</h3>
      <ul>
        {ads.map((a: { text: string; url?: string }) => (
          <li>
            {a.url ? <a href={a.url} target="_blank" rel="noopener noreferrer">{a.text}</a> : <span>{a.text}</span>}
          </li>
        ))}
      </ul>
    </section>
  )}
</aside>

<style>
  .sidebar a {
    display: flex;
    justify-content: space-between;
    gap: 0.5rem;
    align-items: baseline;
    color: var(--ink-soft);
    text-decoration: none;
  }
  .sidebar a:hover { color: var(--accent); }
  .cat-count { color: var(--muted); font-size: 0.78rem; white-space: nowrap; }
  .note { color: var(--muted); font-size: 0.85rem; }
</style>
