/**
 * HeroKpiBand — the four-up KPI band at the top of the SharedReport surface.
 *
 * Visual language is borrowed from the operator design language but adapted
 * for a point-in-time snapshot:
 *   - Monospace numerals (`font-data`) with tabular-nums for stable digit width
 *   - Eyebrow label in muted uppercase tracking
 *   - Optional delta below the value (no count-up, no pulsing live dot —
 *     these are end-of-period totals, not live counters)
 *
 * Only renders the metrics the report has data for (clicks, impressions,
 * CTR, position). Any subset is fine — the grid reflows.
 */
import { ArrowDown, ArrowUp, Minus } from 'lucide-react';

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

interface KpiCellProps {
  label: string;
  value: string;
  delta?: number;
  /**
   * For "position", a lower number is better — invert the delta color logic.
   * Default: higher is better.
   */
  invertDeltaColor?: boolean;
}

function DeltaPill({ delta, invert }: { delta: number; invert?: boolean }) {
  if (delta === 0) {
    return (
      <span className="font-data inline-flex items-center gap-1 text-xs text-muted-foreground">
        <Minus className="size-3" aria-hidden="true" />
        <span>0%</span>
      </span>
    );
  }

  const positive = delta > 0;
  const isGood = invert ? !positive : positive;
  const colorClass = isGood ? 'text-success' : 'text-destructive';
  const Icon = positive ? ArrowUp : ArrowDown;
  const sign = positive ? '+' : '−';
  const formatted = `${sign}${Math.abs(delta).toFixed(1)}%`;

  return (
    <span
      className={cn(
        'font-data inline-flex items-center gap-1 text-xs font-medium',
        colorClass,
      )}
    >
      <Icon className="size-3" aria-hidden="true" />
      <span className="sr-only">
        {positive ? 'increased by' : 'decreased by'} {Math.abs(delta).toFixed(1)} percent —{' '}
        {isGood ? 'improvement' : 'regression'}
      </span>
      <span aria-hidden="true">{formatted}</span>
    </span>
  );
}

function KpiCell({ label, value, delta, invertDeltaColor }: KpiCellProps) {
  // Border-l only applies at sm+ where the grid is 4-col single-row. On mobile
  // (2-col 2-row grid) we rely on `gap-6` for separation — putting border-l
  // there would dangle a vertical line in the middle of row 2, since `first:`
  // only matches the first child in the entire grid, not the first of each row.
  return (
    <div className="flex flex-col gap-2 sm:border-l sm:border-border sm:pl-6 sm:first:border-l-0 sm:first:pl-0">
      <span className="font-data text-[0.6875rem] uppercase tracking-[0.18em] text-muted-foreground">
        {label}
      </span>
      <span className="font-data text-3xl font-semibold tracking-tight text-foreground sm:text-4xl">
        {value}
      </span>
      {typeof delta === 'number' && Number.isFinite(delta) && (
        <DeltaPill delta={delta} invert={invertDeltaColor} />
      )}
    </div>
  );
}

interface HeroKpiBandProps {
  cells: KpiCellProps[];
  className?: string;
}

export function HeroKpiBand({ cells, className }: HeroKpiBandProps) {
  if (cells.length === 0) return null;

  return (
    <section
      aria-label="Headline metrics"
      className={cn(
        // Hairline-grid backdrop for the headline strip — an editorial flourish
        // that anchors the section without competing with the content below.
        'relative overflow-hidden rounded-xl border border-border bg-card',
        'px-6 py-8 sm:px-10 sm:py-10',
        'print:border-0 print:bg-transparent print:px-0 print:py-4',
        className,
      )}
    >
      <div
        aria-hidden="true"
        className="bg-grid-hair pointer-events-none absolute inset-0 opacity-60 print:hidden"
      />
      <div className="relative grid grid-cols-2 gap-6 sm:grid-cols-4 sm:gap-0">
        {cells.map((cell) => (
          <KpiCell key={cell.label} {...cell} />
        ))}
      </div>
    </section>
  );
}
