import { notFound } from 'next/navigation';
import { getLocale, getTranslations } from 'next-intl/server';
import { SiteHeader } from '@/components/SiteHeader';
import { MarkdownRenderer } from '@/components/MarkdownRenderer';
import { BreakpointGate } from '@/components/BreakpointGate';
import { VoteButtons } from '@/components/VoteButtons';
import { getPostBySlug, pickTitle, pickContent, getUserVotes } from '@/lib/blog';
import { splitByBreakpoint } from '@/lib/markdown/remark-breakpoint';
import { getCurrentUser } from '@/lib/auth';
import { recordPageView, getVisitorHash } from '@/lib/visitor-tracker';
import type { Locale } from '@/i18n/config';

interface PageProps {
  params: Promise<{ slug: string }>;
}

export default async function BlogDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const locale = await getLocale() as Locale;
  const t = await getTranslations();
  const user = await getCurrentUser();

  const post = getPostBySlug(slug);
  if (!post || post.status !== 'published') notFound();

  // 记录详情页 PV/UV
  const visitorHash = await getVisitorHash();
  recordPageView({ pageType: 'detail', blogId: post.id, visitorHash });

  const title = pickTitle(post, locale);
  const content = pickContent(post, locale);
  const showNoEnglishNotice = locale === 'en' && !post.contentMdEn;

  const [beforeBreak, afterBreak] = splitByBreakpoint(content);
  const hasBreak = post.hasBreakpoint && afterBreak.length > 0;
  const userVote = user ? getUserVotes(user.id, post.id) : { liked: false, disliked: false };

  return (
    <>
      <SiteHeader />
      <article className="detail-wrap">
        <img
          src={post.coverImage}
          alt={title}
          className="detail-cover"
          width={post.coverWidth || 800}
          height={post.coverHeight || 600}
        />
        <h1 className="detail-title">{title}</h1>
        <div className="detail-meta">
          <span>{t('blog.publishDate')}: {post.publishDate}</span>
          {post.tags && (
            <div className="detail-tags">
              {post.tags.split(',').map(tg => (
                <span key={tg} className="masonry-tag">{tg.trim()}</span>
              ))}
            </div>
          )}
        </div>

        {showNoEnglishNotice && (
          <div className="notice-bar">{t('blog.noEnglish')}</div>
        )}

        {/* 断点前内容 */}
        {beforeBreak && <MarkdownRenderer content={beforeBreak} />}

        {/* 断点机制：访客需登录后查看后续内容 */}
        {hasBreak ? (
          <BreakpointGate
            isLoggedIn={!!user}
            blogId={post.id}
            hiddenContent={<MarkdownRenderer content={afterBreak} />}
          />
        ) : (
          // 无断点 — 直接渲染后续内容
          afterBreak && <MarkdownRenderer content={afterBreak} />
        )}

        {/* 投票 */}
        <VoteButtons
          isLoggedIn={!!user}
          slug={post.slug}
          initialLikeCount={post.likeCount ?? 0}
          initialDislikeCount={post.dislikeCount ?? 0}
          initialLiked={userVote.liked}
          initialDisliked={userVote.disliked}
        />

        <div style={{ marginTop: '2rem', textAlign: 'center' }}>
          <a href="/" className="header-btn">← {t('blog.backHome')}</a>
        </div>
      </article>
    </>
  );
}
