---
import { getCollection } from 'astro:content';
import DefaultLayout from '@/layouts/DefaultLayout.astro';
import { SITE_TITLE, SITE_DESCRIPTION } from '@/consts';
import { ACTIVE_BLOG_SITE } from '@/blog-sites.js';

const posts = (await getCollection(ACTIVE_BLOG_SITE.key)).sort(
  (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);

const formatDate = new Intl.DateTimeFormat('en', {
  month: 'short',
  day: 'numeric',
  year: 'numeric',
  timeZone: 'UTC',
});

const poems = posts.map((post) => ({
  title: post.data.title,
  description: post.data.description,
  href: `/${post.id.replace(/\/index$/, '')}/`,
  dateLabel: formatDate.format(post.data.pubDate),
  searchText: `${post.data.title} ${post.data.description}`.toLowerCase(),
}));
---

<DefaultLayout title={SITE_TITLE} description={SITE_DESCRIPTION}>
  <section class="poetry-home">
    <div class="poetry-home-panel">
      <header class="poetry-home-header">
        <h1>{ACTIVE_BLOG_SITE.title}</h1>

        <form class="poetry-search" data-poem-search-form role="search">
          <label class="sr-only" for="poem-search">Search</label>
          <input
            id="poem-search"
            data-poem-search-input
            type="search"
            autocomplete="off"
            placeholder="Search"
          />
          <button type="submit" aria-label="Search">
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <circle cx="11" cy="11" r="6.5"></circle>
              <path d="m16 16 4 4"></path>
            </svg>
          </button>
        </form>
      </header>

      <div class="poetry-home-grid">
        <section class="poetry-archive" aria-label="Poem archive">
          <ol data-poem-list>
            {poems.map((poem) => (
              <li data-poem-row data-search={poem.searchText}>
                <a href={poem.href}>{poem.title}</a>
                <time>{poem.dateLabel}</time>
              </li>
            ))}
          </ol>
          <p class="poetry-empty" data-poem-empty hidden>No poems found.</p>
        </section>
      </div>
    </div>
  </section>

  <script is:inline>
    const form = document.querySelector("[data-poem-search-form]");
    const input = document.querySelector("[data-poem-search-input]");
    const rows = [...document.querySelectorAll("[data-poem-row]")];
    const empty = document.querySelector("[data-poem-empty]");

    function filterPoems() {
      const query = input.value.trim().toLowerCase();
      let visibleCount = 0;

      for (const row of rows) {
        const isVisible = !query || row.dataset.search.includes(query);
        row.hidden = !isVisible;
        if (isVisible) visibleCount += 1;
      }

      empty.hidden = visibleCount !== 0;
    }

    form.addEventListener("submit", (event) => {
      event.preventDefault();
      input.focus();
      filterPoems();
    });

    input.addEventListener("input", filterPoems);
  </script>
</DefaultLayout>
