---
import BaseLayout from '../../layouts/BaseLayout.astro';
import PageViewTracker from '../../components/seo/PageViewTracker.astro';
import SharePanel from '../../components/seo/SharePanel.astro';
import TerminalWindow from '../../components/ui/TerminalWindow.astro';
import CommandPrompt from '../../components/ui/CommandPrompt.astro';
import ResponsiveImage from '../../components/ui/ResponsiveImage.astro';
import { apiClient, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { parseReview } from '../../lib/reviews';

export const prerender = false;

const { locale, t } = getI18n(Astro);
const copy =
  locale === 'en'
    ? {
        summary: 'Review note',
        metadata: 'Metadata',
        notes: 'Notes',
        tags: 'Tags',
        back: 'Back to reviews',
        openLink: 'Open related link',
        notFoundTitle: 'Review not found',
        notFoundDescription:
          'The requested review does not exist or is temporarily unavailable.',
        rating: 'Rating',
        type: 'Type',
        status: 'Status',
        reviewDate: 'Review date',
        updatedAt: 'Updated at',
      }
    : {
        summary: '评价摘要',
        metadata: '元信息',
        notes: '记录内容',
        tags: '标签',
        back: '返回评价列表',
        openLink: '打开相关链接',
        notFoundTitle: '评价不存在',
        notFoundDescription: '当前请求的评价不存在，或者暂时无法从后端读取。',
        rating: '评分',
        type: '类型',
        status: '状态',
        reviewDate: '记录日期',
        updatedAt: '更新时间',
      };

let siteSettings = DEFAULT_SITE_SETTINGS;
let reviewLookupFailed = false;
try {
  siteSettings = await apiClient.getSiteSettings();
} catch (error) {
  console.error('Failed to load site settings for review detail:', error);
}

const reviewId = Number(Astro.params.id);
let review = null;

if (Number.isFinite(reviewId)) {
  try {
    review = parseReview(await apiClient.getReview(reviewId));
  } catch (error) {
    reviewLookupFailed = true;
    console.error(`Failed to load review ${reviewId}:`, error);
  }
}

if (!review) {
  Astro.response.status = reviewLookupFailed ? 503 : 404;
  if (reviewLookupFailed) {
    Astro.response.headers.set('Retry-After', '120');
  }
}

const typeLabels: Record<string, string> = {
  game: t('reviews.typeGame'),
  anime: t('reviews.typeAnime'),
  music: t('reviews.typeMusic'),
  book: t('reviews.typeBook'),
  movie: t('reviews.typeMovie'),
};

const statusLabels = {
  completed: t('reviews.statusCompleted'),
  'in-progress': t('reviews.statusInProgress'),
  dropped: t('reviews.statusDropped'),
};
const buildReviewFilterUrl = (params: { type?: string; status?: string; tag?: string }) => {
  const search = new URLSearchParams();
  if (params.type) search.set('type', params.type);
  if (params.status) search.set('status', params.status);
  if (params.tag) search.set('tag', params.tag);
  const query = search.toString();
  return query ? `/reviews?${query}` : '/reviews';
};

const pageTitle = review
  ? `${review.title} | ${t('reviews.title')} | ${siteSettings.siteShortName}`
  : `${copy.notFoundTitle} | ${siteSettings.siteShortName}`;
const pageDescription = review?.description || copy.notFoundDescription;
const canonical = review ? `/reviews/${review.id}` : '/reviews';
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const absoluteCanonicalUrl = new URL(canonical, siteBaseUrl).toString();
const sharePanelCopy =
  locale === 'en'
    ? {
        badge: 'review snapshot',
        title: 'Share this review snapshot',
        description:
          'Push the structured rating, status, and canonical review URL into social and AI discovery flows from one compact summary block.',
      }
    : {
        badge: '评测详情',
        title: '分享这份评测',
        description: '把这份评测发出去，方便别人直接看到评分、状态和相关链接。',
      };
const jsonLd = review
  ? [
      {
        '@context': 'https://schema.org',
        '@type': 'Review',
        name: review.title,
        reviewBody: review.description,
        datePublished: review.review_date,
        dateModified: review.updated_at,
        reviewRating: {
          '@type': 'Rating',
          ratingValue: review.rating,
          bestRating: 5,
          worstRating: 1,
        },
        itemReviewed: {
          '@type': 'CreativeWork',
          name: review.title,
          genre: typeLabels[review.review_type] || review.review_type,
          keywords: review.tags,
        },
        keywords: review.tags,
        url: absoluteCanonicalUrl,
      },
      {
        '@context': 'https://schema.org',
        '@type': 'BreadcrumbList',
        itemListElement: [
          {
            '@type': 'ListItem',
            position: 1,
            name: siteSettings.siteName,
            item: siteBaseUrl,
          },
          {
            '@type': 'ListItem',
            position: 2,
            name: t('reviews.title'),
            item: new URL('/reviews', siteBaseUrl).toString(),
          },
          {
            '@type': 'ListItem',
            position: 3,
            name: review.title,
            item: absoluteCanonicalUrl,
          },
        ],
      },
    ]
  : undefined;
---

<BaseLayout
  title={pageTitle}
  description={pageDescription}
  siteSettings={siteSettings}
  canonical={canonical}
  ogImage={review?.coverUrl || undefined}
  ogType={review ? 'article' : 'website'}
  jsonLd={jsonLd}
>
  {review && <PageViewTracker pageType="review" entityId={String(review.id)} />}
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title={review ? `~/reviews/${review.id}` : '~/reviews/not-found'} class="w-full">
      <div class="space-y-6 px-4 py-4">
        <div class="space-y-4">
          <CommandPrompt
            command={review ? `sed -n '1,160p' ./reviews/${review.id}.md` : 'ls ./reviews'}
            path="~/reviews"
          />

          <div class="terminal-panel ml-4">
            <div class="terminal-kicker">{copy.summary}</div>
            <div class="terminal-section-title mt-4">
              <span class="terminal-section-icon">
                <i class={`fas ${review ? 'fa-star' : 'fa-triangle-exclamation'}`}></i>
              </span>
              <div>
                <h1 class="text-2xl font-bold text-[var(--title-color)]">
                  {review ? review.title : copy.notFoundTitle}
                </h1>
                <p class="mt-2 text-sm leading-6 text-[var(--text-secondary)]">
                  {review ? review.description : copy.notFoundDescription}
                </p>
              </div>
            </div>
          </div>

          {review && (
            <div class="ml-4">
              <SharePanel
                shareTitle={pageTitle}
                summary={pageDescription}
                canonicalUrl={absoluteCanonicalUrl}
                badge={sharePanelCopy.badge}
                kicker="geo / review"
                title={sharePanelCopy.title}
                description={sharePanelCopy.description}
                stats={[
                  { label: copy.rating, value: `${review.rating.toFixed(1)}/5` },
                  { label: copy.type, value: typeLabels[review.review_type] || review.review_type },
                  { label: copy.status, value: statusLabels[review.normalizedStatus] || review.normalizedStatus },
                  { label: copy.reviewDate, value: review.review_date },
                ]}
                wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
              />
            </div>
          )}
        </div>

        {review ? (
          <>
            <div>
              <CommandPrompt command="jq '.meta' review.json" path="~/reviews" />
              <div class="review-detail-shell ml-4 mt-2">
                <div class="review-detail-cover terminal-panel">
                  {review.coverUrl ? (
                    <ResponsiveImage
                      src={review.coverUrl}
                      alt={`${review.title} cover`}
                      pictureClass="block h-full w-full"
                      imgClass="review-detail-cover__image"
                      widths={[640, 960, 1280, 1600]}
                      sizes="(min-width: 1280px) 42rem, 100vw"
                    />
                  ) : (
                    <div class="review-detail-cover__fallback">
                      <div class="review-detail-cover__year">{review.review_date.slice(0, 4)}</div>
                      <div class="review-detail-cover__emoji">{review.cover || '★'}</div>
                      <div class="review-detail-cover__title">{review.title}</div>
                    </div>
                  )}
                </div>

                <div class="space-y-4">
                  <div class="terminal-panel review-detail-card">
                    <div class="review-detail-card__header">
                      <span class="terminal-kicker">{copy.metadata}</span>
                      <div class="review-detail-card__rating">
                        <strong>{review.rating.toFixed(1)}</strong>
                        <span>/ 5</span>
                      </div>
                    </div>
                    <div class="review-detail-meta-grid">
                      <div>
                        <div class="review-detail-meta-grid__label">{copy.type}</div>
                        <div>
                          <a
                            href={buildReviewFilterUrl({ type: review.review_type })}
                            class="review-detail-filter-link"
                          >
                            {typeLabels[review.review_type] || review.review_type}
                          </a>
                        </div>
                      </div>
                      <div>
                        <div class="review-detail-meta-grid__label">{copy.status}</div>
                        <div>
                          <a
                            href={buildReviewFilterUrl({ status: review.normalizedStatus })}
                            class="review-detail-filter-link"
                          >
                            {statusLabels[review.normalizedStatus]}
                          </a>
                        </div>
                      </div>
                      <div>
                        <div class="review-detail-meta-grid__label">{copy.reviewDate}</div>
                        <div>{review.review_date}</div>
                      </div>
                      <div>
                        <div class="review-detail-meta-grid__label">{copy.updatedAt}</div>
                        <div>{review.updated_at}</div>
                      </div>
                    </div>
                  </div>

                  <div class="terminal-panel review-detail-card">
                    <div class="terminal-kicker">{copy.tags}</div>
                    <div class="review-detail-tags mt-4">
                      {review.tags.length ? (
                        review.tags.map((tag) => (
                          <a
                            href={`/reviews?tag=${encodeURIComponent(tag)}`}
                            class="terminal-chip text-xs py-1 px-2.5 transition hover:-translate-y-0.5 hover:border-[var(--primary)]"
                          >
                            #{tag}
                          </a>
                        ))
                      ) : (
                        <span class="text-sm text-[var(--text-secondary)]">{t('common.noData')}</span>
                      )}
                    </div>
                  </div>

                  <div class="review-detail-actions">
                    {review.linkUrl && (
                      <a
                        href={review.linkUrl}
                        class="terminal-action-button"
                        target={review.externalLink ? '_blank' : undefined}
                        rel={review.externalLink ? 'noreferrer noopener' : undefined}
                      >
                        <i class={`fas ${review.externalLink ? 'fa-arrow-up-right-from-square' : 'fa-arrow-right'}`}></i>
                        <span>{copy.openLink}</span>
                      </a>
                    )}
                    <a href="/reviews" class="terminal-subtle-link">
                      <i class="fas fa-chevron-left"></i>
                      <span class="font-mono">{copy.back}</span>
                    </a>
                  </div>
                </div>
              </div>
            </div>

            <div>
              <CommandPrompt command="cat review.md" path="~/reviews" />
              <div class="terminal-panel ml-4 mt-2 review-detail-card">
                <div class="terminal-kicker">{copy.notes}</div>
                <div class="review-detail-body mt-4">
                  {review.description}
                </div>
              </div>
            </div>
          </>
        ) : (
          <div class="ml-4 rounded-2xl border border-dashed border-[var(--border-color)] bg-[var(--bg)]/60 px-5 py-8">
            <p class="text-sm leading-7 text-[var(--text-secondary)]">
              {copy.notFoundDescription}
            </p>
            <a href="/reviews" class="terminal-subtle-link mt-4 inline-flex">
              <i class="fas fa-chevron-left"></i>
              <span class="font-mono">{copy.back}</span>
            </a>
          </div>
        )}
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>

<style>
  .review-detail-shell {
    display: grid;
    gap: 1rem;
    grid-template-columns: minmax(0, 1.25fr) minmax(280px, 0.75fr);
  }

  .review-detail-cover {
    overflow: hidden;
    min-height: 22rem;
    padding: 0;
  }

  .review-detail-cover__image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }

  .review-detail-cover__fallback {
    min-height: 22rem;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 1.5rem;
    background:
      linear-gradient(160deg, color-mix(in oklab, var(--primary) 18%, var(--terminal-bg)), color-mix(in oklab, var(--secondary) 12%, var(--header-bg)) 48%, color-mix(in oklab, var(--terminal-bg) 96%, transparent)),
      radial-gradient(circle at top right, color-mix(in oklab, var(--primary) 24%, transparent), transparent 44%);
  }

  .review-detail-cover__year {
    font-size: 0.72rem;
    letter-spacing: 0.18em;
    text-transform: uppercase;
    color: var(--text-tertiary);
  }

  .review-detail-cover__emoji {
    font-size: 4.75rem;
    line-height: 1;
    align-self: center;
  }

  .review-detail-cover__title {
    font-size: 1.3rem;
    font-weight: 800;
    line-height: 1.35;
    color: var(--title-color);
  }

  .review-detail-card {
    padding: 1rem;
  }

  .review-detail-card__header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
  }

  .review-detail-card__rating {
    display: flex;
    align-items: baseline;
    gap: 0.35rem;
    color: var(--primary);
  }

  .review-detail-card__rating strong {
    font-size: 2rem;
    line-height: 1;
  }

  .review-detail-meta-grid {
    margin-top: 1rem;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.9rem;
    font-size: 0.95rem;
    color: var(--text-secondary);
  }

  .review-detail-meta-grid__label {
    margin-bottom: 0.3rem;
    font-size: 0.72rem;
    letter-spacing: 0.14em;
    text-transform: uppercase;
    color: var(--text-tertiary);
  }

  .review-detail-filter-link {
    display: inline-flex;
    align-items: center;
    color: var(--text-primary);
    text-decoration: none;
    border-bottom: 1px dashed transparent;
    transition: color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
  }

  .review-detail-filter-link:hover {
    color: var(--primary);
    border-bottom-color: color-mix(in oklab, var(--primary) 55%, transparent);
    transform: translateY(-1px);
  }

  .review-detail-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  .review-detail-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.85rem;
    align-items: center;
  }

  .review-detail-body {
    white-space: pre-wrap;
    font-size: 0.98rem;
    line-height: 1.95;
    color: var(--text-secondary);
  }

  @media (max-width: 1024px) {
    .review-detail-shell {
      grid-template-columns: minmax(0, 1fr);
    }
  }

  @media (max-width: 640px) {
    .review-detail-meta-grid {
      grid-template-columns: minmax(0, 1fr);
    }
  }
</style>
