import React from 'react';

import type {
  ScanHistoryPoint,
  VisibilityProblem,
} from '../../service/visibility/visibility.interface';

interface MentionedVsCitedCalloutProps {
  scanHistory: ScanHistoryPoint[];
  weekIso: string;
  problems: VisibilityProblem[];
}

const numericMetric = (
  problems: VisibilityProblem[] | null | undefined,
  key: string
): number | null => {
  if (!Array.isArray(problems)) return null;
  for (const problem of problems) {
    const raw = problem?.metrics?.[key];
    if (typeof raw === 'number' && Number.isFinite(raw)) {
      return raw;
    }
  }

  return null;
};

/**
 * "Mentioned vs cited" callout. Composes an English sentence from the
 * metrics we have on hand. Falls back to a simpler message when the
 * citation rate isn't reported for the selected week.
 */
const MentionedVsCitedCallout = ({
  scanHistory,
  weekIso,
  problems,
}: MentionedVsCitedCalloutProps): JSX.Element | null => {
  if (!Array.isArray(scanHistory) || scanHistory.length === 0) {
    return null;
  }
  const point =
    scanHistory.find(p => p?.week_iso === weekIso) ?? scanHistory[0];
  if (
    !point ||
    !point.queries_checked ||
    typeof point.brand_mentions !== 'number'
  ) {
    return null;
  }

  const mentionRate =
    Math.round((point.brand_mentions / point.queries_checked) * 1000) / 10;
  const citationRate = numericMetric(problems, 'citation_rate');

  const mentionSentence = `Your brand appeared in ${mentionRate}% of prompts this week`;
  const body =
    citationRate !== null
      ? `${mentionSentence}, but was cited from your own domain in only ${citationRate}%.`
      : `${mentionSentence}.`;

  return (
    <div className="rounded-xl border border-blue-200 bg-blue-50 p-4">
      <p className="text-sm font-semibold text-blue-900">Mentioned vs cited</p>
      <p className="mt-1 text-sm text-blue-900">{body}</p>
    </div>
  );
};

export default MentionedVsCitedCallout;
