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.

31.4 KB
Raw Blame
"use client";

/**
 * The opportunity inspector, as a right-hand drawer.
 *
 * The single-plan drawer next door still exists and is still the right surface
 * for one step, which is what a deep link from the performance queue and the
 * VS Code webview both carry. This one is the composed unit: a file's whole
 * refactoring, its steps in dependency-safe order, and the evidence they rest
 * on.
 *
 * Three things it says that a list of plans could not:
 *
 * - **Order matters, and one kind of step invalidates the next.** A step
 *   carrying `relocated_by` names an earlier step that moves its symbol to
 *   another file, so its own file and span describe where the symbol *was*.
 *   That is stated once at the top of the list and again on each affected step,
 *   because a reader who scrolls straight to step four would otherwise follow a
 *   line number into the wrong file.
 * - **Mechanical is not a synonym for safe-to-automate-later.** Each step says
 *   which it is and why, and names what the layer could not establish rather
 *   than leaving an unknown looking like a cleared check.
 * - **Evidence is not instruction.** Demoted clone groups and triggering
 *   findings sit under their own heading, worded as observations.
 */

import * as React from "react";
import { Layers, Terminal } from "lucide-react";
import { AiPromptButton } from "../health/ai-prompt-button";

import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
import { Skeleton, SkeletonRegion } from "../ui/skeleton";
import { CollapsibleSection } from "../shared/collapsible-section";
import { disambiguateBasenames, formatNumber } from "../lib/format";
import { FilePath } from "../shared/file-path";
import { ValidationSummary } from "./validation-summary";
import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
import { CodeBlock } from "./plan-detail";
import { SourceExcerpt } from "./source-excerpt";
import { RelatedWork, type RelatedWorkSlotProps } from "../health/related-work";
import { PreviewBadge } from "../health/preview-badge";
import { GenerateCodePanel } from "./generate-code-panel";
import {
  RefactoringModelToggle,
  type RefactoringModelToggleProps,
} from "./refactoring-settings-card";
import { extractHelperDetail, extractMethodSignature, formatSpans, stepExcerptRange } from "./types";
import {
  ORDERING_NOTE,
  STATUS_LABEL,
  TRIAGE_STATUSES,
  addressesPrimaryLabel,
  humanizeBiomarker,
  isRelocated,
} from "./opportunity";
import type {
  GeneratedCode,
  OpportunityStatus,
  OpportunityStep,
  RefactoringOpportunityDetail,
  RefactoringOpportunityDetailResolved,
  RefactoringPlan,
} from "@repowise-dev/types/refactoring";


/** The drill-down an agent should call. Same shape the performance drawer uses,
 *  because it is the same agent surface. */
export function opportunityHandoffCall(opportunityId: string): string {
  return `get_health(opportunity_id="${opportunityId}")`;
}

export interface OpportunityDrawerProps extends RelatedWorkSlotProps {
  detail: RefactoringOpportunityDetail | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  loading?: boolean | undefined;
  error?: string | undefined;
  onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;
  onStatusChange?:
    | ((
        detail: RefactoringOpportunityDetailResolved,
        status: OpportunityStatus,
      ) => Promise<void> | void)
    | undefined;
  /** Open one step as a single plan, in the plan inspector. */
  onOpenStep?: ((planId: string) => void) | undefined;
  fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
  /**
   * The file's text, for a step's inline excerpt. The same read the file view
   * makes; omit it and a step shows only what its stored plan carries.
   */
  readSource?: ((path: string) => Promise<string>) | undefined;
  /** Opt-in model drafting of one step's diff. Omit when generation is off. */
  onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
  /** Offer the model switch inside steps when code generation is off. */
  modelSetting?: RefactoringModelToggleProps | undefined;
}

export function OpportunityDrawer({
  detail,
  open,
  onOpenChange,
  loading = false,
  error,
  onAiPrompt,
  onStatusChange,
  onOpenStep,
  fileHref,
  readSource,
  onGenerateCode,
  modelSetting,
  related,
  relatedWorkHref,
  onNavigate,
}: OpportunityDrawerProps) {
  const resolved = detail?.found ? detail : null;
  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        closeLabel="Close refactoring plan"
        className="w-full max-w-[680px] sm:w-[92vw]"
      >
        {resolved ? (
          <DrawerBody
            detail={resolved}
            onAiPrompt={onAiPrompt}
            onStatusChange={onStatusChange}
            onOpenStep={onOpenStep}
            fileHref={fileHref}
            readSource={readSource}
            onGenerateCode={onGenerateCode}
            modelSetting={modelSetting}
            related={related}
            relatedWorkHref={relatedWorkHref}
            onNavigate={onNavigate}
          />
        ) : loading ? (
          <>
            <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-sm">
              Loading refactoring plan
            </SheetTitle>
            <SkeletonRegion className="space-y-4 px-5 py-5" label="Loading refactoring plan">
              <Skeleton className="h-16 rounded-none" />
              <Skeleton className="h-40 rounded-none" />
            </SkeletonRegion>
          </>
        ) : detail && !detail.found ? (
          <>
            <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-sm">
              Refactoring plan unavailable
            </SheetTitle>
            <div className="space-y-2 px-5 py-5 text-sm text-[var(--color-text-secondary)]">
              <p>
                Nothing resolves for{" "}
                <span className="break-all font-mono text-xs">{detail.opportunity_id}</span>.
              </p>
              {detail.model_state?.state === "stale_model" ? (
                <p>
                  It was written by an older analysis model. Re-index the repository and open it
                  again from the list.
                </p>
              ) : (
                <p>It may have been resolved by a later analysis, or it was never minted here.</p>
              )}
            </div>
          </>
        ) : error ? (
          <>
            <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-sm">
              Refactoring plan unavailable
            </SheetTitle>
            <p className="px-5 py-5 text-sm text-[var(--color-text-secondary)]">{error}</p>
          </>
        ) : (
          <SheetTitle className="sr-only">Refactoring plan</SheetTitle>
        )}
      </SheetContent>
    </Sheet>
  );
}

function DrawerBody({
  detail,
  onAiPrompt,
  onStatusChange,
  onOpenStep,
  fileHref,
  readSource,
  onGenerateCode,
  modelSetting,
  related,
  relatedWorkHref,
  onNavigate,
}: {
  detail: RefactoringOpportunityDetailResolved;
  onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;
  onStatusChange?:
    | ((
        detail: RefactoringOpportunityDetailResolved,
        status: OpportunityStatus,
      ) => Promise<void> | void)
    | undefined;
  onOpenStep?: ((planId: string) => void) | undefined;
  fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
  readSource?: ((path: string) => Promise<string>) | undefined;
  onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
  modelSetting?: RefactoringModelToggleProps | undefined;
} & RelatedWorkSlotProps) {
  const meta = typeMeta(detail.lead_refactoring_type || "");
  const plansById = React.useMemo(
    () => new Map(detail.plans.map((plan) => [plan.id, plan])),
    [detail.plans],
  );
  const name = detail.file_path.split("/").pop() ?? detail.file_path;
  const others = detail.affected_files.filter((f) => f !== detail.file_path);
  const otherLabels = React.useMemo(
    () => disambiguateBasenames(detail.affected_files),
    [detail.affected_files],
  );
  // The opportunity resolved but its steps did not load. Everything else in the
  // drawer, triage included, still describes a real opportunity.
  const stepsUnavailable = detail.details_status === "unavailable";
  const anyRelocated = detail.steps.some(isRelocated);
  const guarding = guardingTestCount(detail.validation_profiles);
  const guardingTests = guarding.count;

  const [pending, setPending] = React.useState<OpportunityStatus | null>(null);
  const [failed, setFailed] = React.useState(false);
  const status = pending ?? detail.status;

  React.useEffect(() => {
    setPending(null);
  }, [detail.status]);

  const setStatus = React.useCallback(
    async (next: OpportunityStatus) => {
      if (!onStatusChange) return;
      setPending(next);
      setFailed(false);
      try {
        await onStatusChange(detail, next);
      } catch {
        setPending(null);
        setFailed(true);
      }
    },
    [onStatusChange, detail],
  );

  const facts: string[] = [
    `${EFFORT_LABEL[detail.effort_bucket]} effort`,
    `${CONFIDENCE_LABEL[detail.confidence]} confidence`,
    `${detail.step_count} step${detail.step_count === 1 ? "" : "s"}, ${detail.mechanical_steps} mechanical`,
  ];
  if (detail.affected_files_total > 1) {
    facts.push(`${formatNumber(detail.affected_files_total)} files affected`);
  }

  return (
    <>
      <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">
        <div className="text-xs text-[var(--color-text-secondary)]">
          {meta.label}
          {detail.lead_biomarker ? ` · against ${humanizeBiomarker(detail.lead_biomarker)}` : ""}
          {detail.preview ? (
            <span className="ml-2">
              <PreviewBadge note={detail.preview} />
            </span>
          ) : null}
        </div>
        <SheetTitle className="mt-0.5 break-words font-mono text-sm font-semibold text-[var(--color-text-primary)]">
          {name}
        </SheetTitle>
        <FilePath
          path={detail.file_path}
          mode="full"
          copyable
          className="mt-1 block text-[var(--color-text-tertiary)]"
        />
      </div>

      <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-[var(--color-border-default)] px-5 py-2.5 text-xs text-[var(--color-text-secondary)]">
        {facts.map((f) => (
          <span key={f}>{f}</span>
        ))}
        {detail.recoverable_health > 0 ? (
          <span className="font-medium tabular-nums text-[var(--color-success)]">
            +{detail.recoverable_health.toFixed(1)} health
          </span>
        ) : (
          <span className="text-[var(--color-text-tertiary)]">No score change</span>
        )}
      </div>

      <p className="border-b border-[var(--color-border-default)] px-5 py-2 text-xs text-[var(--color-text-secondary)]">
        {blastRadiusLine(detail)}{" "}
        {guardingTests > 0
          ? `${guarding.atLeast ? "At least " : ""}${formatNumber(guardingTests)} guarding test${guardingTests === 1 ? "" : "s"} reach it.`
          : "No guarding tests found."}
      </p>

      <div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">
        {/* Tri-state, stated in words. `null` is its own sentence: the layer had
            no dominant finding to compare against, which is not the same claim
            as "these steps address something else". */}
        <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">
          {addressesPrimaryLabel(detail.addresses_primary_problem)}.{" "}
          {detail.addresses_primary_problem === false
            ? "The steps below are still real work; they are just not what is costing this file the most."
            : meta.blurb}
        </p>

        {onStatusChange ? (
          <section>
            <h4 className="mb-2 font-mono text-caption uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
              Triage
            </h4>
            <div role="radiogroup" aria-label="Triage this refactoring plan" className="flex flex-wrap gap-1.5">
              {TRIAGE_STATUSES.map((option) => {
                const current = option.value === status;
                return (
                  <button
                    key={option.value}
                    type="button"
                    role="radio"
                    aria-checked={current}
                    disabled={current}
                    onClick={() => void setStatus(option.value)}
                    className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
                      current
                        ? "bg-[var(--color-bg-selected)] text-[var(--color-text-primary)] shadow-[inset_0_-2px_0_var(--color-tab-active)]"
                        : "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
                    }`}
                  >
                    {option.label}
                  </button>
                );
              })}
            </div>
            <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">
              Applies to all {detail.step_count} step{detail.step_count === 1 ? "" : "s"}.{" "}
              {status === "false_positive"
                ? "A false positive is suppressed on every later analysis."
                : "Currently " + STATUS_LABEL[status].toLowerCase() + "."}
            </p>
            <p
              role="status"
              className={
                failed ? "mt-1 text-xs text-[var(--color-error)]" : "sr-only"
              }
            >
              {failed ? "Could not save that. The refactoring plan is unchanged." : ""}
            </p>
          </section>
        ) : null}

        <section>
          <h4 className="mb-1 font-mono text-caption uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
            The steps, in order
          </h4>
          {anyRelocated ? (
            <p className="mb-3 rounded-md border border-[var(--color-caution)]/40 bg-[var(--color-caution)]/10 px-3 py-2 text-xs text-[var(--color-text-secondary)]">
              {detail.ordering_note ?? ORDERING_NOTE}
            </p>
          ) : null}
          {stepsUnavailable ? (
            <p className="text-xs text-[var(--color-text-secondary)]">
              The {detail.step_count} step{detail.step_count === 1 ? "" : "s"} for this refactoring
              plan could not be loaded. Try again shortly, or ask for it by id below.
            </p>
          ) : null}
          <ol className="space-y-3">
            {detail.steps.map((step, i) => (
              <StepCard
                key={step.plan_id}
                step={step}
                index={i}
                plan={plansById.get(step.plan_id)}
                onOpenStep={onOpenStep}
                fileHref={fileHref}
                readSource={readSource}
                onGenerateCode={onGenerateCode}
                modelSetting={modelSetting}
              />
            ))}
          </ol>
          {detail.steps_total != null && detail.steps_emitted < detail.steps_total ? (
            <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
              Showing {detail.steps_emitted} of {detail.steps_total} steps.
            </p>
          ) : null}
        </section>

        {/* Detail below the steps is collapsed: the line under the facts already
            says whether tests guard the file, which is what a person decides on. */}
        <CollapsibleSection
          title="Verify"
          hint={guardingTests > 0 ? `${formatNumber(guardingTests)} tests` : "none guarding"}
          defaultOpen={guardingTests === 0}
        >
          {detail.validation_profiles.length > 0 ? (
            <div className="space-y-4">
              {detail.validation_profiles.map((profile) => (
                <ValidationSummary
                  key={profile.id}
                  validation={profile}
                  fileHref={(path) => fileHref?.(path, null)}
                />
              ))}
            </div>
          ) : (
            <p className="text-xs text-[var(--color-text-secondary)]">
              No guarding tests found. Write one that pins the current behaviour before applying
              these steps.
            </p>
          )}
        </CollapsibleSection>

        <RelatedWork
          related={related?.file_path === detail.file_path ? related : null}
          relatedWorkHref={relatedWorkHref}
          onNavigate={onNavigate}
          exclude={["refactoring"]}
          headingLevel="h4"
        />

        {detail.evidence.length > 0 ? (
          <CollapsibleSection title="Evidence" hint={formatNumber(detail.evidence_total)}>
            {/* Named as observation, not instruction. These are mostly demoted
                clone groups: real duplication, not a change worth making on its
                own account. */}
            <p className="mb-2.5 text-xs text-[var(--color-text-secondary)]">
              Supporting observations on this file. They are why the diagnosis reads the way it
              does, not extra work to do.
            </p>
            <ul className="space-y-1.5">
              {detail.evidence.map((item) => (
                <li
                  key={item.plan_id}
                  className="border-t border-[var(--color-border-default)] pt-1.5 text-xs text-[var(--color-text-secondary)]"
                >
                  <span className="text-[var(--color-text-tertiary)]">
                    {typeMeta(item.refactoring_type).label}
                  </span>
                  {item.target_symbol ? (
                    <span className="ml-2 break-all font-mono text-xs text-[var(--color-text-primary)]">
                      {item.target_symbol}
                    </span>
                  ) : null}
                </li>
              ))}
            </ul>
            {detail.evidence_truncated ? (
              <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
                Showing {detail.evidence_emitted} of {detail.evidence_total} observations.
              </p>
            ) : null}
          </CollapsibleSection>
        ) : null}

        {others.length > 0 ? (
          <CollapsibleSection
            title={
              <span className="flex items-center gap-1.5">
                <Layers className="h-3.5 w-3.5" aria-hidden="true" />
                Also affected
              </span>
            }
            hint={formatNumber(others.length)}
          >
            <ul className="space-y-1">
              {others.map((f) => {
                const href = fileHref?.(f, null);
                return (
                  <li key={f}>
                    {href ? (
                      <a
                        href={href}
                        className="flex min-w-0 text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
                      >
                        <FilePath path={f} mode="distinguishing" labels={otherLabels} />
                      </a>
                    ) : (
                      <span className="flex min-w-0 text-[var(--color-text-secondary)]">
                        <FilePath path={f} mode="distinguishing" labels={otherLabels} />
                      </span>
                    )}
                  </li>
                );
              })}
            </ul>
          </CollapsibleSection>
        ) : null}

        <CollapsibleSection
          title={
            <span className="flex items-center gap-1.5">
              <Terminal className="h-3.5 w-3.5" aria-hidden="true" />
              Ask for this by id
            </span>
          }
        >
          <p className="text-xs text-[var(--color-text-secondary)]">
            Copy the prompt with the Claude + MCP flavor and it carries this call, so the agent
            can pull the same record itself rather than working from the pasted copy. The other
            flavors inline the whole plan instead, because they have no tool that resolves an id.
          </p>
          <p className="mt-1.5 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">
            {opportunityHandoffCall(detail.opportunity_id)}
          </p>
        </CollapsibleSection>
      </div>

      {/* The prompt carries the ordered steps; without them it would hand an
          agent an empty plan. */}
      {onAiPrompt && !stepsUnavailable ? (
        <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">
          <AiPromptButton onClick={() => onAiPrompt(detail)} />
          <span className="hidden text-xs text-[var(--color-text-tertiary)] sm:block">
            The ordered steps, the evidence, and the id to query it back.
          </span>
        </div>
      ) : null}
    </>
  );
}

function StepCard({
  step,
  index,
  plan,
  onOpenStep,
  fileHref,
  readSource,
  onGenerateCode,
  modelSetting,
}: {
  step: OpportunityStep;
  index: number;
  /** The step's stored plan, when the detail carried it. */
  plan?: RefactoringPlan | undefined;
  onOpenStep?: ((planId: string) => void) | undefined;
  fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
  readSource?: ((path: string) => Promise<string>) | undefined;
  onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
  modelSetting?: RefactoringModelToggleProps | undefined;
}) {
  const meta = typeMeta(step.refactoring_type);
  const mechanical = step.applicability.classification === "mechanical";
  const href = fileHref?.(step.file_path, step.line_start);
  const span = step.line_start
    ? `${step.line_start}${step.line_end ? `–${step.line_end}` : ""}`
    : null;

  return (
    <li className="rounded-lg border border-[var(--color-border-default)] px-3.5 py-3">
      <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
        <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
          {String(index + 1).padStart(2, "0")}
        </span>
        <span className="text-xs text-[var(--color-text-secondary)]">{meta.label}</span>
        {/* Not a colour-only mark: the word is the signal, and the tint only
            reinforces it. */}
        <span
          className={`rounded px-1.5 py-0.5 text-xs font-medium ${
            mechanical
              ? "bg-[var(--color-success)]/12 text-[var(--color-success)]"
              : "bg-[var(--color-bg-inset)] text-[var(--color-text-secondary)]"
          }`}
        >
          {mechanical ? "Mechanical" : "Judgment"}
        </span>
        {isRelocated(step) ? (
          <span className="rounded bg-[var(--color-caution)]/15 px-1.5 py-0.5 text-xs font-medium text-[var(--color-caution)]">
            Moved by an earlier step
          </span>
        ) : null}
        <PreviewBadge note={plan?.preview} />
      </div>

      <button
        type="button"
        onClick={onOpenStep ? () => onOpenStep(step.plan_id) : undefined}
        disabled={!onOpenStep}
        className="mt-1 block break-all text-left font-mono text-sm font-medium text-[var(--color-text-primary)] enabled:hover:text-[var(--color-accent-primary)]"
      >
        {step.target_symbol || meta.label}
      </button>

      <p className="mt-0.5 text-[var(--color-text-tertiary)]">
        {href ? (
          <a href={href} className="underline-offset-2 hover:underline">
            <FilePath path={step.file_path} line={span || null} mode="full" />
          </a>
        ) : (
          <FilePath path={step.file_path} line={span || null} mode="full" />
        )}
      </p>

      {isRelocated(step) ? (
        <p className="mt-1.5 text-xs text-[var(--color-text-secondary)]">
          An earlier step moves this symbol out of that file, so the path and lines above say where
          it was. Find it again before applying this one.
        </p>
      ) : null}

      {step.applicability.reasons.length > 0 ? (
        <p className="mt-1.5 text-xs text-[var(--color-text-secondary)]">
          {step.applicability.reasons.map(humanizeBiomarker).join("; ")}.
        </p>
      ) : null}

      {step.applicability.unknowns.length > 0 ? (
        // An unknown is first-class. Leaving it out would let a check the layer
        // never ran read as a check that passed.
        <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
          Not established: {step.applicability.unknowns.map(humanizeBiomarker).join(", ")}.
        </p>
      ) : null}

      <StepCode
        step={step}
        plan={plan}
        readSource={readSource}
        onGenerateCode={onGenerateCode}
        modelSetting={modelSetting}
      />
    </li>
  );
}

/**
 * The code a step changes, and a diff of the change when one is asked for.
 *
 * Closed by default: a drawer of seven open excerpts would bury the order of
 * the steps, which is the drawer's subject. The excerpt prefers the text the
 * stored plan carries (an extract-helper block); otherwise it reads the file
 * the way the file view does and cuts out the lines the step changes. For an
 * extraction that is the slice, under the helper's proposed signature, not the
 * whole function the step's span covers.
 */
function StepCode({
  step,
  plan,
  readSource,
  onGenerateCode,
  modelSetting,
}: {
  step: OpportunityStep;
  plan?: RefactoringPlan | undefined;
  readSource?: ((path: string) => Promise<string>) | undefined;
  onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
  modelSetting?: RefactoringModelToggleProps | undefined;
}) {
  const [open, setOpen] = React.useState(false);
  const stored = plan ? extractHelperDetail(plan) : null;
  const range = stepExcerptRange(step, plan);
  const canRead = Boolean(readSource && range);
  // One read per file however many stage excerpts ask for it.
  const readOnce = React.useMemo(() => {
    if (!readSource) return undefined;
    const reads = new Map<string, Promise<string>>();
    return (path: string) => {
      if (!reads.has(path)) reads.set(path, readSource(path));
      return reads.get(path)!;
    };
  }, [readSource]);
  if (!stored?.snippet && !canRead && !plan) return null;
  return (
    <div className="mt-2">
      <button
        type="button"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        className="rounded text-xs font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]"
      >
        {open ? "Hide the code" : "Show the code"}
      </button>
      {open ? (
        <div className="mt-2 space-y-3">
          <StepSpans range={range} />
          <StepExcerpt
            step={step}
            stored={stored}
            range={canRead ? range : null}
            readSource={readOnce}
          />
          <StepDiff plan={plan} onGenerateCode={onGenerateCode} modelSetting={modelSetting} />
        </div>
      ) : null}
    </div>
  );
}

/** Which lines the step lifts out, and into what. */
function StepSpans({ range }: { range: ReturnType<typeof stepExcerptRange> }) {
  const extraction = range?.extraction ?? null;
  const slice = extraction?.span ?? null;
  const stages = range?.stages ?? [];
  return (
    <>
      {stages.length > 0 ? (
        <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
          Lines{" "}
          <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">
            {formatSpans(stages.map((st) => st.span))}
          </span>{" "}
          become {stages.length} helpers the function calls in order.
        </p>
      ) : null}
      {extraction && slice ? (
        <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
          Lines {slice.start} to {slice.end} become{" "}
          <code className="break-all font-mono text-[var(--color-text-primary)]">
            {extractMethodSignature(extraction)}
          </code>
        </p>
      ) : null}
    </>
  );
}

/**
 * The excerpt itself: the stored snippet when the plan carries one, else each
 * stage read on its own, else the step's one range. `range` is null when the
 * file cannot be read.
 */
function StepExcerpt({
  step,
  stored,
  range,
  readSource,
}: {
  step: OpportunityStep;
  stored: ReturnType<typeof extractHelperDetail> | null;
  range: ReturnType<typeof stepExcerptRange>;
  readSource: ((path: string) => Promise<string>) | undefined;
}) {
  if (stored?.snippet) {
    return <CodeBlock code={stored.snippet} startLine={stored.snippetStartLine} />;
  }
  if (!range) return null;
  if (range.stages.length > 0) {
    // Each stage on its own: one range from the first stage to the last
    // would show the lines between them and could cut a later stage.
    return range.stages.map((st, i) => (
      <div key={st.span.start} className="space-y-1">
        <p className="font-mono text-[11px] text-[var(--color-text-tertiary)]">
          {`${st.name ?? `Stage ${i + 1}`} · lines ${formatSpans([st.span])}`}
        </p>
        <SourceExcerpt
          path={step.file_path}
          start={st.span.start}
          end={st.span.end}
          readSource={readSource!}
        />
      </div>
    ));
  }
  return (
    <SourceExcerpt
      path={step.file_path}
      start={range.start}
      end={range.end}
      readSource={readSource!}
    />
  );
}

/** The diff preview, the model setting that turns it on, or why it is off. */
function StepDiff({
  plan,
  onGenerateCode,
  modelSetting,
}: {
  plan?: RefactoringPlan | undefined;
  onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
  modelSetting?: RefactoringModelToggleProps | undefined;
}) {
  if (!plan) return null;
  if (onGenerateCode) return <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />;
  if (modelSetting) return <RefactoringModelToggle {...modelSetting} />;
  return (
    <p className="text-xs text-[var(--color-text-tertiary)]">
      A diff preview is drafted by a model on request. Code generation is off here.
    </p>
  );
}

/**
 * Distinct guarding tests across an opportunity's validation profiles.
 *
 * Profiles are deduplicated by their whole content, so two steps with
 * different validations get two profiles that can name the same tests:
 * summing `total` would count those twice. A truncated profile lists only
 * some of its tests, so the count is then a floor, never less than any one
 * profile's total.
 */
export function guardingTestCount(
  profiles: ReadonlyArray<{ total: number; tests: string[]; truncated?: boolean | undefined }>,
): { count: number; atLeast: boolean } {
  const distinct = new Set(profiles.flatMap((profile) => profile.tests)).size;
  const largest = profiles.reduce((n, profile) => Math.max(n, profile.total), 0);
  const atLeast = profiles.length > 1 && profiles.some((p) => p.truncated || p.tests.length < p.total);
  return { count: Math.max(distinct, largest), atLeast };
}

/**
 * Who else the change reaches, in one line, for every type: the files the
 * steps edit, and the files that import the lead file when the store has it.
 */
export function blastRadiusLine(
  detail: Pick<RefactoringOpportunityDetailResolved, "affected_files_total" | "dependents">,
): string {
  const files = detail.affected_files_total;
  const touched = `Touches ${formatNumber(files)} file${files === 1 ? "" : "s"}`;
  if (detail.dependents == null) return `${touched}; importers not recorded.`;
  const deps = detail.dependents;
  return `${touched}; ${formatNumber(deps)} file${deps === 1 ? " imports" : "s import"} it.`;
}