import React from 'react';
import type { GhostNote, ResearchDensityMode } from '../../../types/research';
import { ConfidenceBadge, CitationPill } from './Badges';
import { GHOST_CLASS_LABELS } from './researchMeta';

interface GhostCardProps {
  ghost: GhostNote;
  density: ResearchDensityMode;
  isSelected?: boolean;
  onSelect?: () => void;
  onSelectNote?: (noteId: string) => void;
  actions?: React.ReactNode;
}

const labelize = (value: string) =>
  value
    .split('_')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');

const leverageLabel = (score?: number) => {
  if ((score ?? 0) >= 0.78) {
    return 'High leverage';
  }
  if ((score ?? 0) >= 0.55) {
    return 'Medium leverage';
  }
  return 'Low leverage';
};

export const GhostCard: React.FC<GhostCardProps> = ({
  ghost,
  density,
  isSelected = false,
  onSelect,
  onSelectNote,
  actions,
}) => {
  const target = ghost.targetClaimText || ghost.headline;
  const counterCase = ghost.counterCase || ghost.body;
  const resolutionStatus = ghost.resolutionStatus ?? 'open';
  const supportStrength = ghost.supportStrength ?? (ghost.evidenceThresholdMet ? 'strong' : 'none');

  return (
    // Fixed padding classes keep Tailwind output deterministic across density modes.
    <button
      type="button"
      onClick={onSelect}
      className={`flex w-full flex-col gap-3 rounded-2xl border text-left transition-all hover:border-info hover:bg-term-surface ${
        density === 'detailed' ? 'p-5' : density === 'compact' ? 'p-3' : 'p-4'
      } ${
        isSelected ? 'border-info bg-term-elevated' : 'border-term-border bg-term-bg'
      }`}
    >
      <div className="flex flex-wrap items-center justify-between gap-2">
        <CitationPill label={GHOST_CLASS_LABELS[ghost.ghostClass]} />
        <ConfidenceBadge confidence={ghost.confidence} />
      </div>
      <div>
        <h3 className="text-sm font-semibold text-term-text">{ghost.headline}</h3>
        <p className="mt-2 text-sm leading-6 text-term-text-muted line-clamp-3">{target}</p>
        <p className="mt-2 text-xs leading-5 text-term-text-tertiary line-clamp-3">
          Counter-case: {counterCase}
        </p>
      </div>
      <div className="flex flex-wrap gap-2 text-[11px] text-term-text-tertiary">
        <span>{leverageLabel(ghost.leverageScore)}</span>
        <span>Support: {labelize(supportStrength)}</span>
        <span>Status: {labelize(resolutionStatus)}</span>
      </div>
      {ghost.targetNoteId && onSelectNote ? (
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            onSelectNote(ghost.targetNoteId!);
          }}
          className="text-xs text-info underline decoration-info/40 underline-offset-2 hover:text-term-text"
        >
          View targeted point
        </button>
      ) : null}
      {actions ? <div className="flex flex-wrap gap-2">{actions}</div> : null}
    </button>
  );
};
