---
import Layout from '../../layouts/BaseLayout.astro';
import DiscoveryBrief from '../../components/seo/DiscoveryBrief.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 FilterPill from '../../components/ui/FilterPill.astro';
import ResponsiveImage from '../../components/ui/ResponsiveImage.astro';
import { apiClient, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { buildDiscoveryHighlights, buildFaqJsonLd, buildPageFaqs, compactJsonLd } from '../../lib/seo';
import { parseReview, type ParsedReview, type ReviewStatus } from '../../lib/reviews';

export const prerender = false;

let reviews: Awaited<ReturnType<typeof apiClient.getReviews>> = [];
let siteSettings = DEFAULT_SITE_SETTINGS;
const url = new URL(Astro.request.url);
const selectedType = url.searchParams.get('type') || 'all';
const selectedStatus = url.searchParams.get('status') || 'all';
const selectedTag = url.searchParams.get('tag') || '';
const selectedQuery = url.searchParams.get('q')?.trim() || '';
const { locale, t } = getI18n(Astro);
const isEnglish = locale.startsWith('en');

try {
  const [reviewsResult, settingsResult] = await Promise.allSettled([
    apiClient.getReviews(),
    apiClient.getSiteSettings(),
  ]);

  if (reviewsResult.status === 'fulfilled') {
    reviews = reviewsResult.value;
  } else {
    console.error('Failed to fetch reviews:', reviewsResult.reason);
  }

  if (settingsResult.status === 'fulfilled') {
    siteSettings = settingsResult.value;
  } else {
    console.error('Failed to fetch site settings for reviews:', settingsResult.reason);
  }
} catch (error) {
  console.error('Failed to fetch reviews:', error);
}

const parsedReviews: ParsedReview[] = reviews.map(parseReview);
const normalizedSelectedTag = selectedTag.trim().toLowerCase();
const normalizedSelectedQuery = selectedQuery.toLowerCase();

const filteredReviews = parsedReviews.filter((review) => {
  if (selectedType !== 'all' && review.review_type !== selectedType) return false;
  if (selectedStatus !== 'all' && review.normalizedStatus !== selectedStatus) return false;
  if (
    normalizedSelectedTag &&
    !review.tags.some((tag) => tag.trim().toLowerCase() === normalizedSelectedTag)
  ) {
    return false;
  }
  if (normalizedSelectedQuery) {
    const haystack = [
      review.title,
      review.description,
      review.review_type,
      review.status,
      review.tags.join(' '),
    ]
      .join(' ')
      .toLowerCase();
    if (!haystack.includes(normalizedSelectedQuery)) return false;
  }
  return true;
});

const stats = {
  total: filteredReviews.length,
  avgRating: filteredReviews.length > 0
    ? (filteredReviews.reduce((sum, r) => sum + (r.rating || 0), 0) / filteredReviews.length).toFixed(1)
    : '0',
  completed: filteredReviews.filter(r => r.normalizedStatus === 'completed').length,
  inProgress: filteredReviews.filter(r => r.normalizedStatus === 'in-progress').length
};
const highRatingCount = filteredReviews.filter(r => (r.rating || 0) >= 4).length;
const completedRatio = filteredReviews.length > 0 ? Math.round((stats.completed / filteredReviews.length) * 100) : 0;
const inProgressRatio = filteredReviews.length > 0 ? Math.round((stats.inProgress / filteredReviews.length) * 100) : 0;

const filters = [
  { id: 'all', name: t('reviews.typeAll'), icon: 'fa-list', count: parsedReviews.length },
  { id: 'game', name: t('reviews.typeGame'), icon: 'fa-gamepad', count: parsedReviews.filter(r => r.review_type === 'game').length },
  { id: 'anime', name: t('reviews.typeAnime'), icon: 'fa-tv', count: parsedReviews.filter(r => r.review_type === 'anime').length },
  { id: 'music', name: t('reviews.typeMusic'), icon: 'fa-music', count: parsedReviews.filter(r => r.review_type === 'music').length },
  { id: 'book', name: t('reviews.typeBook'), icon: 'fa-book', count: parsedReviews.filter(r => r.review_type === 'book').length },
  { id: 'movie', name: t('reviews.typeMovie'), icon: 'fa-film', count: parsedReviews.filter(r => r.review_type === 'movie').length }
];

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 typeColors: Record<string, string> = {
  game: '#4285f4',
  anime: '#ff6b6b',
  music: '#00ff9d',
  book: '#f59e0b',
  movie: '#9b59b6'
};

const statusLabels: Record<ReviewStatus, string> = {
  completed: t('reviews.statusCompleted'),
  'in-progress': t('reviews.statusInProgress'),
  dropped: t('reviews.statusDropped'),
};

const statusColors: Record<ReviewStatus, string> = {
  completed: 'var(--success)',
  'in-progress': 'var(--warning)',
  dropped: 'var(--text-tertiary)',
};

const statusOptions = [
  { id: 'all', label: '全部状态' },
  { id: 'completed', label: t('reviews.statusCompleted') },
  { id: 'in-progress', label: t('reviews.statusInProgress') },
  { id: 'dropped', label: t('reviews.statusDropped') },
];

const tagOptions = Array.from(
  parsedReviews.reduce((set, review) => {
    review.tags.forEach((tag) => set.add(tag));
    return set;
  }, new Set<string>()),
).sort((left, right) => left.localeCompare(right));

const statCards = [
  {
    id: 'total',
    label: t('reviews.total'),
    icon: 'fa-layer-group',
    color: 'var(--primary)',
    value: stats.total,
    detail: `>=4 ★ · ${highRatingCount}`,
    barWidth: `${stats.total ? Math.max((highRatingCount / stats.total) * 100, 12) : 12}%`,
  },
  {
    id: 'average',
    label: t('reviews.average'),
    icon: 'fa-star',
    color: '#e0a100',
    value: stats.avgRating,
    detail: '/ 5',
    barWidth: `${Math.max((Number(stats.avgRating) / 5) * 100, 8)}%`,
  },
  {
    id: 'completed',
    label: t('reviews.completed'),
    icon: 'fa-circle-check',
    color: 'var(--success)',
    value: stats.completed,
    detail: `${completedRatio}%`,
    barWidth: `${completedRatio}%`,
  },
  {
    id: 'progress',
    label: t('reviews.inProgress'),
    icon: 'fa-hourglass-half',
    color: 'var(--warning)',
    value: stats.inProgress,
    detail: `${inProgressRatio}%`,
    barWidth: `${inProgressRatio}%`,
  }
];
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const absoluteCanonicalUrl = new URL('/reviews', siteBaseUrl).toString();
const reviewsJsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: t('reviews.title'),
    description: t('reviews.subtitle'),
    url: absoluteCanonicalUrl,
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${t('reviews.title')} list`,
    itemListElement: filteredReviews.map((review, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      url: new URL(`/reviews/${review.id}`, siteBaseUrl).toString(),
      name: review.title,
      description: review.description,
    })),
  },
  {
    '@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: absoluteCanonicalUrl,
      },
    ],
  },
];

const buildReviewsUrl = ({
  type = selectedType,
  status = selectedStatus,
  tag = selectedTag,
  q = selectedQuery,
}: {
  type?: string;
  status?: string;
  tag?: string;
  q?: string;
}) => {
  const params = new URLSearchParams();
  if (type && type !== 'all') params.set('type', type);
  if (status && status !== 'all') params.set('status', status);
  if (tag) params.set('tag', tag);
  if (q) params.set('q', q);
  const query = params.toString();
  return query ? `/reviews?${query}` : '/reviews';
};

const activeFilters = [
  selectedType !== 'all' ? typeLabels[selectedType] || selectedType : '',
  selectedStatus !== 'all'
    ? statusOptions.find((item) => item.id === selectedStatus)?.label || selectedStatus
    : '',
  selectedTag ? `#${selectedTag}` : '',
  selectedQuery ? `q=${selectedQuery}` : '',
].filter(Boolean);
const hasActiveFilters = activeFilters.length > 0;
const sharePanelCopy = isEnglish
  ? {
      badge: 'review archive',
      title: 'Share the review archive',
      description:
        'Use the reviews index as the canonical entry for ratings, statuses, and tagged review snapshots so AI search and readers can drill down from one source.',
    }
    : {
      badge: '评测列表',
      title: '分享评测列表',
      description: '把评测列表分享出去，方便快速查看评分、状态和分类。',
    };
const reviewHighlights = buildDiscoveryHighlights([
  t('reviews.subtitle'),
  `${t('reviews.total')}: ${stats.total}`,
  `${t('reviews.average')}: ${stats.avgRating}`,
  `${t('reviews.completed')}: ${stats.completed}`,
  `${t('reviews.inProgress')}: ${stats.inProgress}`,
]);
const reviewFaqs = buildPageFaqs({
  locale,
  pageTitle: t('reviews.pageTitle'),
  summary: t('reviews.pageDescription'),
  primaryLabel: t('reviews.title'),
  primaryUrl: absoluteCanonicalUrl,
  relatedLinks: [
    { label: t('nav.timeline'), url: `${siteBaseUrl}/timeline` },
    { label: t('nav.tags'), url: `${siteBaseUrl}/tags` },
    { label: t('nav.about'), url: `${siteBaseUrl}/about` },
  ],
  signals: reviewHighlights,
});
const reviewFaqJsonLd = buildFaqJsonLd(reviewFaqs);
---

<Layout
  title={`${t('reviews.pageTitle')} | Termi`}
  description={t('reviews.pageDescription')}
  siteSettings={siteSettings}
  canonical={hasActiveFilters ? '/reviews' : undefined}
  noindex={hasActiveFilters}
  jsonLd={compactJsonLd([...reviewsJsonLd, reviewFaqJsonLd])}
>
  <PageViewTracker pageType="reviews" entityId="reviews-index" />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/reviews" class="w-full">
      <div class="px-4 py-4 space-y-6">
        <div>
          <CommandPrompt command="less README.md" path="~/reviews" />
          <div class="terminal-panel ml-4 mt-4">
            <div class="terminal-kicker">review ledger</div>
            <div class="terminal-section-title mt-4">
              <span class="terminal-section-icon">
                <i class="fas fa-star"></i>
              </span>
              <div>
                <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('reviews.title')}</h1>
                <p id="reviews-subtitle" class="mt-2 text-sm leading-6 text-[var(--text-secondary)]">
                  {t('reviews.subtitle')}
                  {activeFilters.length > 0 && ` · ${activeFilters.join(' · ')}`}
                </p>
              </div>
            </div>
          </div>

          <div class="ml-4 mt-4">
            <SharePanel
              shareTitle={`${t('reviews.pageTitle')} | ${siteSettings.siteShortName || siteSettings.siteName}`}
              summary={t('reviews.subtitle')}
              canonicalUrl={absoluteCanonicalUrl}
              badge={sharePanelCopy.badge}
              kicker="geo / reviews"
              title={sharePanelCopy.title}
              description={sharePanelCopy.description}
              stats={[
                { label: t('reviews.total'), value: String(stats.total) },
                { label: t('reviews.average'), value: stats.avgRating },
                { label: t('reviews.completed'), value: String(stats.completed) },
                { label: t('reviews.inProgress'), value: String(stats.inProgress) },
              ]}
              wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
            />
          </div>

          <div class="ml-4 mt-4">
            <DiscoveryBrief
              badge={isEnglish ? 'review brief' : '评测摘要'}
              kicker="geo / review"
              title={isEnglish ? 'AI-readable review brief' : '给 AI 看的评测摘要'}
              summary={t('reviews.pageDescription')}
              highlights={reviewHighlights}
              faqs={reviewFaqs}
            />
          </div>
        </div>

        <div>
          <CommandPrompt command="jq '.summary' stats.json" path="~/reviews" />
          <div class="reviews-stats-grid ml-4 mt-2">
            {statCards.map((card) => (
              <div class="reviews-stat-card" style={`--review-stat-color: ${card.color};`}>
                <div class="reviews-stat-card__head">
                  <span class="reviews-stat-card__icon">
                    <i class={`fas ${card.icon}`}></i>
                  </span>
                  <span class="terminal-kicker">{card.label}</span>
                </div>
                <div class="mt-3 flex items-end justify-between gap-4">
                  <div class="min-w-0">
                    <div class="reviews-stat-card__value">{card.value}</div>
                    <div class="reviews-stat-card__detail">
                      {card.id === 'average' ? '/ 5' : card.detail}
                    </div>
                  </div>
                  {card.id === 'average' && (
                    <div class="reviews-average-stars">
                      {Array.from({ length: 5 }).map((_, index) => (
                        <i class={`fas fa-star ${index < Math.round(Number(stats.avgRating)) ? '' : 'opacity-25'}`}></i>
                      ))}
                    </div>
                  )}
                </div>
                <div class="reviews-stat-card__bar">
                  <div class="reviews-stat-card__bar-fill" style={`width: ${card.barWidth};`}></div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div>
          <CommandPrompt command="printf '%s\n' all game anime music book movie" path="~/reviews" />
          <div class="ml-4 mt-4 flex flex-wrap gap-2">
            {filters.map(filter => (
              <FilterPill
                href={buildReviewsUrl({ type: filter.id })}
                tone={filter.id === 'all' ? 'neutral' : filter.id === 'game' ? 'blue' : filter.id === 'book' ? 'amber' : filter.id === 'music' ? 'teal' : 'violet'}
                active={selectedType === filter.id}
                class="review-filter"
              >
                <i class={`fas ${filter.icon}`}></i>
                {filter.name}
                <span class="review-filter__count">{filter.count}</span>
              </FilterPill>
            ))}
          </div>
        </div>

        <div>
          <CommandPrompt command="reviews filter --public-only" path="~/reviews" />
          <div class="terminal-panel ml-4 mt-4">
            <form method="GET" action="/reviews" class="reviews-filter-form">
              <label class="reviews-filter-field">
                <span>搜索</span>
                <input type="text" name="q" value={selectedQuery} placeholder="标题 / 简介 / 标签" />
              </label>

              <label class="reviews-filter-field">
                <span>状态</span>
                <select name="status">
                  {statusOptions.map((option) => (
                    <option value={option.id} selected={selectedStatus === option.id}>{option.label}</option>
                  ))}
                </select>
              </label>

              <label class="reviews-filter-field">
                <span>标签</span>
                <select name="tag">
                  <option value="" selected={!selectedTag}>全部标签</option>
                  {tagOptions.map((tag) => (
                    <option value={tag} selected={selectedTag === tag}>{tag}</option>
                  ))}
                </select>
              </label>

              {selectedType !== 'all' ? <input type="hidden" name="type" value={selectedType} /> : null}

              <div class="reviews-filter-actions">
                <button type="submit" class="terminal-action-button terminal-action-button-primary">
                  <i class="fas fa-filter"></i>
                  <span>应用筛选</span>
                </button>
                <a href="/reviews" class="terminal-action-button">
                  <i class="fas fa-rotate-left"></i>
                  <span>{t('common.clearFilters')}</span>
                </a>
              </div>
            </form>
          </div>
        </div>

        <div>
          <CommandPrompt command="find . -maxdepth 1 -name '*.md' | sort" path="~/reviews" />
          <div class="ml-4 mt-2">
            <div class="reviews-card-grid">
              {filteredReviews.map(review => (
                <article
                  class="review-card terminal-panel group"
                  style={`--review-accent: ${typeColors[review.review_type] || '#888'};`}
                >
                  <div class="review-card__poster">
                    <a href={`/reviews/${review.id}`} class="review-card__poster-link" aria-label={`查看 ${review.title} 详情`}>
                      {review.coverUrl ? (
                        <ResponsiveImage
                          src={review.coverUrl}
                          alt={`${review.title} cover`}
                          pictureClass="block h-full w-full"
                          imgClass="review-card__poster-image"
                          widths={[320, 480, 720, 960]}
                          sizes="(min-width: 1536px) 18vw, (min-width: 1024px) 28vw, (min-width: 640px) 45vw, 100vw"
                        />
                      ) : (
                        <div class="review-card__poster-fallback">
                          <div class="review-card__poster-kicker">
                            <span>{typeLabels[review.review_type] || review.review_type}</span>
                            <span>{review.review_date.slice(0, 4)}</span>
                          </div>
                          <div class="review-card__poster-emoji">{review.cover || '★'}</div>
                          <div class="review-card__poster-title">{review.title}</div>
                        </div>
                      )}
                    </a>
                  </div>

                  <div class="review-card__body">
                    <div class="review-card__head">
                      <div class="min-w-0">
                        <div class="review-card__badges">
                          <span class="terminal-chip terminal-chip--accent text-[10px] py-1 px-2" style={`--accent-color:${typeColors[review.review_type] || '#888'};--accent-rgb:${review.review_type === 'game' ? '66 133 244' : review.review_type === 'anime' ? '255 107 107' : review.review_type === 'music' ? '0 255 157' : review.review_type === 'book' ? '245 158 11' : '155 89 182'};`}>
                            {typeLabels[review.review_type] || review.review_type}
                          </span>
                          <span class="terminal-chip text-[10px] py-1 px-2" style={`color:${statusColors[review.normalizedStatus]};`}>
                            {statusLabels[review.normalizedStatus]}
                          </span>
                        </div>
                        <h2 class="review-card__title">
                          <a href={`/reviews/${review.id}`} class="review-card__title-link">
                            {review.title}
                          </a>
                        </h2>
                      </div>
                      <div class="review-card__rating">
                        <div class="review-card__rating-value">{review.rating || 0}.0</div>
                        <div class="review-card__rating-stars">
                          {Array.from({ length: 5 }).map((_, i) => (
                            <i class={`fas fa-star ${i < (review.rating || 0) ? 'text-yellow-500' : 'text-[var(--border-color)]'}`}></i>
                          ))}
                        </div>
                      </div>
                    </div>

                    <p class="review-card__description">{review.description}</p>

                    <div class="review-card__meta">
                      <a href={`/reviews/${review.id}`} class="review-card__link review-card__link--internal">
                        <i class="fas fa-file-lines"></i>
                        <span class="font-mono">cat review.md</span>
                      </a>
                      <span class="terminal-chip text-xs py-1 px-2.5">
                        <i class="fas fa-calendar text-[10px]"></i>
                        <span>{review.review_date}</span>
                      </span>
                      <span class="terminal-chip text-xs py-1 px-2.5">
                        <i class="fas fa-star text-[10px] text-yellow-500"></i>
                        <span>{review.rating || 0}/5</span>
                      </span>
                      {review.linkUrl && (
                        <a
                          href={review.linkUrl}
                          class="review-card__link"
                          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 class="font-mono">xdg-open</span>
                        </a>
                      )}
                    </div>

                    <div class="review-card__tags">
                      {review.tags.map((tag: string) => (
                        <a class="terminal-chip text-xs py-1 px-2.5" href={buildReviewsUrl({ tag, status: selectedStatus, q: selectedQuery })}>
                          #{tag}
                        </a>
                      ))}
                    </div>
                  </div>
                </article>
              ))}
            </div>

            <div id="reviews-empty-state" class:list={['terminal-empty mt-4', filteredReviews.length > 0 && 'hidden']}>
              <div class="text-3xl text-[var(--primary)] mb-3">
                <i class="fas fa-inbox"></i>
              </div>
              <div class="text-[var(--text-secondary)]">
                {parsedReviews.length === 0 ? t('reviews.emptyData') : t('reviews.emptyFiltered')}
              </div>
            </div>
          </div>
        </div>

        <div class="pt-4 border-t border-[var(--border-color)]">
          <a href="/" class="terminal-subtle-link">
            <i class="fas fa-chevron-left"></i>
            <span class="font-mono">cd ~</span>
          </a>
        </div>
      </div>
    </TerminalWindow>
  </div>
</Layout>

<style>
  .reviews-stats-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 1rem;
  }

  .reviews-stat-card {
    border: 1px solid color-mix(in oklab, var(--review-stat-color) 18%, var(--border-color));
    background:
      linear-gradient(180deg, color-mix(in oklab, var(--terminal-bg) 98%, transparent), color-mix(in oklab, var(--review-stat-color) 5%, var(--header-bg))),
      radial-gradient(circle at top right, color-mix(in oklab, var(--review-stat-color) 14%, transparent), transparent 52%);
    border-radius: 1.1rem;
    padding: 1rem 1rem 0.95rem;
    box-shadow: 0 12px 28px rgba(var(--text-rgb), 0.05);
  }

  .reviews-stat-card__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
  }

  .reviews-stat-card__icon {
    display: inline-flex;
    height: 2.75rem;
    width: 2.75rem;
    align-items: center;
    justify-content: center;
    border-radius: 1rem;
    color: var(--review-stat-color);
    background: color-mix(in oklab, var(--review-stat-color) 12%, var(--terminal-bg));
    border: 1px solid color-mix(in oklab, var(--review-stat-color) 18%, var(--border-color));
  }

  .reviews-stat-card__value {
    font-size: clamp(2rem, 3vw, 2.4rem);
    line-height: 1;
    font-weight: 800;
    color: var(--review-stat-color);
  }

  .reviews-stat-card__detail {
    margin-top: 0.35rem;
    font-size: 0.8rem;
    color: var(--text-secondary);
  }

  .reviews-stat-card__bar {
    margin-top: 0.9rem;
    height: 0.35rem;
    border-radius: 999px;
    background: color-mix(in oklab, var(--review-stat-color) 12%, transparent);
    overflow: hidden;
  }

  .reviews-stat-card__bar-fill {
    height: 100%;
    border-radius: inherit;
    background: var(--review-stat-color);
  }

  .reviews-average-stars {
    display: flex;
    flex-wrap: wrap;
    gap: 0.25rem;
    color: #e0a100;
  }

  .reviews-filter-form {
    display: grid;
    gap: 0.9rem;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    align-items: end;
  }

  .reviews-filter-field {
    display: grid;
    gap: 0.45rem;
  }

  .reviews-filter-field span {
    font-size: 0.72rem;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--text-tertiary);
  }

  .reviews-filter-field input,
  .reviews-filter-field select {
    min-height: 2.85rem;
    width: 100%;
    border-radius: 0.95rem;
    border: 1px solid color-mix(in oklab, var(--primary) 12%, var(--border-color));
    background: color-mix(in oklab, var(--terminal-bg) 96%, transparent);
    color: var(--title-color);
    padding: 0.8rem 0.95rem;
  }

  .reviews-filter-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.65rem;
    grid-column: 1 / -1;
  }

  .reviews-card-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.9rem;
  }

  .review-card {
    display: grid;
    grid-template-columns: minmax(8.4rem, 9.6rem) minmax(0, 1fr);
    gap: 0.9rem;
    border-color: color-mix(in oklab, var(--review-accent) 18%, var(--border-color));
    background:
      linear-gradient(180deg, color-mix(in oklab, var(--terminal-bg) 98%, transparent), color-mix(in oklab, var(--review-accent) 5%, var(--header-bg))),
      radial-gradient(circle at top right, color-mix(in oklab, var(--review-accent) 12%, transparent), transparent 42%);
    transition: transform 180ms ease, border-color 180ms ease, box-shadow 180ms ease;
    padding: 0.8rem;
  }

  .review-card:hover {
    transform: translateY(-4px);
    border-color: color-mix(in oklab, var(--review-accent) 30%, var(--border-color));
    box-shadow: 0 18px 36px rgba(var(--text-rgb), 0.08);
  }

  .review-card__poster {
    position: relative;
    min-height: 13rem;
    border-radius: 0.95rem;
    overflow: hidden;
    border: 1px solid color-mix(in oklab, var(--review-accent) 18%, var(--border-color));
    background: color-mix(in oklab, var(--review-accent) 8%, var(--terminal-bg));
    box-shadow:
      0 14px 30px rgba(var(--text-rgb), 0.14),
      inset 0 1px 0 rgba(255, 255, 255, 0.08);
  }

  .review-card__poster-link {
    display: block;
    height: 100%;
    color: inherit;
    text-decoration: none;
  }

  .review-card__poster-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    transform: scale(1.01);
  }

  .review-card__poster-fallback {
    position: relative;
    height: 100%;
    min-height: 12rem;
    padding: 0.8rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background:
      linear-gradient(160deg, color-mix(in oklab, var(--review-accent) 26%, var(--terminal-bg)), color-mix(in oklab, var(--review-accent) 10%, var(--header-bg)) 42%, color-mix(in oklab, var(--terminal-bg) 94%, transparent)),
      radial-gradient(circle at top right, color-mix(in oklab, var(--review-accent) 26%, transparent), transparent 45%);
  }

  .review-card__poster-kicker {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.5rem;
    font-size: 0.68rem;
    letter-spacing: 0.18em;
    text-transform: uppercase;
    color: color-mix(in oklab, var(--title-color) 68%, var(--review-accent));
  }

  .review-card__poster-emoji {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 4rem;
    opacity: 0.9;
    filter: saturate(1.1);
  }

  .review-card__poster-title {
    position: relative;
    z-index: 1;
    font-size: 1rem;
    line-height: 1.35;
    font-weight: 700;
    color: var(--title-color);
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.18);
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .review-card__body {
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 0.72rem;
    justify-content: space-between;
  }

  .review-card__head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 0.9rem;
  }

  .review-card__badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.45rem;
    margin-bottom: 0.5rem;
  }

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

  .review-card__title-link {
    color: inherit;
    text-decoration: none;
    transition: color 180ms ease;
  }

  .review-card__title-link:hover {
    color: var(--review-accent);
  }

  .review-card__rating {
    text-align: right;
    flex-shrink: 0;
  }

  .review-card__rating-value {
    font-size: 1.25rem;
    line-height: 1;
    font-weight: 800;
    color: var(--review-accent);
  }

  .review-card__rating-stars {
    margin-top: 0.35rem;
    display: flex;
    justify-content: flex-end;
    gap: 0.2rem;
    font-size: 0.72rem;
  }

  .review-card__description {
    color: var(--text-secondary);
    font-size: 0.88rem;
    line-height: 1.62;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .review-card__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.55rem;
  }

  .review-card__link {
    display: inline-flex;
    align-items: center;
    gap: 0.42rem;
    padding: 0.3rem 0.72rem;
    border-radius: 999px;
    border: 1px solid color-mix(in oklab, var(--review-accent) 20%, var(--border-color));
    background: color-mix(in oklab, var(--review-accent) 10%, var(--terminal-bg));
    color: color-mix(in oklab, var(--review-accent) 60%, var(--title-color));
    font-size: 0.76rem;
    line-height: 1;
    text-decoration: none;
    transition: border-color 180ms ease, transform 180ms ease, background 180ms ease;
  }

  .review-card__link:hover {
    transform: translateY(-1px);
    border-color: color-mix(in oklab, var(--review-accent) 34%, var(--border-color));
    background: color-mix(in oklab, var(--review-accent) 16%, var(--terminal-bg));
  }

  .review-card__link--internal {
    color: var(--title-color);
  }

  .review-card__tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.45rem;
  }

  .review-filter__count {
    display: inline-flex;
    min-width: 1.4rem;
    height: 1.4rem;
    align-items: center;
    justify-content: center;
    padding: 0 0.38rem;
    border-radius: 999px;
    background: color-mix(in oklab, var(--terminal-bg) 82%, var(--border-color));
    color: var(--text-tertiary);
    font-size: 0.7rem;
    line-height: 1;
    font-variant-numeric: tabular-nums;
  }

  @media (max-width: 1024px) {
    .reviews-stats-grid,
    .reviews-card-grid,
    .reviews-filter-form {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  @media (max-width: 720px) {
    .reviews-stats-grid,
    .reviews-card-grid,
    .reviews-filter-form {
      grid-template-columns: minmax(0, 1fr);
    }

    .review-card {
      grid-template-columns: minmax(0, 1fr);
    }

    .review-card__poster {
      min-height: 14rem;
    }

    .review-card__head {
      flex-direction: column;
    }

    .review-card__rating {
      text-align: left;
    }

    .review-card__rating-stars {
      justify-content: flex-start;
    }
  }
</style>
