"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import type { EntityTagReturnDto } from "@enode/core/api/dtos/tags";
import { useHasPrivilege } from "@enode/core/auth/use-privilege";
import { reportError } from "@enode/core/errors/report";
import { useExercises } from "@enode/core/exercises/hooks";
import { tagsFromUsers } from "@enode/core/tags/from-users";
import { useTagsVersion } from "@enode/core/tags/hooks";
import { withoutArchivedTags } from "@enode/core/tags/archive";
import { getTagsForEntityKind, loadTags } from "@enode/core/tags/store";
import { tagDotStyle } from "@enode/core/tags/tag-style";
import { displayName } from "@enode/core/text-content/display-name";
import { useTranslation } from "@enode/core/translations/hooks";
import type { UserReducedReturnDto } from "@enode/core/api/dtos/users";
import { StalenessHint } from "@enode/ui/feedback/staleness-hint";
import { SearchAndFilterCard } from "@enode/ui/search-and-filter-card";
import { useChartDemo, useChartTagOf } from "../../../../components/charts/chart-demo";
import {
  TagTheseAthletesButton,
  useTagTheseAthletes,
} from "../../../../components/selection/athlete-scope";
import { AthleteSelection } from "../../../../components/selection/athlete-selection";
import { ExerciseSelection } from "../../../../components/selection/exercise-selection";
import { exerciseLabelResolver } from "../../../../components/selection/exercise-labels";
import { tagMemberIDs } from "../../../../components/selection/tag-members";
import { liftActivity } from "./lift-activity";
import { MetricAxesSelection } from "./metric-selection";
import { hasScope, readRecentScope, type ScopeIDs } from "./recent-scope";
import { useChartTagTheseWording } from "./scope-selection";
import { TimeframePresets } from "./timeframe-field";
import type { Timeframe } from "./timeframe";
import type { MetricOption } from "./use-metric-options";
import { useLiftActivity } from "./use-lift-activity";

// The single-question screens of the guided path: whose sessions, which lifts,
// and (Profile) which metrics. Each writes the same ids the full builder does —
// fixed athlete ids and/or athlete tags, exercise definitions, display bases —
// so "Adjust everything" opens the builder with every choice in place.
//
// Inside the Insights demo (chart-demo.tsx) they offer only what the demo has:
// its squad, its tags and its lifts. The pickers of the whole roster and
// catalogue, "Same as last chart" and "Tag these athletes…" are left out there,
// as each would read or write the coach's own data.

// ─── Shared row ──────────────────────────────────────────────────────────────

/** One selectable answer: a radio or check mark, a title, a detail line and an optional trailing slot. */
export function ChoiceRow({
  active,
  multiple = false,
  title,
  detail,
  leading,
  trailing,
  dimmed = false,
  onClick,
}: {
  active: boolean;
  multiple?: boolean;
  title: ReactNode;
  detail?: ReactNode;
  leading?: ReactNode;
  trailing?: ReactNode;
  dimmed?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      role={multiple ? "checkbox" : "radio"}
      aria-checked={active}
      onClick={onClick}
      className={`flex w-full items-center gap-3 rounded-2xl border px-4 py-3 text-left transition-colors ${
        active
          ? "border-foreground-red-orange bg-foreground-red-orange/8"
          : "border-surface-stroke hover:bg-surface-base-muted"
      } ${dimmed && !active ? "opacity-60" : ""}`}
    >
      <span
        aria-hidden
        className={`flex size-5 shrink-0 items-center justify-center border-2 transition-colors ${
          multiple ? "rounded-md" : "rounded-full"
        } ${active ? "border-foreground-red-orange bg-foreground-red-orange" : "border-surface-stroke"}`}
      >
        {active ? <span className="size-2 rounded-full bg-surface-base" /> : null}
      </span>
      {leading}
      <span className="min-w-0 flex-1">
        <span className="body-prominent block text-foreground-default">{title}</span>
        {detail ? <span className="body-small block text-foreground-muted">{detail}</span> : null}
      </span>
      {trailing}
    </button>
  );
}

function sameSet(a: readonly string[], b: readonly string[]): boolean {
  if (a.length !== b.length) return false;
  const set = new Set(a);
  return b.every((id) => set.has(id));
}

function sameScope(a: ScopeIDs, b: ScopeIDs): boolean {
  return sameSet(a.ids, b.ids) && sameSet(a.tagIDs, b.tagIDs);
}

// ─── Whose sessions ──────────────────────────────────────────────────────────

/** How many tags the whose-sessions step shows before "Show all tags". */
const TOP_TAGS = 8;

type TagOption = { tag: EntityTagReturnDto; count: number };

/**
 * Every athlete tag the coach can pick — the tag catalogue's athlete tags plus
 * any tag the roster carries that the catalogue hasn't loaded — with its
 * member count today, biggest first, then by name. Tags nobody carries yet are
 * included (count 0): a chart on one fills in as athletes get the tag.
 */
export function athleteTagOptions(
  catalogue: readonly EntityTagReturnDto[],
  roster: readonly UserReducedReturnDto[],
): TagOption[] {
  const byID = new Map<string, EntityTagReturnDto>();
  for (const tag of [...catalogue, ...tagsFromUsers(roster)]) {
    if (tag.id && !byID.has(tag.id)) byID.set(tag.id, tag);
  }
  return [...byID.values()]
    .map((tag) => ({ tag, count: tagMemberIDs(roster, tag.id).length }))
    .sort(
      (a, b) =>
        b.count - a.count || displayName(a.tag).trim().localeCompare(displayName(b.tag).trim()),
    );
}

/**
 * One answer to "whose sessions?": the whole squad, one athlete tag (with its
 * size — the biggest first, every tag one tap away under "Show all tags", empty
 * ones included), the last chart's athletes, or athletes picked one by one. A
 * tag stays a tag, so athletes who get it later join the chart automatically;
 * combining fixed picks with tags is the full builder's job.
 */
export function WhoStep({
  prompt,
  value,
  onChange,
  roster,
  pickerTitle,
}: {
  prompt: string;
  value: ScopeIDs;
  onChange: (next: ScopeIDs) => void;
  /** The trainable, non-archived athletes the chart can cover. */
  roster: readonly UserReducedReturnDto[];
  pickerTitle: string;
}) {
  const { t } = useTranslation();
  const demo = useChartDemo();
  const tagOf = useChartTagOf();
  const rosterIDs = roster.map((user) => user.id);
  // The full athlete-tag catalogue (not only tags someone carries), kept fresh.
  // The demo's tags are the ones its squad carries.
  useTagsVersion();
  useEffect(() => {
    if (demo) return;
    loadTags().catch((err) => reportError(err, { context: "insights.guided.tags" }));
  }, [demo]);
  const groups = athleteTagOptions(
    demo ? [] : withoutArchivedTags(getTagsForEntityKind("user")),
    roster,
  );
  const [showAll, setShowAll] = useState(false);
  const [search, setSearch] = useState("");
  const canWriteTag = useHasPrivilege("writeEntityTag") && demo == null;
  const tagTheseWording = useChartTagTheseWording();
  const tagTheseAthletes = useTagTheseAthletes(tagTheseWording);
  const [recent] = useState(() => (demo ? null : (readRecentScope()?.athletes ?? null)));
  const rosterSet = new Set(rosterIDs);
  const recentPick: ScopeIDs | null = hasScope(recent)
    ? { ids: recent.ids.filter((id) => rosterSet.has(id)), tagIDs: recent.tagIDs }
    : null;

  const wholeSquad: ScopeIDs = { ids: rosterIDs, tagIDs: [] };
  const isWhole = rosterIDs.length > 0 && sameScope(value, wholeSquad);
  const isGroup = (tagID: string) => value.ids.length === 0 && sameSet(value.tagIDs, [tagID]);
  // Collapsed: the biggest groups with members, plus the picked one wherever
  // it ranks. Expanded: every athlete tag, filtered by the search.
  const top = groups.filter((group) => group.count > 0).slice(0, TOP_TAGS);
  const picked = groups.find((group) => isGroup(group.tag.id));
  const term = search.trim().toLowerCase();
  const shownGroups = showAll
    ? groups.filter((group) => !term || displayName(group.tag).toLowerCase().includes(term))
    : picked && !top.includes(picked)
      ? [...top, picked]
      : top;
  const hiddenCount = groups.length - top.length;
  const recentIsOwnRow =
    recentPick != null &&
    hasScope(recentPick) &&
    !sameScope(recentPick, wholeSquad) &&
    !groups.some(({ tag }) => sameScope(recentPick, { ids: [], tagIDs: [tag.id] }));
  const isRecent = recentIsOwnRow && sameScope(value, recentPick);
  const isOneByOne =
    hasScope(value) && !isWhole && !groups.some(({ tag }) => isGroup(tag.id)) && !isRecent;

  const nameOf = (id: string) => {
    const user = roster.find((u) => u.id === id);
    return user?.name ?? user?.email ?? "";
  };
  const recentLabel = recentPick
    ? [
        ...recentPick.tagIDs.map((id) => {
          const tag = groups.find((g) => g.tag.id === id)?.tag;
          return tag ? displayName(tag).trim() : "";
        }),
        ...recentPick.ids.map(nameOf),
      ]
        .filter((name) => name.length > 0)
        .slice(0, 3)
        .join(", ")
    : "";

  return (
    <div className="space-y-3" role="radiogroup" aria-label={prompt}>
      <p className="heading-normal text-foreground-default">{prompt}</p>

      <ChoiceRow
        active={isWhole}
        title={t("Whole squad")}
        detail={t("{count, plural, one {# athlete} other {# athletes}}", { count: rosterIDs.length })}
        onClick={() => onChange(wholeSquad)}
      />

      {groups.length > 0 ? (
        <p className="body-small pt-1 text-foreground-muted">{t("Your tags")}</p>
      ) : null}
      {showAll ? (
        <SearchAndFilterCard
          search={search}
          onSearch={setSearch}
          placeholder={t("Search tags…")}
        />
      ) : null}
      {showAll && shownGroups.length === 0 ? (
        <p className="body-small text-foreground-muted">{t("No tag matches.")}</p>
      ) : null}
      {shownGroups.map(({ tag, count }) => (
        <ChoiceRow
          key={tag.id}
          active={isGroup(tag.id)}
          leading={
            <span
              aria-hidden
              className="size-2.5 shrink-0 rounded-full"
              style={tagDotStyle(tag.colorCode)}
            />
          }
          title={displayName(tag).trim()}
          detail={
            count === 0
              ? t("No athletes yet · anyone who gets this tag joins automatically")
              : isGroup(tag.id)
                ? t("{count, plural, one {# athlete} other {# athletes}} · athletes who get the tag later join automatically", { count })
                : t("{count, plural, one {# athlete} other {# athletes}}", { count })
          }
          onClick={() => onChange({ ids: [], tagIDs: [tag.id] })}
        />
      ))}
      {hiddenCount > 0 ? (
        <button
          type="button"
          onClick={() => {
            setShowAll(!showAll);
            setSearch("");
          }}
          aria-expanded={showAll}
          className="body-small font-medium text-foreground-red-orange transition-opacity hover:opacity-80"
        >
          {showAll
            ? t("Show fewer tags")
            : t("Show all tags ({count})", { count: groups.length })}
        </button>
      ) : null}

      {recentIsOwnRow && recentPick ? (
        <ChoiceRow
          active={isRecent}
          title={t("Same as last chart")}
          detail={recentLabel}
          onClick={() => onChange(recentPick)}
        />
      ) : null}

      {/* The picker of the whole roster: not in the demo, whose squad is the
          answers above. */}
      {demo ? null : (
        <div
          className={`rounded-2xl border px-4 py-3 ${
            isOneByOne ? "border-foreground-red-orange" : "border-surface-stroke"
          }`}
        >
          <div className="mb-2 flex items-center gap-2">
            <p className="body-prominent min-w-0 flex-1 text-foreground-default">
              {t("Pick athletes one by one")}
            </p>
            {/* A hand-picked list never grows; tagging the picks on the spot
                turns it into a tag the chart follows. */}
            {canWriteTag && isOneByOne && value.ids.length > 0 ? (
              <TagTheseAthletesButton
                count={value.ids.length}
                onClick={() =>
                  tagTheseAthletes(value.ids, (tag) => onChange({ ids: [], tagIDs: [...value.tagIDs, tag.id] }))
                }
              />
            ) : null}
          </div>
          <AthleteSelection
            pickerTitle={pickerTitle}
            ids={isOneByOne ? value.ids : []}
            onChange={(ids) => onChange({ ids, tagIDs: [] })}
            emptyHint=""
            hideLabel
            onUseTag={(tagID, otherIDs) => onChange({ ids: otherIDs, tagIDs: [tagID] })}
          />
          {/* A group taken over from the picker ("use this tag") that isn't
              listed above would otherwise be selected but invisible. */}
          {isOneByOne && value.tagIDs.length > 0 ? (
            <p className="body-small mt-2 text-foreground-muted">
              {t("Includes everyone tagged {tags}. Athletes who get the tag later join automatically.", {
                tags: value.tagIDs
                  .map((id) => displayName(tagOf(id)).trim())
                  .filter((name) => name.length > 0)
                  .join(", "),
              })}
            </p>
          ) : null}
          {canWriteTag && isOneByOne && value.ids.length > 0 && value.tagIDs.length === 0 ? (
            <p className="body-small mt-2 text-foreground-more-muted">
              {t("A fixed list: athletes added later won't join. Tag them to let the chart grow.")}
            </p>
          ) : null}
        </div>
      )}
    </div>
  );
}

/**
 * On the check step: says that a chart built on a fixed list of athletes won't
 * pick up athletes added later, and offers to tag them on the spot so the
 * chart follows the tag instead. Renders nothing without tag-write rights or
 * when the scope has no fixed athletes.
 */
export function FixedListTagHint({
  scope,
  onChange,
  name,
}: {
  scope: ScopeIDs;
  onChange: (next: ScopeIDs) => void;
  /** The side of a Profile this concerns, e.g. "Whole squad"; omitted for one-scope charts. */
  name?: string;
}) {
  const { t } = useTranslation();
  const demo = useChartDemo();
  const canWriteTag = useHasPrivilege("writeEntityTag");
  const tagTheseWording = useChartTagTheseWording();
  const tagTheseAthletes = useTagTheseAthletes(tagTheseWording);
  if (demo || !canWriteTag || scope.ids.length === 0) return null;
  return (
    <div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-2xl border border-surface-stroke px-4 py-3">
      <p className="body-small min-w-0 flex-1 text-foreground-muted">
        {name
          ? t("{name} is a fixed list of athletes: athletes added later won't join. Tag them to let it grow.", { name })
          : t("These athletes are a fixed list: athletes added later won't join. Tag them to let the chart grow.")}
      </p>
      <TagTheseAthletesButton
        count={scope.ids.length}
        onClick={() => tagTheseAthletes(scope.ids, (tag) => onChange({ ids: [], tagIDs: [...scope.tagIDs, tag.id] }))}
      />
    </div>
  );
}

/**
 * "Which athlete?" for questions about one athlete (their lifts side by side):
 * a searchable list of the roster, one pick. Saved as a fixed athlete, never a
 * tag — the question is about this person, and a tag could grow into a team.
 */
export function OneAthleteStep({
  prompt,
  value,
  onChange,
  roster,
}: {
  prompt: string;
  value: ScopeIDs;
  onChange: (next: ScopeIDs) => void;
  roster: readonly UserReducedReturnDto[];
}) {
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const term = search.trim().toLowerCase();
  const picked = value.tagIDs.length === 0 && value.ids.length === 1 ? value.ids[0] : null;
  const athletes = [...roster]
    .sort((a, b) => (a.name ?? a.email ?? "").localeCompare(b.name ?? b.email ?? ""))
    .filter((user) => !term || (user.name ?? user.email ?? "").toLowerCase().includes(term));
  return (
    <div className="space-y-3" role="radiogroup" aria-label={prompt}>
      <p className="heading-normal text-foreground-default">{prompt}</p>
      {value.ids.length + value.tagIDs.length > 0 && picked == null ? (
        <p className="body-small text-feedback-warning">
          {t("This question looks at one athlete. Pick one.")}
        </p>
      ) : null}
      <SearchAndFilterCard
        search={search}
        onSearch={setSearch}
        placeholder={t("Search athletes…")}
      />
      {athletes.length === 0 ? (
        <p className="body-small text-foreground-muted">{t("No athlete matches.")}</p>
      ) : null}
      {athletes.map((user) => (
        <ChoiceRow
          key={user.id}
          active={picked === user.id}
          title={user.name ?? user.email ?? ""}
          onClick={() => onChange({ ids: [user.id], tagIDs: [] })}
        />
      ))}
    </div>
  );
}

/** The athletes a scope covers today: fixed picks plus the tags' members. */
export function scopeMembers(scope: ScopeIDs, roster: readonly UserReducedReturnDto[]): string[] {
  const tagged = scope.tagIDs.flatMap((tagID) => tagMemberIDs(roster, tagID));
  return [...new Set([...scope.ids, ...tagged])];
}

// ─── Which lifts ─────────────────────────────────────────────────────────────

/** How many suggested lifts the step lists before "Other exercise". */
const MAX_LIFTS = 8;

/**
 * "Which lifts?": the exercises the given athletes actually trained in the
 * timeframe, most athletes first, with how many of them did. Any other
 * exercise stays reachable through the regular picker. `single` (Ranking)
 * takes one lift, as the chart shows one at a time; there a lift trained by
 * fewer than `minAthletes` is flagged as too few to compare.
 */
export function LiftsStep({
  prompt,
  athleteIDs,
  timeframe,
  onTimeframeChange,
  value,
  onChange,
  single = false,
  max,
  prepick = 0,
  optional = false,
  minAthletes = 0,
  pickerTitle,
}: {
  prompt: string;
  athleteIDs: readonly string[];
  timeframe: Timeframe;
  onTimeframeChange: (next: Timeframe) => void;
  value: readonly string[];
  onChange: (ids: string[]) => void;
  single?: boolean;
  /** The most lifts this question takes; further rows can't be ticked once reached. */
  max?: number;
  /** Pre-pick this many of the most-trained lifts when the step opens empty. */
  prepick?: number;
  optional?: boolean;
  minAthletes?: number;
  pickerTitle: string;
}) {
  const { t } = useTranslation();
  const demo = useChartDemo();
  const activity = useLiftActivity(timeframe);
  const { exercises: catalogue } = useExercises();
  const rows = activity.status === "ready" ? activity.rows : [];
  const lifts = liftActivity(rows, athleteIDs).slice(0, MAX_LIFTS);
  const nameOf = exerciseLabelResolver(catalogue, rows);
  const suggested = new Set(lifts.map((lift) => lift.definitionID));
  const others = value.filter((id) => !suggested.has(id));
  const groupSize = athleteIDs.length;

  const atMax = !single && max != null && value.length >= max;
  const overShape = single ? value.length > 1 : max != null && value.length > max;

  function toggle(id: string) {
    if (single) onChange([id]);
    else if (value.includes(id)) onChange(value.filter((x) => x !== id));
    else if (!atMax) onChange([...value, id]);
  }

  // A question that starts on a few lifts (the team matrix) pre-picks the
  // most-trained ones once, as soon as they're known, if nothing is picked yet.
  const prepicked = useRef(false);
  useEffect(() => {
    if (prepicked.current || prepick <= 0 || value.length > 0 || lifts.length === 0) return;
    prepicked.current = true;
    onChange(lifts.slice(0, prepick).map((lift) => lift.definitionID));
  }, [prepick, value.length, lifts, onChange]);

  return (
    <div className="space-y-3">
      <div>
        <p className="heading-normal text-foreground-default">{prompt}</p>
        <p className="body-small mt-1 text-foreground-muted">
          {optional
            ? t("Optional for this metric. Lifts these athletes trained, most athletes first.")
            : t("Lifts these athletes trained, most athletes first.")}
        </p>
        {/* The question fixes how many lifts it compares (its shape). A pick
            carried over from another question can be over that; say so. */}
        {overShape ? (
          <p className="body-small mt-1 text-feedback-warning">
            {single
              ? t("This question looks at one lift. Pick one.")
              : t("This question compares up to {max} lifts. Untick some.", { max: max ?? 0 })}
          </p>
        ) : max != null && !single ? (
          <p className="body-small mt-1 text-foreground-more-muted">
            {t("Up to {max} lifts for this question.", { max })}
          </p>
        ) : null}
      </div>
      <TimeframePresets value={timeframe} onChange={onTimeframeChange} />

      {activity.status === "loading" ? (
        <p className="body-small text-foreground-more-muted">
          {t("Looking up what these athletes trained…")}
        </p>
      ) : activity.status === "error" ? (
        <StalenessHint onRetry={activity.retry}>
          {t("Couldn’t look up what these athletes trained. You can still pick any exercise below.")}
        </StalenessHint>
      ) : athleteIDs.length === 0 ? (
        <p className="body-small text-foreground-muted">
          {t("Nobody has this tag yet, so there is nothing to suggest. Pick the exercises below.")}
        </p>
      ) : lifts.length === 0 ? (
        <p className="body-small text-foreground-muted">
          {t("None of these athletes has a session in this timeframe. Try a longer one, or pick an exercise below.")}
        </p>
      ) : (
        <div className="space-y-2" role={single ? "radiogroup" : "group"} aria-label={prompt}>
          {lifts.map((lift) => {
            const count = lift.athleteIDs.length;
            const tooFew = minAthletes > 0 && count < minAthletes;
            return (
              <ChoiceRow
                key={lift.definitionID}
                multiple={!single}
                active={value.includes(lift.definitionID)}
                dimmed={tooFew || (atMax && !value.includes(lift.definitionID))}
                title={nameOf(lift.definitionID)}
                detail={
                  tooFew
                    ? t("{count, plural, one {# athlete} other {# athletes}} trained it · too few to compare", { count })
                    : t("{count, plural, one {# athlete} other {# athletes}} trained it", { count })
                }
                trailing={
                  <span aria-hidden className="flex w-14 shrink-0">
                    <span
                      className="h-1.5 rounded-full bg-foreground-platinum-green-bright/60"
                      style={{ width: `${groupSize ? Math.max(8, (count / groupSize) * 100) : 0}%` }}
                    />
                  </span>
                }
                onClick={() => toggle(lift.definitionID)}
              />
            );
          })}
        </div>
      )}

      {/* The whole catalogue: not in the demo, whose lifts are the suggestions. */}
      {demo ? null : (
        <div className="rounded-2xl border border-surface-stroke px-4 py-3">
          <p className="body-prominent mb-2 text-foreground-default">{t("Other exercise")}</p>
          <ExerciseSelection
            pickerTitle={pickerTitle}
            ids={others}
            athleteIDs={athleteIDs}
            emptyHint=""
            hideLabel
            onChange={(nextOthers) => {
              if (single) {
                const added = nextOthers.find((id) => !others.includes(id)) ?? nextOthers[0];
                onChange(added ? [added] : value.filter((id) => suggested.has(id)));
              } else {
                onChange([...value.filter((id) => suggested.has(id)), ...nextOthers]);
              }
            }}
          />
        </div>
      )}
    </div>
  );
}

// ─── Profile: which metrics ──────────────────────────────────────────────────

/** The radar reads best with this many axes. */
export const PROFILE_AXES_MIN = 3;
export const PROFILE_AXES_MAX = 6;

/**
 * "Compare on…": the template's metric bundle as one choice, or a custom set
 * of axes (the regular multi-picker) with a note on how many read well.
 */
export function BundleStep({
  prompt,
  bundleName,
  bundleIDs,
  value,
  onChange,
  options,
  loading,
}: {
  prompt: string;
  bundleName: string;
  bundleIDs: readonly string[];
  value: readonly string[];
  onChange: (ids: string[]) => void;
  options: MetricOption[];
  loading: boolean;
}) {
  const { t } = useTranslation();
  const isBundle = bundleIDs.length > 0 && sameSet(value, bundleIDs);
  const [customOpen, setCustomOpen] = useState(!isBundle && value.length > 0);
  const labelOf = (id: string) => options.find((o) => o.displayBaseID === id)?.label ?? "";
  const bundleNames = bundleIDs.map(labelOf).filter((n) => n.length > 0).join(" · ");
  const outside = value.length > 0 && (value.length < PROFILE_AXES_MIN || value.length > PROFILE_AXES_MAX);

  return (
    <div className="space-y-3" role="radiogroup" aria-label={prompt}>
      <p className="heading-normal text-foreground-default">{prompt}</p>
      {bundleIDs.length > 0 ? (
        <ChoiceRow
          active={isBundle && !customOpen}
          title={bundleName}
          detail={bundleNames}
          onClick={() => {
            setCustomOpen(false);
            onChange([...bundleIDs]);
          }}
        />
      ) : null}
      <ChoiceRow
        active={customOpen || (!isBundle && value.length > 0)}
        title={t("Choose the metrics yourself")}
        detail={t("3 to 6 metrics read best.")}
        onClick={() => setCustomOpen(true)}
      />
      {customOpen || (!isBundle && value.length > 0) ? (
        <div className="space-y-2 rounded-2xl border border-surface-stroke px-4 py-3">
          <MetricAxesSelection
            options={options}
            loading={loading}
            selectedIDs={[...value]}
            onChange={onChange}
            title={t("Metrics")}
          />
          {outside ? (
            <p className="body-small text-foreground-red-orange">
              {value.length < PROFILE_AXES_MIN
                ? t("With fewer than 3 metrics the shape says little. Add one or two more.")
                : t("More than 6 metrics get hard to read. Consider leaving some out.")}
            </p>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
