'use client';

import type { ReportSynthesis, ReviewEvidence as ReviewEvidenceType, ReviewClassification } from '../types';
import type { ReportLocale } from '../i18n/useReportLocale';
import { useReportLocale } from '../i18n/useReportLocale';
import ReportPage from '../components/ReportPage';
import SectionHeader from '../components/SectionHeader';
import { getValenceColor, getDomainColor } from '../styles/report-theme';
import { translatePrimitive } from '../i18n/contentTranslations';
import { paginateItems } from '../utils/paginate';

interface ReviewEvidenceProps {
  report: ReportSynthesis;
  locale?: ReportLocale;
  startPage?: number;
  totalPages?: number;
  sectionNumber?: number | string;
}

/** Build highlighted review text with anchor spans color-coded by valence. */
function HighlightedReviewText({ text, classifications }: { text: string; classifications: ReviewClassification[] }) {
  // Sort anchors by start position (descending) to avoid offset shift
  const anchors = classifications
    .filter(c => c.anchor_start != null && c.anchor_end != null)
    .sort((a, b) => (a.anchor_start ?? 0) - (b.anchor_start ?? 0));

  if (anchors.length === 0) {
    return <span className="body-sm text-secondary">{text}</span>;
  }

  const parts: React.ReactNode[] = [];
  let cursor = 0;

  for (const anchor of anchors) {
    const start = anchor.anchor_start!;
    const end = anchor.anchor_end!;

    // Skip overlapping or invalid anchors
    if (start < cursor || start >= text.length) continue;

    // Text before anchor
    if (cursor < start) {
      parts.push(<span key={`pre-${start}`} className="body-sm text-secondary">{text.slice(cursor, start)}</span>);
    }

    // Anchor span
    const valenceColorMap: Record<string, string> = {
      '+': '#DCFCE7',
      '-': '#FEE2E2',
      '±': '#FEF3C7',
      '0': '#F3F4F6',
    };
    const bgColor = valenceColorMap[anchor.valence] || '#F3F4F6';
    const borderColor = getValenceColor(anchor.valence);

    parts.push(
      <span
        key={`anchor-${start}`}
        title={`${anchor.primitive} (${anchor.valence})`}
        style={{
          backgroundColor: bgColor,
          borderBottom: `2px solid ${borderColor}`,
          borderRadius: 2,
          padding: '0 2px',
        }}
      >
        <span className="body-sm" style={{ fontWeight: 500 }}>{text.slice(start, Math.min(end, text.length))}</span>
      </span>
    );
    cursor = Math.min(end, text.length);
  }

  // Remaining text
  if (cursor < text.length) {
    parts.push(<span key="tail" className="body-sm text-secondary">{text.slice(cursor)}</span>);
  }

  return <>{parts}</>;
}

function StarRating({ rating }: { rating: number }) {
  return (
    <span style={{ fontSize: 12, letterSpacing: 1 }}>
      {Array.from({ length: 5 }, (_, i) => (
        <span key={i} style={{ color: i < rating ? '#FBBC05' : '#D1D5DB' }}>★</span>
      ))}
    </span>
  );
}

// 3 reviews per first page, 4 per subsequent
const FIRST_PAGE_LIMIT = 3;
const NEXT_PAGE_LIMIT = 4;

export default function ReviewEvidence({
  report,
  locale = 'en',
  startPage = 10,
  totalPages = 12,
  sectionNumber = 'A',
}: ReviewEvidenceProps) {
  const { t } = useReportLocale(locale);
  const reviews = report.review_evidence;

  if (!reviews?.length) return null;

  // Only show reviews with text
  const filtered = reviews.filter(r => r.full_text && r.full_text.length > 0);
  if (filtered.length === 0) return null;

  const pages = paginateItems(filtered, FIRST_PAGE_LIMIT, NEXT_PAGE_LIMIT);

  return (
    <>
      {pages.map((pageItems, pageIdx) => (
        <ReportPage key={pageIdx} pageNumber={startPage + pageIdx} totalPages={totalPages} background="white">
          {pageIdx === 0 ? (
            <SectionHeader
              number={sectionNumber}
              title={t('appendix_review_evidence')}
              subtitle={t('appendix_lead')}
            />
          ) : (
            <div className="caption" style={{ marginBottom: 16, fontSize: 12 }}>
              {t('appendix_review_evidence')} ({t('continued')})
            </div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {pageItems.map((review, idx) => (
              <ReviewCard
                key={review.review_id}
                review={review}
                locale={locale}
                t={t}
              />
            ))}
          </div>
        </ReportPage>
      ))}
    </>
  );
}

function ReviewCard({
  review,
  locale,
  t,
}: {
  review: ReviewEvidenceType;
  locale: string;
  t: (key: string) => string;
}) {
  return (
    <div style={{
      padding: '12px 0',
      borderBottom: '1px solid var(--border-light)',
    }}>
      {/* Header: author + rating + date */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="heading-md" style={{ fontSize: 13 }}>
            {review.author || t('anonymous')}
          </span>
          {review.rating && <StarRating rating={review.rating} />}
          {review.date && (
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
              {isNaN(Date.parse(review.date)) ? review.date : new Date(review.date).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' })}
            </span>
          )}
        </div>
      </div>

      {/* Highlighted review text */}
      <div style={{ marginBottom: 8, lineHeight: 1.6 }}>
        <HighlightedReviewText
          text={review.full_text}
          classifications={review.classifications}
        />
      </div>

      {/* Classification tags */}
      {review.classifications.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {review.classifications.map((cls, i) => {
            const color = getValenceColor(cls.valence);
            const bgMap: Record<string, string> = { '+': '#DCFCE7', '-': '#FEE2E2', '±': '#FEF3C7', '0': '#F3F4F6' };
            const textMap: Record<string, string> = { '+': '#166534', '-': '#991B1B', '±': '#92400E', '0': '#6B7280' };
            const bg = bgMap[cls.valence] || '#F3F4F6';
            const textColor = textMap[cls.valence] || '#6B7280';
            return (
              <span
                key={i}
                style={{
                  fontSize: 10,
                  background: bg,
                  color: textColor,
                  borderLeft: `3px solid ${color}`,
                  paddingLeft: 6,
                  padding: '2px 8px 2px 6px',
                  borderRadius: 4,
                  fontWeight: 500,
                }}
              >
                {translatePrimitive(cls.primitive, locale)} <span style={{ fontWeight: 700 }}>{cls.valence}</span>
              </span>
            );
          })}
        </div>
      )}
    </div>
  );
}
