/* =====================================================================
 * AlgorithmCorrelationCard — Google algorithm update ↔ traffic insight
 *
 * Surfaces the most recent Google algorithm update that correlates with a
 * shift in the site's organic clicks. Card-only, hairline editorial idiom
 * (matches IntegrationStatusCard). NO chart / timeline overlay.
 *
 * Behaviour: returns null when there is no correlated update (the common
 * case for new accounts) so the dashboard never renders an empty box.
 *
 * Low-confidence state: when `low_confidence` is true the service could not
 * compute a trustworthy percentage (before-window clicks below the
 * min_baseline_clicks threshold). The card renders the update name and an
 * honest "not enough data" message rather than a misleading headline %.
 * ===================================================================== */
import { ArrowDownRight, ArrowUpRight, Minus } from 'lucide-react';

import { cn } from '@/lib/utils';

export interface AlgorithmCorrelation {
  key: string;
  name: string;
  type: string;
  started_at: string;
  ended_at: string | null;
  delta_percent: number | null;
  direction: 'negative' | 'positive' | 'flat';
  clicks_before: number;
  clicks_after: number;
  url: string | null;
  /**
   * Optional for backward-compatibility: older cached Inertia payloads may
   * omit this field. When missing it defaults to `false` (i.e., assume the
   * data is trustworthy rather than silently showing a stale low-confidence
   * marker). The field is always present in current backend responses.
   */
  low_confidence?: boolean;
}

interface AlgorithmCorrelationCardProps {
  correlations: AlgorithmCorrelation[];
}

const TYPE_LABELS: Record<string, string> = {
  core: 'Core Update',
  spam: 'Spam Update',
  helpful_content: 'Helpful Content Update',
  reviews: 'Reviews Update',
  other: 'Algorithm Update',
};

function formatDelta(deltaPercent: number | null): string {
  if (deltaPercent === null) return '—';
  if (!Number.isFinite(deltaPercent)) return '—';
  const sign = deltaPercent > 0 ? '+' : '';
  return `${sign}${deltaPercent.toFixed(1)}%`;
}

/**
 * Returns the human-readable impact description for the headline row.
 * When low_confidence is true we describe the observed period honestly
 * without surfacing a headline percentage that could be misleading.
 */
function impactLabel(c: AlgorithmCorrelation): string {
  if (c.low_confidence) return 'Not enough traffic data to assess impact';
  if (c.delta_percent === null) return 'No baseline to compare';
  if (c.direction === 'flat') return 'No clear impact';
  return `Observed change around this update: ${formatDelta(c.delta_percent)} clicks`;
}

export default function AlgorithmCorrelationCard({
  correlations,
}: AlgorithmCorrelationCardProps) {
  // Empty state: render nothing so the dashboard layout stays clean for
  // accounts with no correlated update.
  if (!correlations || correlations.length === 0) return null;

  // Surface the most recent correlation prominently (service returns the list
  // sorted by started_at descending), with any older ones as quiet rows.
  const [primary, ...rest] = correlations;

  const directionStyles: Record<
    AlgorithmCorrelation['direction'],
    { icon: typeof ArrowDownRight; tone: string }
  > = {
    negative: { icon: ArrowDownRight, tone: 'text-destructive' },
    positive: { icon: ArrowUpRight, tone: 'text-success-strong' },
    flat: { icon: Minus, tone: 'text-muted-foreground' },
  };

  // When low-confidence, always render as flat/muted — no directional signal.
  const effectiveDirection = primary.low_confidence ? 'flat' : primary.direction;
  const PrimaryIcon = directionStyles[effectiveDirection].icon;
  const primaryTone = directionStyles[effectiveDirection].tone;

  return (
    <div className="rounded-2xl border bg-card overflow-hidden">
      <div className="flex items-center justify-between gap-3 px-5 py-4 border-b">
        <h3 className="text-sm font-semibold tracking-tight">Algorithm Update Impact</h3>
        <span className="font-data text-[11px] uppercase tracking-[0.16em] text-muted-foreground tabular-nums">
          {TYPE_LABELS[primary.type] ?? TYPE_LABELS.other}
        </span>
      </div>

      <div className="px-5 py-4">
        <div className="flex items-start justify-between gap-4">
          <div className="min-w-0">
            <p className="text-sm font-medium text-foreground">{primary.name}</p>
            <p className="mt-1 text-xs text-muted-foreground">{impactLabel(primary)}</p>
          </div>
          {/* Only render the headline % when the signal is trustworthy */}
          {!primary.low_confidence && (
            <div className={cn('flex items-center gap-1.5 shrink-0', primaryTone)}>
              <PrimaryIcon className="size-4" aria-hidden="true" />
              <span className="font-data text-2xl font-semibold tabular-nums tracking-tight">
                {formatDelta(primary.delta_percent)}
              </span>
            </div>
          )}
        </div>
        {primary.url && (
          <a
            href={primary.url}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-3 inline-block font-data text-[11px] uppercase tracking-[0.16em] font-semibold text-primary hover:underline"
          >
            Google announcement →
          </a>
        )}
      </div>

      {rest.length > 0 && (
        <ul className="divide-y border-t">
          {rest.map((c) => {
            const effectiveDir = c.low_confidence ? 'flat' : c.direction;
            const Icon = directionStyles[effectiveDir].icon;
            const tone = directionStyles[effectiveDir].tone;
            return (
              <li
                key={c.key}
                className="flex items-center justify-between gap-3 px-5 py-2.5 text-sm"
              >
                <span className="truncate text-muted-foreground">{c.name}</span>
                <span className={cn('flex items-center gap-1 shrink-0 font-data tabular-nums', tone)}>
                  {c.low_confidence ? (
                    <span className="text-xs text-muted-foreground">insufficient data</span>
                  ) : (
                    <>
                      <Icon className="size-3.5" aria-hidden="true" />
                      {formatDelta(c.delta_percent)}
                    </>
                  )}
                </span>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
