import { getLocale, getTranslations } from 'next-intl/server';
import { SiteHeader } from '@/components/SiteHeader';
import { MasonryGrid } from '@/components/MasonryGrid';
import { HomeLoginTrigger } from '@/components/HomeLoginTrigger';
import { getPublishedPosts, getAllTags } from '@/lib/blog';
import { getCurrentUser } from '@/lib/auth';
import { recordPageView, getVisitorHash } from '@/lib/visitor-tracker';
import type { Locale } from '@/i18n/config';

interface HomePageProps {
  searchParams: Promise<{ login?: string; tag?: string; q?: string }>;
}

export default async function HomePage({ searchParams }: HomePageProps) {
  const locale = await getLocale() as Locale;
  const t = await getTranslations();
  const user = await getCurrentUser();
  const sp = await searchParams;

  // 记录首页 PV/UV
  const visitorHash = await getVisitorHash();
  recordPageView({ pageType: 'home', visitorHash });

  const tag = sp.tag || 'all';
  const q = sp.q || '';
  const { posts, total } = getPublishedPosts({ page: 1, limit: 12, tag, q });
  const tags = getAllTags();

  return (
    <>
      <SiteHeader />
      <main className="container">
        <div className="hero">
          <h1>{t('metadata.title')}</h1>
          <p>{t('metadata.description')}</p>
        </div>
        <MasonryGrid
          initialPosts={posts}
          initialTotal={total}
          locale={locale}
          initialTag={tag}
          initialQ={q}
          tags={tags}
        />
      </main>
      <footer className="site-footer">
        <p>{t('footer.copyright')}</p>
        <p style={{ marginTop: '0.3rem' }}>{t('footer.poweredBy')}</p>
      </footer>
      {!user && <HomeLoginTrigger />}
    </>
  );
}
