---
import Layout from '../../layouts/BaseLayout.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 } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import type { Review } from '../../lib/api/client';

export const prerender = false;

type ReviewStatus = 'completed' | 'in-progress' | 'dropped';

type ParsedReview = Omit<Review, 'tags'> & {
  tags: string[];
  normalizedStatus: ReviewStatus;
  coverIsImage: boolean;
  coverUrl: string | null;
  linkUrl: string | null;
  externalLink: boolean;
};

// Fetch reviews from backend API
let reviews: Awaited<ReturnType<typeof apiClient.getReviews>> = [];
const url = new URL(Astro.request.url);
const selectedType = url.searchParams.get('type') || 'all';
const { t } = getI18n(Astro);
try {
  reviews = await apiClient.getReviews();
} catch (error) {
  console.error('Failed to fetch reviews:', error);
}

const normalizeReviewStatus = (status: string | null | undefined): ReviewStatus => {
  const normalized = String(status || '').trim().toLowerCase();

  if (normalized === 'published' || normalized === 'completed' || normalized === 'done') {
    return 'completed';
  }

  if (normalized === 'draft' || normalized === 'in-progress' || normalized === 'watching' || normalized === 'reading' || normalized === 'listening') {
    return 'in-progress';
  }

  if (normalized === 'dropped' || normalized === 'abandoned') {
    return 'dropped';
  }

  return 'completed';
};

const isImageCover = (cover: string | null | undefined) => /^(https?:)?\/\//.test(String(cover || '').trim()) || String(cover || '').trim().startsWith('/');

const reviewCoverCatalog: Record<string, string> = {
  '《漫长的季节》': '/review-covers/the-long-season.svg',
  '《十三邀》': '/review-covers/thirteen-invites.svg',
  '《黑神话：悟空》': '/review-covers/black-myth-wukong.svg',
  '《置身事内》': '/review-covers/placed-within.svg',
  '《宇宙探索编辑部》': '/review-covers/journey-to-the-west-editorial.svg',
  '《疲惫生活中的英雄梦想》': '/review-covers/hero-dreams-in-tired-life.svg',
};

const resolveReviewCover = (review: Review) => {
  if (isImageCover(review.cover)) {
    return String(review.cover).trim();
  }

  return reviewCoverCatalog[review.title] || null;
};

const normalizeLinkUrl = (value: string | null | undefined) => {
  const trimmed = String(value || '').trim();
  return trimmed ? trimmed : null;
};

const isExternalLink = (value: string | null | undefined) => /^(https?:)?\/\//.test(String(value || '').trim());

// Parse tags from JSON string
const parsedReviews: ParsedReview[] = reviews.map(r => ({
  ...r,
  tags: r.tags ? JSON.parse(r.tags) as string[] : [],
  normalizedStatus: normalizeReviewStatus(r.status),
  coverIsImage: isImageCover(r.cover),
  coverUrl: resolveReviewCover(r),
  linkUrl: normalizeLinkUrl(r.link_url),
  externalLink: isExternalLink(r.link_url),
}));

const filteredReviews = selectedType === 'all'
  ? parsedReviews
  : parsedReviews.filter(review => review.review_type === selectedType);

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 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}%`,
  }
];
---

<Layout title={`${t('reviews.pageTitle')} | Termi`} description={t('reviews.pageDescription')}>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Single Terminal Window for entire page -->
    <TerminalWindow title="~/reviews" class="w-full">
      <div class="px-4 py-4 space-y-6">

        <!-- Header Section -->
        <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')}
                  {selectedType !== 'all' && ` · ${t('reviews.currentFilter', { type: typeLabels[selectedType] || selectedType })}`}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div>
          <CommandPrompt promptId="reviews-stats-prompt" 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
                      id={card.id === 'total' ? 'reviews-total' : card.id === 'average' ? 'reviews-average' : card.id === 'completed' ? 'reviews-completed' : 'reviews-progress'}
                      class="reviews-stat-card__value"
                    >
                      {card.value}
                    </div>
                    <div
                      id={card.id === 'total' ? 'reviews-total-detail' : card.id === 'completed' ? 'reviews-completed-detail' : card.id === 'progress' ? 'reviews-progress-detail' : undefined}
                      class:list={[
                        'reviews-stat-card__detail',
                        card.id === 'average' && 'hidden'
                      ]}
                    >
                      {card.id === 'average' ? '' : card.detail}
                    </div>
                    {card.id === 'average' && <div class="reviews-stat-card__detail">/ 5</div>}
                  </div>
                  {card.id === 'average' && (
                    <div id="reviews-average-stars" 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
                    id={card.id === 'total' ? 'reviews-total-bar' : card.id === 'completed' ? 'reviews-completed-bar' : card.id === 'progress' ? 'reviews-progress-bar' : 'reviews-average-bar'}
                    class="reviews-stat-card__bar-fill"
                    style={`width: ${card.barWidth};`}
                  ></div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div>
          <CommandPrompt promptId="reviews-filter-prompt" 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={filter.id === 'all' ? '/reviews' : `/reviews?type=${filter.id}`}
                data-review-filter={filter.id}
                data-review-label={filter.name}
                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 promptId="reviews-list-prompt" command="find . -maxdepth 1 -name '*.md' | sort" path="~/reviews" />
          <div class="ml-4 mt-2">
            <div class="reviews-card-grid">
              {parsedReviews.map(review => (
                <article
                  class="review-card terminal-panel group"
                  data-review-card
                  data-review-type={review.review_type}
                  data-review-status={review.normalizedStatus}
                  data-review-rating={review.rating || 0}
                  style={`--review-accent: ${typeColors[review.review_type] || '#888'};`}
                >
                  <div class="review-card__poster">
                    {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>
                    )}
                  </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:${typeColors[review.review_type] === '#4285f4' ? '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">{review.title}</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">
                      <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) => (
                        <span class="terminal-chip text-xs py-1 px-2.5">
                          #{tag}
                        </span>
                      ))}
                    </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>

        <!-- Back to Home -->
        <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>
  <script
    is:inline
    define:vars={{
      reviewTypeLabels: {
        game: t('reviews.typeGame'),
        anime: t('reviews.typeAnime'),
        music: t('reviews.typeMusic'),
        book: t('reviews.typeBook'),
        movie: t('reviews.typeMovie'),
        all: t('reviews.typeAll'),
      },
      reviewsBaseSubtitle: t('reviews.subtitle'),
    }}
  >
  (function() {
    /** @type {Window['__termiCommandPrompt']} */
    let promptApi;

    const typeLabels = reviewTypeLabels;

    const cards = Array.from(document.querySelectorAll('[data-review-card]'));
    const filters = Array.from(document.querySelectorAll('[data-review-filter]'));
    const subtitle = document.getElementById('reviews-subtitle');
    const totalEl = document.getElementById('reviews-total');
    const avgEl = document.getElementById('reviews-average');
    const completedEl = document.getElementById('reviews-completed');
    const progressEl = document.getElementById('reviews-progress');
    const totalDetailEl = document.getElementById('reviews-total-detail');
    const totalBarEl = document.getElementById('reviews-total-bar');
    const averageStarsEl = document.getElementById('reviews-average-stars');
    const completedDetailEl = document.getElementById('reviews-completed-detail');
    const completedBarEl = document.getElementById('reviews-completed-bar');
    const progressDetailEl = document.getElementById('reviews-progress-detail');
    const progressBarEl = document.getElementById('reviews-progress-bar');
    const emptyState = document.getElementById('reviews-empty-state');
    const t = window.__termiTranslate;
    const baseSubtitle = reviewsBaseSubtitle;
    promptApi = window.__termiCommandPrompt;

    function updateReviewPrompts(type) {
      const selectedType = type || 'all';
      const statsCommand = selectedType === 'all'
        ? "jq '.summary' stats.json"
        : `jq '.summary.${selectedType}' stats.json`;
      const filterCommand = selectedType === 'all'
        ? "printf '%s\\n' all game anime music book movie"
        : `printf '%s\\n' ${selectedType}`;
      const listCommand = selectedType === 'all'
        ? "find . -maxdepth 1 -name '*.md' | sort"
        : `grep -El '^type: ${selectedType}$' ./*.md`;

      promptApi?.set?.('reviews-stats-prompt', statsCommand, { typing: false });
      promptApi?.set?.('reviews-filter-prompt', filterCommand, { typing: false });
      promptApi?.set?.('reviews-list-prompt', listCommand, { typing: false });
    }

    function updateFilterUi(activeType) {
      filters.forEach((filter) => {
        const isActive = filter.dataset.reviewFilter === activeType;
        filter.classList.toggle('is-active', isActive);
      });
    }

    function updateStats(visibleCards) {
      const total = visibleCards.length;
      const average = total
        ? (visibleCards.reduce((sum, card) => sum + Number(card.dataset.reviewRating || 0), 0) / total).toFixed(1)
        : '0';
      const completed = visibleCards.filter((card) => card.dataset.reviewStatus === 'completed').length;
      const inProgress = visibleCards.filter((card) => card.dataset.reviewStatus === 'in-progress').length;
      const highRatingCount = visibleCards.filter((card) => Number(card.dataset.reviewRating || 0) >= 4).length;
      const completedRatio = total ? Math.round((completed / total) * 100) : 0;
      const inProgressRatio = total ? Math.round((inProgress / total) * 100) : 0;

      if (totalEl) totalEl.textContent = String(total);
      if (avgEl) avgEl.textContent = average;
      if (completedEl) completedEl.textContent = String(completed);
      if (progressEl) progressEl.textContent = String(inProgress);
      if (totalDetailEl) totalDetailEl.textContent = `≥4 ★ · ${highRatingCount}`;
      if (totalBarEl) totalBarEl.style.width = `${total ? Math.max((highRatingCount / total) * 100, 12) : 12}%`;
      if (completedDetailEl) completedDetailEl.textContent = `${completedRatio}%`;
      if (completedBarEl) completedBarEl.style.width = `${completedRatio}%`;
      if (progressDetailEl) progressDetailEl.textContent = `${inProgressRatio}%`;
      if (progressBarEl) progressBarEl.style.width = `${inProgressRatio}%`;
      if (averageStarsEl) {
        const roundedAverage = Math.round(Number(average));
        averageStarsEl.innerHTML = Array.from({ length: 5 }, (_, index) =>
          `<i class="fas fa-star ${index < roundedAverage ? '' : 'opacity-25'}"></i>`
        ).join('');
      }
    }

    function applyFilter(type, pushState = true) {
      const visibleCards = cards.filter((card) => type === 'all' || card.dataset.reviewType === type);

      cards.forEach((card) => {
        card.style.display = visibleCards.includes(card) ? '' : 'none';
      });

      if (emptyState) {
        emptyState.classList.toggle('hidden', visibleCards.length > 0);
      }

      updateFilterUi(type);
      updateStats(visibleCards);

      if (subtitle) {
        subtitle.textContent = type === 'all'
          ? baseSubtitle
          : `${baseSubtitle} · ${t('reviews.currentFilter', { type: typeLabels[type] || type })}`;
      }

      if (pushState) {
        const nextUrl = type === 'all' ? '/reviews' : `/reviews?type=${encodeURIComponent(type)}`;
        window.history.replaceState({}, '', nextUrl);
      }

      updateReviewPrompts(type);
    }

    filters.forEach((filter) => {
      filter.addEventListener('click', (event) => {
        event.preventDefault();
        applyFilter(filter.dataset.reviewFilter || 'all');
      });
    });

    applyFilter(new URL(window.location.href).searchParams.get('type') || 'all', false);
  })();
  </script>
</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-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-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__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__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 {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  @media (max-width: 720px) {
    .reviews-stats-grid,
    .reviews-card-grid {
      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>
