import type { ProductReview } from 'brainerce';
import { getServerClient } from '@/core/lib/brainerce.server';
import { isReviewsDisabledError } from '@/core/lib/reviews-disabled';
import { CdnImage } from '@/ui/shared/cdn-image';
<% if (i18nEnabled) { %>import { getMessages, defaultLocale } from '@/i18n';<% } else { %>import { defaultLocale, messages } from '@/i18n';<% } %>
import { ReviewForm } from './review-form';

// Server component — it renders before any client i18n context exists, so the
// wrapper strings (title / empty state / verified badge) are read straight
// from the `reviews` namespace in messages/, keyed by the store locale.
type ReviewStrings = Record<string, string>;

<% if (i18nEnabled) { %>async function getReviewStrings(locale: string): Promise<ReviewStrings> {
  return ((await getMessages(locale)).reviews ?? {}) as ReviewStrings;
}<% } else { %>async function getReviewStrings(_locale: string): Promise<ReviewStrings> {
  return messages.reviews as ReviewStrings;
}<% } %>

interface ReviewsSectionProps {
  productId: string;
  initialReviews?: ProductReview[];
  /**
   * REQUIRED on purpose (pass `locale={locale}` from the route, or `undefined` on a
   * single-language store). It used to be optional with a default, so a caller that
   * forgot it compiled fine and silently rendered this block in the default language.
   */
  locale: string | undefined;
  /** Where to send users back to after submit (defaults to the current product URL). */
  returnUrl?: string;
}

/**
 * Renders the visible reviews for a product plus a submit form.
 *
 * Server component — fetches with the SDK on the server so reviews are in
 * the initial HTML payload (good for SEO; JSON-LD on the same page already
 * carries `aggregateRating` when reviewCount > 0).
 */
export async function ReviewsSection({
  productId,
  initialReviews,
  locale,
}: ReviewsSectionProps) {
  const t = await getReviewStrings(locale ?? defaultLocale);
  let reviews: ProductReview[] = initialReviews ?? [];

  if (!initialReviews) {
    try {
      const result = await (await getServerClient()).listProductReviews(productId, { page: 1, limit: 20, sort: 'photos_first' });
      reviews = result.data;
    } catch (err) {
      // The merchant switched reviews off: this store collects none, so render
      // nothing (no heading, no "no reviews yet", no form). Any other failure
      // (network, 5xx) is not "off": render the form with an empty list.
      if (isReviewsDisabledError(err)) return null;
      reviews = [];
    }
  }

  return (
    <section aria-labelledby="reviews-heading">
      {/* DESIGN ME — product reviews: server-fetched review list (SDK listProductReviews) + eligibility-aware submit form. Compose with the shadcn/ui primitives in src/components/ui (Button, Card, Badge, Input, Select, Accordion, Dialog, Skeleton, ...) + lucide-react icons. */}
      <h2 id="reviews-heading">{t.title}</h2>

      {reviews.length === 0 ? (
        <p>{t.noReviews}</p>
      ) : (
        <ul>
          {reviews.map((review) => (
            <ReviewCard key={review.id} review={review} verifiedLabel={t.verifiedPurchase} />
          ))}
        </ul>
      )}

      <ReviewForm productId={productId} />
    </section>
  );
}

function ReviewCard({ review, verifiedLabel }: { review: ProductReview; verifiedLabel: string }) {
  return (
    <li>
      <article>
        <header className="flex flex-wrap items-center gap-2">
          <Stars rating={review.rating} />
          <span>{review.authorName}</span>
          {review.verifiedPurchase && <span>{verifiedLabel}</span>}
          <time dateTime={review.createdAt}>{new Date(review.createdAt).toLocaleDateString()}</time>
        </header>
        {review.body && <p className="whitespace-pre-line break-words">{review.body}</p>}
        <ReviewPhotos review={review} />
      </article>
    </li>
  );
}

/**
 * Photos the reviewer attached. `review.images` is always an array and already
 * carries only what shoppers are allowed to see, so there is nothing to filter.
 *
 * The intrinsic width/height come back from the API — passing them through is
 * what stops the page jumping as the photos load.
 */
function ReviewPhotos({ review }: { review: ProductReview }) {
  if (review.images.length === 0) return null;

  return (
    <ul className="mt-3 flex flex-wrap gap-2">
      {review.images.map((image) => (
        <li key={image.id}>
          <a href={image.url} target="_blank" rel="noopener noreferrer">
            <CdnImage
              src={image.thumbnailUrl ?? image.url}
              alt=""
              width={image.width ?? 96}
              height={image.height ?? 96}
              className="h-24 w-24 rounded-md border object-cover"
            />
          </a>
        </li>
      ))}
    </ul>
  );
}

function Stars({ rating }: { rating: number }) {
  return (
    <span aria-label={`${rating} of 5 stars`}>
      {[1, 2, 3, 4, 5].map((n) => (
        <span key={n} aria-hidden="true">
          {n <= rating ? '★' : '☆'}
        </span>
      ))}
    </span>
  );
}
