/**
 * OpportunityScores — UX-213 / OPP-10
 *
 * Shared score display used by both UnifiedCard (Action Queue) and
 * RecommendationCard (Recommendations surface) to ensure identical
 * stat vocabulary, numeral font, and tooltip framing across surfaces.
 *
 * Impact and Confidence are rendered as qualitative High/Medium/Low
 * labels with font-data tabular-nums numerics and InfoTooltips that
 * explain the scoring methodology in plain English.
 *
 * OPP-10: optional `rankingRationale` surfaces the top ranking drivers
 * as small driver chips + a one-line plain-English sentence beneath the
 * scores, so the persona can immediately understand why this row is ranked
 * where it is without opening the detail drawer.
 */
import { Badge } from '@/Components/ui/badge';
import { InfoTooltip } from '@/Components/ui/info-tooltip';
import { formatConfidenceScore } from '@/lib/format';

// ─── Confidence helpers (module-private) ─────────────────────────────────────
// Not exported — react-refresh/only-export-components requires a file to export
// only components (or nothing). If callers outside this file need these helpers,
// extract to a separate lib/confidence.ts utility.

function getConfidenceLevel(score: number): string {
  if (score >= 67) return 'High';
  if (score >= 34) return 'Medium';
  return 'Low';
}

function getConfidenceBadgeVariant(
  score: number,
): 'default' | 'medium' | 'secondary' | 'outline' {
  if (score >= 67) return 'default';
  if (score >= 34) return 'secondary';
  return 'outline';
}

// ─── Ranking rationale types (OPP-10) ────────────────────────────────────────

/**
 * A single ranking driver chip: a short label the persona can scan at a glance.
 * Kept as a value object so callers (UnifiedCard) derive it from demand data and
 * the component stays purely presentational.
 */
export interface RankingDriver {
  /** Short display label, e.g. "1,200 impressions" or "−45% clicks" */
  label: string;
  /** Accessible description for screen readers / tooltip fallback */
  description: string;
}

/**
 * Ranking rationale passed to OpportunityScores (OPP-10).
 * Both fields are optional; the component renders gracefully when absent.
 */
export interface RankingRationale {
  /**
   * One-line plain-English sentence explaining the rank, e.g.
   * "Ranked high: losing ~800 clicks/month with high confidence."
   */
  sentence: string;
  /** Up to 3 driver chips. Rendered as small muted pills beneath the scores. */
  drivers: RankingDriver[];
}

// ─── Component ───────────────────────────────────────────────────────────────

interface OpportunityScoresProps {
  /** 0–100 impact score */
  impactScore: number;
  /** 0–100 confidence score */
  confidenceScore: number;
  /**
   * OPP-10: optional ranking explanation derived by UnifiedCard from the
   * opportunity's demand data. When present, driver chips + a one-line sentence
   * appear beneath the scores so the persona understands the queue order.
   */
  rankingRationale?: RankingRationale;
}

/**
 * Renders Impact + Confidence in a compact side-by-side layout with:
 *   - font-data tabular-nums numerics for density alignment
 *   - Qualitative High/Medium/Low badge for confidence (easier to scan)
 *   - InfoTooltips on both labels explaining the methodology
 *   - OPP-10: optional ranking rationale (sentence + driver chips) beneath
 */
export function OpportunityScores({
  impactScore,
  confidenceScore,
  rankingRationale,
}: OpportunityScoresProps) {
  return (
    <div className="flex flex-col items-end gap-1.5 sm:shrink-0">
      {/* Scores row */}
      <div className="flex items-center gap-4">
        {/* Impact */}
        <div className="text-center">
          <p className="font-data text-2xl font-semibold tabular-nums leading-none">
            {Math.round(impactScore)}
          </p>
          <div className="mt-0.5 inline-flex items-center gap-0.5">
            <p className="text-xs text-muted-foreground">Impact</p>
            <InfoTooltip
              content="Estimated traffic upside (0–100). Higher scores indicate pages with more recoverable clicks if the recommended action is applied."
              side="top"
              iconClassName="h-3 w-3"
            />
          </div>
        </div>

        {/* Confidence */}
        <div className="text-center">
          <div className="inline-flex items-center gap-1 mb-0.5">
            <Badge variant={getConfidenceBadgeVariant(confidenceScore)}>
              {getConfidenceLevel(confidenceScore)}
            </Badge>
            <InfoTooltip
              content="Confidence: how certain we are this recommendation will improve your traffic (based on data analysis). Low (0–33%), Medium (34–66%), High (67–100%)"
              side="top"
              iconClassName="h-3 w-3"
            />
          </div>
          <p className="text-xs text-muted-foreground font-data tabular-nums">
            {formatConfidenceScore(confidenceScore)}
          </p>
        </div>
      </div>

      {/* OPP-10: ranking rationale — driver chips + one-line sentence */}
      {rankingRationale && (
        <div
          className="flex flex-col items-end gap-1 max-w-[220px]"
          data-testid="ranking-rationale"
        >
          {/* Driver chips — up to 3, right-aligned to match score widget */}
          {rankingRationale.drivers.length > 0 && (
            <div className="flex flex-wrap justify-end gap-1">
              {rankingRationale.drivers.map((driver) => (
                <span
                  key={driver.label}
                  title={driver.description}
                  className="inline-block rounded px-1.5 py-0.5 text-[10px] font-medium bg-muted text-muted-foreground leading-none"
                >
                  {driver.label}
                </span>
              ))}
            </div>
          )}
          {/* Plain-English ranking sentence */}
          <p className="text-[10px] text-muted-foreground text-right leading-tight">
            {rankingRationale.sentence}
          </p>
        </div>
      )}
    </div>
  );
}
