---
import ArticleCard from '~/components/blog/article-card.astro';
import { createNewsletterUser, getArticles } from '~/directus';
import DefaultLayout from '~/layouts/default-layout.astro';

import NewsletterCard from './_parts/newsletter-card.astro';

const errors = [];
let redirectTo = '';

if (Astro.request.method === 'POST') {
  try {
    const data = await Astro.request.formData();
    const email = data.get('email');

    if (!email || typeof email !== 'string') {
      errors.push('Email is required.');
    }

    if (!errors.length) {
      await createNewsletterUser(email!.toString())!;
      redirectTo = '/newsletter/thank-you';
    }
  }
  catch (error) {
    console.error(error);
    errors.push('Something went wrong. Please try again later.');
  }
}

if (redirectTo) {
  return Astro.redirect(redirectTo);
}

const articles = await getArticles({
  limit: 14,
});


---
<DefaultLayout
  title="DashHub.ai"
  description="Welcome to Dashhub!"
>
  <section class="container mx-auto px-4 py-8">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-12">
      <div class="lg:col-span-2">
        <h2 class="text-2xl font-bold mb-4">Articles</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-6 lg:gap-12">
          {articles.map(article => (
            <ArticleCard article={article} />
          ))}
        </div>
      </div>

      <aside class="lg:col-span-1">
        <h2 class="text-2xl font-bold mb-4">Featured Articles</h2>
        <ul class="flex flex-col gap-y-4 border-t border-gray-300 pt-4">
          {articles.slice(0, 5).map(article => (
            <li class="border-b border-gray-300">
              <a href={`/blog/${article.slug}`} class="hover:underline block py-2 pb-4">
                {article.title}
              </a>
            </li>
          ))}
        </ul>

        <NewsletterCard errors={errors} />
      </aside>
    </div>
  </section>
</DefaultLayout>
