Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

34.0 KB
Raw Blame
"use client";

import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";
import { getLanguageFromPath } from "../c4/panels/CodeViewer";
import { HighlightedCodeBlock } from "../shared/code-block";
import { FilePath, type FilePathMode } from "../shared/file-path";
import { PlaceholderHint } from "./placeholder-hint";
import { ProvenancePathList } from "../shared/provenance-path-list";
import {
  blastFiles,
  cutEdges,
  cycleMembers,
  extractClassGroups,
  extractHelperDetail,
  extractHelperOccurrences,
  extractHelperReuse,
  extractMethodPlan,
  extractMethodSignature,
  extractMethodStages,
  extractOrchestrator,
  extractParameterObject,
  helperSite,
  moveTarget,
  performancePlanDetail,
  slotLabel,
  splitBlast,
  splitGroups,
  splitResidual,
  splitShimRequired,
} from "./types";
import type { ExtractStage } from "./types";
import type { ExtractHelperReuse, RefactoringPlan } from "@repowise-dev/types/refactoring";

export interface PlanDetailProps {
  plan: RefactoringPlan;
  /** Render a file path as a link (e.g. to the file's health drawer). */
  fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
  /** Drop the leading prose line — used when the plan is the "after" column of
   *  a before→after comparison, where the intro would be redundant. */
  hideIntro?: boolean;
}

function shortFile(path: string): string {
  const parts = path.split("/");
  return parts.length <= 2 ? path : `…/${parts.slice(-2).join("/")}`;
}

function FileRef({
  path,
  line,
  fileHref,
  label,
  mode = "name-first",
  className = "",
}: {
  path: string;
  line?: number | null;
  fileHref?: PlanDetailProps["fileHref"];
  /** A symbol to print instead of the path, which then rides on `title`. */
  label?: string;
  mode?: FilePathMode;
  /** Extra classes, e.g. `flex` to let a name-first path clip in its column. */
  className?: string;
}) {
  const inner = label ? (
    <>
      {label}
      {line ? <span className="text-[var(--color-text-tertiary)]">:{line}</span> : null}
    </>
  ) : (
    <FilePath path={path} line={line} mode={mode} />
  );
  const base = `min-w-0 font-mono text-xs text-[var(--color-text-secondary)] ${className}`;
  const title = label ? path : undefined;
  const href = fileHref?.(path, line ?? null);
  if (!href) {
    return (
      <span className={base} title={title}>
        {inner}
      </span>
    );
  }
  return (
    <a
      href={href}
      className={`${base} underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline`}
      title={title}
    >
      {inner}
    </a>
  );
}

/** A read-only source block with a line-number gutter. Scrolls horizontally on
 *  its own so a long line never widens the page. The gutter counts up from
 *  `startLine` so the numbers match the file the block came from. */
export function CodeBlock({ code, startLine }: { code: string; startLine: number | null }) {
  const lines = code.split("\n");
  const base = startLine ?? 1;
  const gutterWidth = `${String(base + lines.length - 1).length}ch`;
  return (
    <div className="overflow-x-auto rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
      <pre className="py-2 text-2xs leading-relaxed">
        <code className="block font-mono">
          {lines.map((ln, i) => (
            <div key={i} className="flex px-3">
              <span
                className="mr-3 shrink-0 select-none text-right tabular-nums text-[var(--color-text-tertiary)]"
                style={{ minWidth: gutterWidth }}
                aria-hidden
              >
                {base + i}
              </span>
              <span className="whitespace-pre text-[var(--color-text-secondary)]">{ln || " "}</span>
            </div>
          ))}
        </code>
      </pre>
    </div>
  );
}

/** A staged Extract Method plan: the shared object once, then each helper the
 *  function will call, in order. Each stage folds to one line; the first is
 *  open. Every text has the code block's own copy button. */
function StagedExtract({
  plan,
  fileHref,
  hideIntro,
  stages,
}: {
  plan: RefactoringPlan;
  fileHref: PlanDetailProps["fileHref"];
  hideIntro: boolean;
  stages: ExtractStage[];
}) {
  const language = getLanguageFromPath(plan.file_path);
  const shared = extractParameterObject(plan);
  const ccn = extractOrchestrator(plan);
  return (
    <div className="space-y-3">
      {hideIntro ? null : (
        <p className="text-xs text-[var(--color-text-tertiary)]">
          Split <span className="font-mono">{plan.target_symbol}</span> into {stages.length} helpers
          it calls in order
          {ccn ? `, taking its complexity from ${ccn.before} to about ${ccn.after}` : ""}.
        </p>
      )}
      {shared ? (
        <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
          {shared.declaration_text ? (
            <HighlightedCodeBlock
              code={shared.declaration_text}
              language={language}
              label={`Shared values: ${shared.name}`}
              compact
              className="my-0"
            />
          ) : null}
          <HighlightedCodeBlock
            code={shared.construct_text}
            language={language}
            label={shared.construct_before ? `Build it above line ${shared.construct_before}` : "Build it"}
            compact
            className="mb-0 mt-2"
          />
        </div>
      ) : null}
      <ol className="space-y-2">
        {stages.map((stage, i) => (
          <li
            key={stage.span.start}
            className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5"
          >
            <details open={i === 0} className="group">
              {/* Wraps: in the drawer's half-width column a one-line summary
                  clipped the line range and CCN off the right edge. */}
              <summary className="flex cursor-pointer flex-wrap items-center gap-x-2 gap-y-1 text-xs">
                <Scissors className="h-4 w-4 shrink-0" style={{ color: ACCENT }} aria-hidden />
                <span className="whitespace-nowrap font-mono text-[var(--color-text-primary)]">
                  {stage.name ?? `Stage ${i + 1}`}
                </span>
                <FileRef
                  path={plan.file_path}
                  line={stage.span.start}
                  fileHref={fileHref}
                  mode="full"
                />
                <span className="ml-auto whitespace-nowrap font-mono text-[var(--color-text-secondary)]">
                  lines {stage.span.start}–{stage.span.end}
                  {stage.ccn ? ` · CCN ${stage.ccn}` : ""}
                </span>
              </summary>
              <div className="mt-2">
                {stage.signature_text ? (
                  <HighlightedCodeBlock
                    code={stage.signature_text}
                    language={language}
                    label="New helper"
                    compact
                    className="my-0"
                  />
                ) : null}
                {stage.return_text ? (
                  <HighlightedCodeBlock
                    code={stage.return_text}
                    language={language}
                    label="Ends with"
                    compact
                    className="mb-0 mt-2"
                  />
                ) : null}
                {stage.call_text ? (
                  <HighlightedCodeBlock
                    code={stage.call_text}
                    language={language}
                    label={`Replaces lines ${stage.span.start}–${stage.span.end}`}
                    compact
                    className="mb-0 mt-2"
                  />
                ) : null}
                <PlaceholderHint texts={[stage.signature_text ?? "", stage.call_text ?? ""]} />
                {stage.notes.map((note) => (
                  <p key={note} className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
                    {note}
                  </p>
                ))}
              </div>
            </details>
          </li>
        ))}
      </ol>
    </div>
  );
}

/**
 * The concrete, type-specific body of a refactoring plan: split groups as a
 * tree, the move as an arrow, clone occurrences as a list, the cycle as cut
 * edges. This is the "what exactly to do" — the heart of the surface.
 */
/** One accent for every type. See the note in `plan-before.tsx`. */
const ACCENT = "var(--color-accent-fill)";

/** Extract Helper when one site already is a function: name it, and say what
 *  each other site does (call it, or delete a copy of it). */
function ReuseDetail({
  reuse,
  fileHref,
  hideIntro,
}: {
  reuse: ExtractHelperReuse;
  fileHref: PlanDetailProps["fileHref"];
  hideIntro: boolean;
}) {
  const name = reuse.existing_symbol.split("::").pop() ?? reuse.existing_symbol;
  return (
    <div className="space-y-3">
      {hideIntro ? null : (
        <p className="text-xs text-[var(--color-text-tertiary)]">{reuse.reason}</p>
      )}
      <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
        <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
          Existing function
        </div>
        <FileRef
          path={reuse.file}
          line={reuse.span.start || null}
          fileHref={fileHref}
          label={`${name}()`}
          className="mt-1 block break-all font-semibold"
        />
      </div>
      <div className="space-y-1.5">
        <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
          Change at {reuse.sites.length} site{reuse.sites.length === 1 ? "" : "s"}
        </div>
        <ul className="divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
          {reuse.sites.map((s, i) => (
            <li key={i} className="space-y-1.5 px-3.5 py-2.5">
              <div className="flex items-center justify-between gap-3">
                <span className="min-w-0 flex-1">
                  <FileRef
                    path={s.file}
                    line={s.span.start || null}
                    fileHref={fileHref}
                    className="flex"
                  />
                </span>
                <span className="shrink-0 text-2xs tabular-nums text-[var(--color-text-tertiary)]">
                  {s.action === "delete" ? "Delete copy" : "Replace"}, lines {s.span.start}–
                  {s.span.end}
                </span>
              </div>
              {s.action === "delete" ? (
                <p className="text-2xs text-[var(--color-text-secondary)]">
                  Import <code>{name}</code> from <code>{reuse.file}</code> in its place.
                </p>
              ) : s.new_text ? (
                <code className="block whitespace-pre-wrap break-all rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]">
                  {s.new_text}
                </code>
              ) : null}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProps) {
  const accent = ACCENT;

  if (plan.refactoring_type === "performance_fix") {
    const detail = performancePlanDetail(plan);
    const provenance =
      typeof plan.evidence?.provenance === "string" ? plan.evidence.provenance : "unresolved";
    return (
      <div className="space-y-4">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            {detail.safety === "proven" ? "Proven" : "Advisory"}{" "}
            {detail.strategy.replaceAll("_", " ")} at the shared intervention.
          </p>
        )}
        <div className="border-y border-[var(--color-border-default)] py-3">
          <div className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
            Intervention point
          </div>
          <FileRef
            path={plan.file_path}
            line={plan.line_start ?? null}
            fileHref={fileHref}
            label={detail.interventionSymbol ?? plan.target_symbol}
            className="mt-1 block break-all text-xs font-semibold"
          />
        </div>
        <div>
          <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
            Caller-to-sink paths
          </div>
          <ProvenancePathList
            paths={detail.paths.map((nodes) => ({ nodes, provenance }))}
            total={detail.paths.length}
            fileHref={(path) => fileHref?.(path, null)}
          />
          {detail.truncated ? (
            <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
              {detail.paths.length} resolved {detail.paths.length === 1 ? "path" : "paths"} shown;
              additional observations remain in Code Health evidence.
            </p>
          ) : null}
        </div>
        <div>
          <div className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
            Affected targets
          </div>
          <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
            {detail.affectedLocations.map((location, index) => (
              <li key={`${location.file_path}:${location.line_start ?? index}`} className="py-2">
                <FileRef
                  path={location.file_path}
                  line={location.line_start ?? null}
                  fileHref={fileHref}
                  mode="full"
                />
              </li>
            ))}
          </ul>
          {detail.affectedLocations.length < detail.affectedLocationsTotal ? (
            <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
              {detail.affectedLocations.length} shown of {detail.affectedLocationsTotal} affected
              call sites.
            </p>
          ) : null}
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "extract_class") {
    const groups = extractClassGroups(plan).filter(
      (g) => g.methods.length > 0 || g.fields.length > 0,
    );
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            Split into {groups.length} cohesive group{groups.length === 1 ? "" : "s"} — each
            group's methods travel with the fields they touch.
          </p>
        )}
        <div className="grid gap-2.5 sm:grid-cols-2">
          {groups.map((g, i) => (
            <div
              key={i}
              className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5"
            >
              <div className="mb-2 flex items-center gap-2">
                <span
                  className="h-2 w-2 rounded-full"
                  style={{ backgroundColor: accent }}
                  aria-hidden
                />
                <span className="text-xs font-semibold text-[var(--color-text-primary)]">
                  {g.name ?? `Group ${i + 1}`}
                </span>
              </div>
              {g.fields.length > 0 ? (
                <div className="mb-1.5">
                  <span className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
                    Fields
                  </span>
                  <div className="mt-1 flex flex-wrap gap-1">
                    {g.fields.map((f) => (
                      <code
                        key={f}
                        className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]"
                      >
                        {f}
                      </code>
                    ))}
                  </div>
                </div>
              ) : null}
              <div>
                <span className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
                  Methods
                </span>
                <ul className="mt-1 space-y-0.5">
                  {g.methods.map((m) => (
                    <li
                      key={m}
                      className="flex items-center gap-1.5 font-mono text-2xs text-[var(--color-text-secondary)]"
                    >
                      <CornerDownRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />
                      {m}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "extract_helper") {
    const reuse = extractHelperReuse(plan);
    if (reuse) return <ReuseDetail reuse={reuse} fileHref={fileHref} hideIntro={hideIntro} />;
    const occ = extractHelperOccurrences(plan);
    const site = helperSite(plan);
    const detail = extractHelperDetail(plan);
    const dupLines = Number(plan.evidence?.duplicated_lines ?? 0);
    const helperName = detail.suggestedName ?? "helper";
    const call = `${helperName}()`;
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            The same {dupLines ? `${dupLines}-line ` : ""}block appears in {occ.length} place
            {occ.length === 1 ? "" : "s"}. Extract it once into{" "}
            <code className="rounded bg-[var(--color-bg-elevated)] px-1 py-0.5 text-2xs text-[var(--color-text-primary)]">
              {call}
            </code>
            {site ? (
              <>
                {" "}
                near{" "}
                <code className="rounded bg-[var(--color-bg-elevated)] px-1 py-0.5 text-2xs text-[var(--color-text-secondary)]">
                  {site}
                </code>
              </>
            ) : null}
            .
          </p>
        )}

        {/* Collapse at a glance: N duplicate copies → 1 shared helper. */}
        <div className="flex items-center gap-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
          <div className="min-w-0 flex-1">
            <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              Today
            </div>
            <div className="text-xs font-semibold text-[var(--color-text-primary)]">
              {occ.length} duplicate cop{occ.length === 1 ? "y" : "ies"}
            </div>
          </div>
          <ArrowRight className="h-4 w-4 shrink-0" style={{ color: accent }} aria-hidden />
          <div className="min-w-0 flex-1 text-right">
            <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              After
            </div>
            <code className="text-xs font-semibold text-[var(--color-text-primary)]">{call}</code>
          </div>
        </div>

        {/* The duplicated block itself, shown once (identical across sites). */}
        {detail.snippet ? (
          <div className="space-y-1.5">
            <div className="flex items-center gap-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              <Scissors className="h-3.5 w-3.5" style={{ color: accent }} aria-hidden />
              The duplicated block
              {detail.snippetTruncated ? (
                <span className="normal-case tracking-normal text-[var(--color-text-tertiary)]">
                  (first lines shown)
                </span>
              ) : null}
            </div>
            <CodeBlock code={detail.snippet} startLine={detail.snippetStartLine} />
          </div>
        ) : null}

        {/* Every site, as a jump link, with the call that replaces it. */}
        <div className="space-y-1.5">
          <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
            Replace at {occ.length} site{occ.length === 1 ? "" : "s"}
          </div>
          <ul className="divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
            {occ.map((o, i) => (
              <li key={i} className="flex items-center justify-between gap-3 px-3.5 py-2.5">
                <span className="min-w-0 flex-1">
                  <FileRef
                    path={o.file}
                    line={o.line_start}
                    fileHref={fileHref}
                    className="flex"
                  />
                </span>
                <span className="flex shrink-0 items-center gap-2">
                  <span className="text-2xs tabular-nums text-[var(--color-text-tertiary)]">
                    lines {o.line_start}–{o.line_end}
                  </span>
                  <ArrowRight
                    className="h-3 w-3 text-[var(--color-text-tertiary)]"
                    aria-hidden
                  />
                  <code className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]">
                    {call}
                  </code>
                </span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "move_method") {
    const mv = moveTarget(plan);
    if (!mv) return null;
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            This method leans on another class's data more than its own — move it home.
          </p>
        )}
        <div className="flex flex-wrap items-center gap-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
          <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">
            <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              From
            </div>
            <code className="text-xs text-[var(--color-text-secondary)]">{mv.from_class}</code>
          </div>
          <div className="flex flex-col items-center text-[var(--color-text-tertiary)]">
            <code className="mb-0.5 text-2xs text-[var(--color-text-primary)]">{mv.method}</code>
            <ArrowRight className="h-4 w-4" style={{ color: accent }} />
          </div>
          <div
            className="rounded-lg border px-3 py-2"
            style={{
              borderColor: accent,
              backgroundColor: `color-mix(in srgb, ${accent} 8%, transparent)`,
            }}
          >
            <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              To
            </div>
            <code className="text-xs text-[var(--color-text-primary)]">{mv.to_class}</code>
            {mv.to_file ? (
              <div className="mt-0.5">
                <FileRef path={mv.to_file} fileHref={fileHref} />
              </div>
            ) : null}
          </div>
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "break_cycle") {
    const members = cycleMembers(plan);
    const edges = cutEdges(plan);
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            {members.length} files import each other in a cycle. Cut {edges.length} edge
            {edges.length === 1 ? "" : "s"} to break it.
          </p>
        )}
        <div className="space-y-2 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
          <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
            Cut these import edges
          </div>
          {edges.map((e, i) => (
            <div key={i} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
              <Scissors className="h-3.5 w-3.5 shrink-0" style={{ color: accent }} />
              <FileRef path={e.from} fileHref={fileHref} className="flex" />
              <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
              <FileRef path={e.to} fileHref={fileHref} className="flex" />
            </div>
          ))}
          {members.length > 0 ? (
            <div className="break-words pt-1 text-2xs leading-relaxed text-[var(--color-text-tertiary)]">
              Cycle: {members.map(shortFile).join(" → ")}
            </div>
          ) : null}
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "extract_method") {
    const stages = extractMethodStages(plan);
    // Two or more valid stages, as Fix first counts them; else the single span.
    if (stages.length >= 2) {
      return <StagedExtract plan={plan} fileHref={fileHref} hideIntro={hideIntro} stages={stages} />;
    }
    const em = extractMethodPlan(plan);
    const lines = em.span ? em.span.end - em.span.start + 1 : 0;
    const ccn = Number(plan.evidence?.ccn_removed ?? 0);
    const sig = extractMethodSignature(em);
    // The one extension-to-language map in the UI lives in the code viewer.
    const codeLanguage = getLanguageFromPath(plan.file_path);
    // Typed where the plan has them; a method's receiver is not a parameter.
    const inLabels = em.typed_params.length ? em.typed_params.map(slotLabel) : em.params;
    const outLabels = em.typed_returns.length ? em.typed_returns.map(slotLabel) : em.returns;
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            Lift {lines} line{lines === 1 ? "" : "s"} out of{" "}
            <span className="font-mono">{plan.target_symbol}</span> into a focused{" "}
            {em.needs_async ? "async helper whose call is awaited" : "helper"}
            {ccn ? `, shedding ${ccn} decision point${ccn === 1 ? "" : "s"}` : ""}.
          </p>
        )}

        {em.span ? (
          <div className="flex items-center gap-2 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
            <Scissors className="h-4 w-4 shrink-0" style={{ color: accent }} aria-hidden />
            <div className="min-w-0">
              <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
                Extract span
              </div>
              <FileRef
                path={plan.file_path}
                line={em.span.start}
                fileHref={fileHref}
                className="flex"
              />
            </div>
            <span className="ml-auto shrink-0 font-mono text-xs text-[var(--color-text-secondary)]">
              lines {em.span.start}–{em.span.end}
            </span>
          </div>
        ) : null}

        <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
          {em.signature_text ? (
            <>
              <HighlightedCodeBlock
                code={em.signature_text}
                language={codeLanguage}
                label="New helper"
                compact
                className="my-0"
              />
              {em.call_site ? (
                <HighlightedCodeBlock
                  code={em.call_site.new_text}
                  language={codeLanguage}
                  label={`Replaces lines ${em.call_site.replace_span.start}–${em.call_site.replace_span.end}`}
                  compact
                  className="mb-0 mt-2"
                />
              ) : null}
              <PlaceholderHint texts={[em.signature_text, em.call_site?.new_text ?? ""]} />
              {em.notes.map((note) => (
                <p key={note} className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
                  {note}
                </p>
              ))}
            </>
          ) : (
            <>
              <div className="mb-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
                Inferred signature
              </div>
              <code className="block break-all font-mono text-xs text-[var(--color-text-primary)]">
                {sig}
              </code>
            </>
          )}
          <div className="mt-2 flex flex-wrap gap-3 text-2xs text-[var(--color-text-tertiary)]">
            <span>
              In (params):{" "}
              <span className="text-[var(--color-text-secondary)]">
                {inLabels.length ? inLabels.join(", ") : "none"}
              </span>
            </span>
            <span>
              Out (return):{" "}
              <span className="text-[var(--color-text-secondary)]">
                {outLabels.length ? outLabels.join(", ") : "none"}
              </span>
            </span>
          </div>
          {em.async_host === false ? (
            <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
              Judgment call: the span awaits, but the function holding it is not declared
              async, so an async helper cannot be written in its place.
            </p>
          ) : null}
          {em.receiver_hazard ? (
            <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
              {em.receiver_hazard === "receiver_unbound"
                ? "Judgment call: the span uses this outside a class, so no helper method can share it."
                : "Judgment call: the span writes fields of a value receiver (a copy), so a helper with its own copy would lose those writes."}
            </p>
          ) : null}
        </div>
      </div>
    );
  }

  if (plan.refactoring_type === "split_file") {
    const groups = splitGroups(plan);
    const residual = splitResidual(plan);
    const shim = splitShimRequired(plan);
    const blast = splitBlast(plan);
    const originalName = plan.file_path.split("/").pop() ?? plan.file_path;
    const shownDeps = blast.dependent_files.slice(0, 8);
    return (
      <div className="space-y-3">
        {hideIntro ? null : (
          <p className="text-xs text-[var(--color-text-tertiary)]">
            Split into {groups.length} cohesive module{groups.length === 1 ? "" : "s"} — each
            group's symbols move to a new file
            {shim ? ", with a back-compat shim left in the original path" : ""}.
          </p>
        )}
        <div className="grid gap-2.5 sm:grid-cols-2">
          {groups.map((g, i) => (
            <div
              key={i}
              className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5"
            >
              <div className="mb-1 flex items-center gap-2">
                <span
                  className="h-2 w-2 rounded-full"
                  style={{ backgroundColor: accent }}
                  aria-hidden
                />
                <span className="text-xs font-semibold text-[var(--color-text-primary)]">
                  {g.name ?? `Group ${i + 1}`}
                </span>
              </div>
              {g.suggested_file ? (
                <div className="mb-2 flex items-center gap-1.5">
                  <FilePlus2 className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
                  <FileRef path={g.suggested_file} fileHref={fileHref} className="flex" />
                </div>
              ) : null}
              <ul className="space-y-0.5">
                {g.symbols.map((s) => (
                  <li
                    key={s}
                    className="flex items-center gap-1.5 font-mono text-2xs text-[var(--color-text-secondary)]"
                  >
                    <CornerDownRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
                    <span className="truncate">{s}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        {residual.length > 0 ? (
          <div className="rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
            <div className="mb-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              Stays in {originalName} (shared core)
            </div>
            <div className="flex flex-wrap gap-1">
              {residual.map((s) => (
                <code
                  key={s}
                  className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]"
                >
                  {s}
                </code>
              ))}
            </div>
          </div>
        ) : null}

        {blast.dependent_count > 0 ? (
          <div className="space-y-1.5 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
            <div className="flex items-center gap-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
              <Layers className="h-3.5 w-3.5" />
              {blast.import_rewrites > 0
                ? `Rewrite imports in ${blast.import_rewrites} dependent file${
                    blast.import_rewrites === 1 ? "" : "s"
                  }`
                : `${blast.dependent_count} dependent${
                    blast.dependent_count === 1 ? "" : "s"
                  } · same-package split, no import edits`}
            </div>
            {blast.import_rewrites > 0 ? (
              <ul className="space-y-1">
                {shownDeps.map((f) => (
                  <li key={f}>
                    <FileRef path={f} fileHref={fileHref} className="flex" />
                  </li>
                ))}
                {blast.dependent_files.length > shownDeps.length ? (
                  <li className="text-2xs text-[var(--color-text-tertiary)]">
                    +{blast.dependent_files.length - shownDeps.length} more
                  </li>
                ) : null}
              </ul>
            ) : null}
          </div>
        ) : null}
      </div>
    );
  }

  // Unknown type — show the raw blast files as a minimal fallback.
  const files = blastFiles(plan);
  return files.length ? (
    <ul className="space-y-1">
      {files.map((f) => (
        <li key={f}>
          <FileRef path={f} fileHref={fileHref} />
        </li>
      ))}
    </ul>
  ) : null;
}