"use client";

import { useState, type CSSProperties, type ReactNode } from "react";
import type {
  LiftsSummaryReturnDto,
  ZoneReturnDto,
} from "@enode/core/api/dtos/history-stats";
import {
  LIFT_BAND_KEYS,
  liftBandCaption,
  liftBandColor,
  liftBandFigures,
  type LiftBandFigures,
} from "@enode/core/analysis/lift-bands";
import {
  MUSCLE_USAGE_TIER_BOUNDS,
  muscleFillFor,
  muscleUsageColor,
} from "@enode/core/muscle-map/coloring";
import type { StoreState } from "@enode/core/store-kit/status";
import { weekEndExclusive } from "@enode/core/training/calendar-week";
import {
  roundSets,
  sessionMuscleBar,
  sessionMuscleFocus,
  setsAxis,
  type ExerciseMuscles,
  type SessionMuscleRowVm,
  type SetsAxis,
  type SessionMusclesVm,
} from "@enode/core/training/session-muscle-week";
import { splitPercents } from "@enode/core/training/zone-split";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  LiftBandBar,
  useLiftAverageCaption,
  useTopLiftText,
} from "../charts/lift-bands";
import {
  ZONE_COLORS,
  ZoneSplitBar,
  type ZoneSplit,
} from "../charts/zone-split-slider";
import { RequireData } from "../feedback/require-data";
import { CheckCircleFillIcon, TargetIcon } from "../icons";
import { LOOK } from "../live/look";
import { LottieCircle } from "@enode/ui/LottieCircle";
import { MUSCLE_ICON_MEDIA } from "@enode/core/muscle-map/icons";
import { MuscleMap } from "../muscle-map/muscle-map";

// Session Details → "What this session did": the session's effect. Shared by
// the portal's session drawer and the tracking app's Insights → Details tab.
// - The muscles card leads: a large body map in the session's tint beside
//   what the session did to the muscles — the headline (the main work, the
//   sets it added, where that leaves the week's target) over every muscle's
//   week as a bar: this session (orange, or the host's `sessionTone`), the
//   rest of its week (grey), the
//   target as the track's end or a tick past it.
// - Under it, the session's character as its own card — the muscle-quality
//   split, the session's bar over the goal's (strength), or the lifts per band
//   (weightlifting) — beside whatever the host passes as `beside` (the
//   Details tab's tags and note).
// The figures come from the host (`@enode/core/training/session-muscle-week`):
// the portal reads a stored session's history stats, the tracking app derives
// a live session's from its local sets; this file only paints.
//
// The big map this replaced was the same for every session of an exercise:
// the session's `muscleMapVolume` is scaled to its busiest muscle, so it only
// shows which muscles the exercise trains.
//
// Adaptive to the section's width (`@container`) — the portal drawer resizes,
// the app shows it in a phone sheet or a side pane:
// - narrow: the map over the muscles; the character over `beside`;
// - from 40rem of the muscles card: the map beside the muscles;
// - from 56rem: the character beside `beside`, both as tall as the taller.

const CARD = `min-w-0 ${LOOK.panel} p-5`;

// The small caps label over the headline (the section header's grammar).
const LABEL = "stat-small uppercase text-foreground-muted";

// The session's part of the muscle bars, its figures and its key dot. Red-orange
// unless the host opts into another tone (`sessionTone`), which sets
// `--session-tone` on the section. Both apps draw the session in Deep Green.
const SESSION_COLOR = "var(--session-tone, var(--foreground-red-orange))";

// The muscle bars' thickness and corner radius: 10 px with small corners unless
// the host opts into its own thickness (`barThicknessPx`), which sets
// `--session-bar-h` and turns the bars into pills.
const MUSCLE_BAR_H = "var(--session-bar-h, 0.625rem)";
const MUSCLE_BAR_R = "var(--session-bar-r, 0.25rem)";

/** The colour of the session's own part of the muscle bars and figures. */
export type SessionTone = "redOrange" | "deepGreen";

const SESSION_TONE_VALUE: Record<SessionTone, string | undefined> = {
  redOrange: undefined,
  deepGreen: "var(--foreground-platinum-green-bright)",
};

// The rest of the week, a lighter grey: the session's colour leads the bar.
const OTHERS_COLOR = "color-mix(in srgb, var(--foreground-most-muted) 55%, transparent)";

/** The session's week, as the Details tab loaded it for "Sets per muscle". */
export type SessionWeekFigures = {
  /** Monday 00:00 (local) of the session's week. */
  start: number;
  isCurrentWeek: boolean;
  status: "idle" | "loading" | "loaded" | "empty" | "error";
  /** For the error surface (`RequireData`). */
  state: StoreState;
  retry: () => void;
};

// The quality the most sets trained — only when one leads outright.
function dominantZoneIndex(split: ZoneSplit): number | null {
  const shares = [split.zone0, split.zone1, split.zone2];
  const max = Math.max(...shares);
  if (!(max > 0)) return null;
  const leaders = shares.filter((share) => share === max);
  return leaders.length === 1 ? shares.indexOf(max) : null;
}

/**
 * The muscle-quality card: the session's split bar over the goal's (with
 * `goalSplit`) — the goal's at reduced opacity so it reads as the
 * reference, not a second result — then the session's three shares, and, in
 * the title row, how the session's lead
 * sits with the goal's. The goal's shares are the bar's accessible name, not
 * printed. Renders nothing without a distribution (a weightlifting session:
 * the key is absent).
 */
export function ZoneDistributionCard({
  zoneDistribution,
  goalSplit = null,
}: {
  zoneDistribution: ZoneReturnDto | null | undefined;
  goalSplit?: ZoneSplit | null;
}) {
  const { t } = useTranslation();
  if (!zoneDistribution) return null;
  const split = {
    zone0: zoneDistribution.zone0 ?? 0,
    zone1: zoneDistribution.zone1 ?? 0,
    zone2: zoneDistribution.zone2 ?? 0,
  };
  const names = [t("Power"), t("Hypertrophy"), t("Strength")];
  const percents = splitPercents(split);
  const goalPercents = goalSplit ? splitPercents(goalSplit) : null;
  const dominant = dominantZoneIndex(split);
  const goalDominant = goalSplit ? dominantZoneIndex(goalSplit) : null;
  const matchesGoal = dominant != null && dominant === goalDominant;

  return (
    <section className={`${CARD} flex flex-col`}>
      <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
        <h3 className="heading-section text-foreground-default">{t("Muscle qualities")}</h3>
        {goalDominant != null ? (
          matchesGoal ? (
            <span className="body-small inline-flex items-center gap-1.5 rounded-full bg-foreground-platinum-green/12 py-0.5 pl-1.5 pr-2.5 text-foreground-platinum-green">
              <CheckCircleFillIcon className="size-3.5 shrink-0" />
              {t("In line with the goal")}
            </span>
          ) : (
            <span className="body-small inline-flex items-center gap-1.5 rounded-full bg-surface-base-muted py-0.5 pl-1.5 pr-2.5 text-foreground-default">
              <TargetIcon className="size-3.5 shrink-0 text-foreground-muted" />
              {t("The goal focuses on {quality}", { quality: names[goalDominant] })}
            </span>
          )
        ) : null}
      </div>

      {/* Bars and shares as one block, centred in what the card has left when
          it stretches to its neighbour's height. */}
      <div className="my-auto pt-5">
      {/* The session's bar is decorative (the shares are printed below); the
          goal's carries its shares as its accessible name. */}
      <div className="flex flex-col gap-2.5">
        {goalSplit && goalPercents ? (
          <>
            <BarRow label={t("Session")}>
              <ZoneSplitBar {...split} height={10} />
            </BarRow>
            <BarRow label={t("Goal")}>
              <ZoneSplitBar
                {...goalSplit}
                height={10}
                className="opacity-40"
                ariaLabel={t("Goal: {power} % power, {hypertrophy} % hypertrophy, {strength} % strength", {
                  power: goalPercents[0],
                  hypertrophy: goalPercents[1],
                  strength: goalPercents[2],
                })}
              />
            </BarRow>
          </>
        ) : (
          <ZoneSplitBar {...split} height={10} />
        )}
      </div>

      <dl className="mt-5 grid grid-cols-3 gap-2">
        {names.map((name, index) => {
          return (
            <div key={name} className="flex min-w-0 flex-col-reverse">
              <dt className="body-small flex min-w-0 items-center gap-1.5 text-foreground-muted">
                <span
                  aria-hidden
                  className="size-2 shrink-0 rounded-full"
                  style={{ backgroundColor: ZONE_COLORS[index] }}
                />
                <span className="truncate">{name}</span>
              </dt>
              <dd className="stat-medium-digits tabular-nums text-foreground-default">
                {percents[index]} %
              </dd>
            </div>
          );
        })}
      </dl>
      </div>
    </section>
  );
}

/**
 * A weightlifting session's lifts per band, in the muscle-quality card's
 * grammar so the two read as one family: the title (sets · lifts) with the
 * average % PB as a pill, the band bar and the four counts as a block centred
 * in the card (number first, the band's dot and range under it), the top lift
 * at the card's foot. The figures come from `liftBandFigures`; the shared
 * `LiftBands` block (week card) keeps its own layout.
 */
function LiftBandsCard({ figures, sets }: { figures: LiftBandFigures; sets: number | null }) {
  const { t } = useTranslation();
  const average = useLiftAverageCaption(figures);
  const top = useTopLiftText(figures);
  const lifts = t(
    {
      text: "{count, plural, one {# lift} other {# lifts}}",
      context:
        "Weightlifting volume: number of lifts (reps at 50 % of the PB or more), not attempts or disciplines",
    },
    { count: figures.lifts },
  );

  return (
    <section className={`${CARD} flex flex-col`}>
      <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
        <h3 className="heading-section text-foreground-default">
          {sets != null && sets > 0
            ? `${t("{count, plural, one {# set} other {# sets}}", { count: sets })} · ${lifts}`
            : lifts}
        </h3>
        {average ? (
          <span className="body-small rounded-full bg-surface-base-muted px-2.5 py-0.5 tabular-nums text-foreground-default">
            {average}
          </span>
        ) : null}
      </div>

      <div className="my-auto pt-5">
        {figures.bandedLifts > 0 ? (
          <>
            <LiftBandBar bands={figures.bands} height={10} />
            <dl className="mt-5 grid grid-cols-4 gap-2">
              {LIFT_BAND_KEYS.map((key, index) => (
                <div key={key} className="flex min-w-0 flex-col-reverse">
                  <dt className="body-small flex min-w-0 items-center gap-1.5 text-foreground-muted">
                    <span
                      aria-hidden
                      className="size-2 shrink-0 rounded-full"
                      style={{ backgroundColor: liftBandColor(index) }}
                    />
                    <span className="truncate">{liftBandCaption(index)}</span>
                  </dt>
                  <dd className="stat-medium-digits tabular-nums text-foreground-default">
                    {figures.bands[index] ?? 0}
                  </dd>
                </div>
              ))}
            </dl>
          </>
        ) : (
          // Lifts without a PB: counted, no bands, no empty bar.
          <p className="body-normal text-foreground-muted">{t("No PB for this lift yet")}</p>
        )}
      </div>

      {top ? (
        <div className="mt-5 flex items-baseline justify-between gap-3 border-t border-surface-stroke-muted pt-3">
          <span className={LABEL}>
            {t({
              text: "Top lift",
              context: "Weightlifting: the heaviest single lift of the scope, never 1RM",
            })}
          </span>
          <span className="body-normal tabular-nums text-foreground-default">{top}</span>
        </div>
      ) : null}
    </section>
  );
}

function BarRow({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="grid grid-cols-[4rem_minmax(0,1fr)] items-center gap-3">
      <span className="body-small truncate text-foreground-muted">{label}</span>
      {children}
    </div>
  );
}

/**
 * The "What this session did" section.
 *
 * @param muscles - the session's sets per muscle, from `buildSessionMusclesVm`.
 * @param week - the session's week, or `null` when it can't be loaded (no
 *   athlete or date on the session): the rows then show the session's sets only.
 * @param zoneDistribution - the quality split; pass `null` where the session
 *   has none to show (not a strength session, or no distribution).
 * @param goalSplit - what the athlete's training goal asks for; `null` without one.
 * @param lifts - a weightlifting session's lifts summary and the sets behind
 *   them (`sessionLiftSets`); `null`, or a summary without lifts, shows none.
 * @param beside - shown beside the character card (full width without one).
 * @param warmupsOnly - the session had warm-up sets only: the backend counts no
 *   work set, so its figures are all zero. The muscles card then says so and
 *   shows `exercise` — what the exercise trains — instead of empty rows.
 * @param exercise - from `exerciseMuscles`; `null` when unknown.
 */
export function SessionTrainedSection({
  muscles,
  week,
  zoneDistribution,
  goalSplit,
  lifts,
  beside = null,
  warmupsOnly = false,
  exercise = null,
  sessionTone = "redOrange",
  barThicknessPx,
  titleInCard = false,
  narrowIcons = false,
}: {
  muscles: SessionMusclesVm;
  week: SessionWeekFigures | null;
  zoneDistribution: ZoneReturnDto | null;
  goalSplit: ZoneSplit | null;
  lifts: { summary: LiftsSummaryReturnDto | null | undefined; sets: number | null } | null;
  beside?: ReactNode;
  warmupsOnly?: boolean;
  exercise?: ExerciseMuscles | null;
  /** The session's colour in the muscle bars; see {@link SessionTone}. */
  sessionTone?: SessionTone;
  /**
   * Draws the muscle bars as pills of this thickness (the host's shared bar
   * thickness) instead of the default 10 px bars with small corners. Unset,
   * the portal's look.
   */
  barThicknessPx?: number;
  /**
   * Puts "What this session did" inside the muscles card as its heading (the
   * look of the other session-details cards, e.g. the velocity profile)
   * instead of a small label above the cards. Unset, the portal's look.
   */
  titleInCard?: boolean;
  /**
   * On a narrow card, the muscle rows keep the wide table layout (icon | bar |
   * session | week) with each muscle's icon in place of its name. Unset, the
   * narrow layout puts name and figures on a line over the bar.
   */
  narrowIcons?: boolean;
}) {
  const { t } = useTranslation();
  const liftFigures = lifts ? liftBandFigures(lifts.summary) : null;
  // An all-zero split (no work set counted) has nothing to show.
  const hasShares =
    zoneDistribution != null &&
    [zoneDistribution.zone0, zoneDistribution.zone1, zoneDistribution.zone2].some(
      (share) => typeof share === "number" && share > 0,
    );
  const character =
    hasShares ? (
      <ZoneDistributionCard zoneDistribution={zoneDistribution} goalSplit={goalSplit} />
    ) : liftFigures ? (
      <LiftBandsCard figures={liftFigures} sets={lifts?.sets ?? null} />
    ) : null;

  return (
    // `contents`: the wrapper only carries the tone variable down.
    <div
      className="contents"
      style={
        {
          "--session-tone": SESSION_TONE_VALUE[sessionTone],
          "--session-bar-h": barThicknessPx != null ? `${barThicknessPx}px` : undefined,
          "--session-bar-r": barThicknessPx != null ? "9999px" : undefined,
        } as CSSProperties
      }
    >
      <TrainedFrame
        title={titleInCard ? null : t("What this session did")}
        character={character}
        beside={beside}
      >
        {warmupsOnly ? (
          <WarmupsOnlyCard
            exercise={exercise}
            title={titleInCard ? t("What this session did") : undefined}
          />
        ) : (
          <SessionMusclesCard
            vm={muscles}
            week={week}
            title={titleInCard ? t("What this session did") : undefined}
            narrowIcons={narrowIcons}
          />
        )}
      </TrainedFrame>
    </div>
  );
}

function TrainedFrame({
  title,
  character,
  beside,
  children,
}: {
  /** The label above the cards; `null` when the host puts it in the card. */
  title: string | null;
  character: ReactNode;
  beside: ReactNode;
  children: ReactNode;
}) {
  return (
    <section className="@container min-w-0">
      {title != null ? <h3 className={LOOK.eyebrow}>{title}</h3> : null}
      <div className={`flex flex-col gap-3 ${title != null ? "mt-3" : ""}`}>
        {children}
        {character || beside ? (
          // Both cards as tall as the taller one (grid stretch).
          <div className={`grid gap-3 ${character && beside ? "@[56rem]:grid-cols-2" : ""}`}>
            {character}
            {beside}
          </div>
        ) : null}
      </div>
    </section>
  );
}

// What the week part of the rows can show right now.
type WeekPhase = "loading" | "ready" | "none";

function weekPhaseOf(week: SessionWeekFigures | null, hasWeekRows: boolean): WeekPhase {
  if (!week) return "none";
  if (week.status === "idle" || week.status === "loading") return "loading";
  return week.status === "loaded" && hasWeekRows ? "ready" : "none";
}

// Rows shown before "Show all": a compound lift names a dozen muscles, most
// with a fraction of a set — the first few carry the story.
const COLLAPSED_ROWS = 5;

// The muscles card's grid: the map's column (small beside the headline on a
// phone, 17rem from 44rem of the card) and the headline + table column.
const MUSCLES_GRID =
  "grid-cols-[6.5rem_minmax(0,1fr)] @[44rem]:grid-cols-[17rem_minmax(0,1fr)]";
// The map's cell: beside the headline on a phone; from 44rem the full height
// of the card, split off by a hairline, with its key under the map.
const MAP_CELL =
  "flex flex-col items-center justify-center gap-4 pl-5 pt-5 @[44rem]:row-span-2 @[44rem]:border-r @[44rem]:border-surface-stroke-muted @[44rem]:px-5 @[44rem]:py-6";

// The map's column of the muscles skeleton: the full height of the card from
// 44rem of the card (split off by a hairline), a band over the text below that.
const MAP_STAGE =
  "flex shrink-0 flex-col items-center justify-center gap-4 border-b border-surface-stroke-muted px-5 py-6 @[44rem]:w-[17rem] @[44rem]:border-b-0 @[44rem]:border-r";

// One muscle row, as a table from 34rem of the muscles pane: name | bar |
// this session | week. Narrow: name and figures on a line, the bar under them.
const ROW_GRID =
  "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1.5 @[34rem]:grid-cols-[minmax(7rem,10rem)_minmax(0,1fr)_8rem]";
// `narrowIcons`: the table layout at every width — on a narrow pane the
// muscle's icon takes the name's column (the name stays for screen readers).
const ICON_ROW_GRID =
  "grid grid-cols-[2.25rem_minmax(0,1fr)_8rem] items-center gap-x-3 @[34rem]:grid-cols-[minmax(7rem,10rem)_minmax(0,1fr)_8rem] @[34rem]:gap-x-4";
// The two figure columns, right-aligned in fixed widths so they line up.
const SESSION_COL = "w-12 text-right";
const WEEK_COL = "w-16 text-right";

/**
 * The muscles card: the body map on its own stage (keyed: main work /
 * assisting) beside the headline — the main work, the sets it added, the
 * week's target — over "Sets per muscle", a table of the muscles the session
 * trained: the week as a bar (this session orange, the rest of its week grey,
 * the target as the track's end or a tick past it), the sets this session
 * added and the week's sets against the target. Long lists fold after
 * {@link COLLAPSED_ROWS} rows.
 */
// The section title as the muscles card's own heading (`titleInCard`): the
// session-details cards' heading style, over the card's grid; the negative
// margin takes back part of the grid's top padding so the gap matches theirs.
function CardHeading({ title }: { title: string }) {
  return (
    <div className="-mb-2 px-5 pt-5 @[44rem]:-mb-3 @[44rem]:px-6 @[44rem]:pt-6">
      <h3 className="heading-section text-foreground-default">{title}</h3>
    </div>
  );
}

export function SessionMusclesCard({
  vm,
  week,
  title,
  narrowIcons = false,
}: {
  vm: SessionMusclesVm;
  week: SessionWeekFigures | null;
  /** A heading inside the card (see `titleInCard`). */
  title?: string;
  /** Icons for names on a narrow card (see `SessionTrainedSection`). */
  narrowIcons?: boolean;
}) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(false);
  const hasWeekRows = vm.rows.some((row) => row.week != null);
  const phase = weekPhaseOf(week, hasWeekRows);
  const hasTargets = vm.rows.some((row) => row.week?.target != null);
  const hasMap = Object.keys(vm.usage).length > 0;
  const { primary } = sessionMuscleFocus(vm.rows);
  const primaryKeys = new Set(primary.map((row) => row.key));
  // One scale for every row — from all rows, so it holds when the list unfolds.
  // Without the week's figures yet, the bars show the session's sets alone.
  const axis = setsAxis(
    phase === "ready" ? vm.rows : vm.rows.map((row) => ({ ...row, week: null })),
  );
  const showTargets = phase === "ready" && hasTargets;
  // Folding one row away would cost a line to save a line.
  const foldable = vm.rows.length > COLLAPSED_ROWS + 1;
  const visibleRows = foldable && !expanded ? vm.rows.slice(0, COLLAPSED_ROWS) : vm.rows;

  if (vm.rows.length === 0) {
    return (
      <section className={CARD}>
        <h3 className="heading-section text-foreground-default">{t("Sets per muscle")}</h3>
        <p className="body-normal mt-3 text-foreground-muted">
          {t("No muscle data for this session.")}
        </p>
      </section>
    );
  }

  return (
    <section className={`@container min-w-0 overflow-hidden ${LOOK.panel}`}>
      {title ? <CardHeading title={title} /> : null}
      {/* Narrow (a phone): a small map beside the headline, the table under
          both. From 44rem: the map's own full-height column, the headline over
          the table beside it. */}
      <div className={`grid ${hasMap ? MUSCLES_GRID : "grid-cols-1"}`}>
        {hasMap ? (
          <div className={MAP_CELL}>
            <div className="w-full max-w-[13rem]">
              <MuscleMap
                fluid
                bodyFill="var(--surface-base-muted)"
                muscleFill={muscleFillFor(vm.usage)}
              />
            </div>
            {/* The small map's tints are read off the rows' dots. */}
            <div className="hidden @[44rem]:block">
              <MapKey />
            </div>
          </div>
        ) : null}

        <div className="min-w-0 self-center p-5 @[44rem]:self-start @[44rem]:p-6 @[44rem]:pb-0">
          <MuscleHeadline rows={vm.rows} phase={phase} />
        </div>

        <div
          className={`@container min-w-0 px-5 pb-5 @[44rem]:px-6 @[44rem]:pb-6 ${
            hasMap ? "col-span-2 @[44rem]:col-span-1 @[44rem]:col-start-2" : ""
          }`}
        >
          <div className="mt-1 @[44rem]:mt-6">
            <div
              className={`${narrowIcons ? ICON_ROW_GRID : ROW_GRID} border-b border-surface-stroke-muted pb-2`}
            >
              <h3
                className={`heading-section text-foreground-default ${
                  narrowIcons ? "col-span-2" : "@[34rem]:col-span-2"
                }`}
              >
                {t("Sets per muscle")}
              </h3>
              <div className="body-small flex justify-end gap-2 text-foreground-muted">
                <span className={SESSION_COL}>{t("Session")}</span>
                <span className={WEEK_COL}>{t("Week")}</span>
              </div>
            </div>
            <ul className="flex flex-col">
              {visibleRows.map((row) => (
                <SessionMuscleRow
                  key={row.key}
                  row={row}
                  phase={phase}
                  axis={axis}
                  main={primaryKeys.has(row.key)}
                  narrowIcons={narrowIcons}
                />
              ))}
            </ul>
            {phase !== "loading" ? <SetsAxisRow axis={axis} narrowIcons={narrowIcons} /> : null}
            {foldable ? (
              <button
                type="button"
                onClick={() => setExpanded((open) => !open)}
                aria-expanded={expanded}
                className="clickable-small -ml-2.5 mt-2 rounded-full px-2.5 py-1 text-foreground-red-orange transition-colors hover:bg-surface-base-muted"
              >
                {expanded
                  ? t("Show fewer")
                  : t("Show all {count} muscles", { count: vm.rows.length })}
              </button>
            ) : null}

            {week ? (
              // The week's figures failed: the rows keep the session's own
              // sets; the engine's inline alert offers Try again.
              <RequireData
                requirements={[{ state: week.state, label: t("the week's figures") }]}
                onRetry={week.retry}
                loading={<></>}
              >
                <></>
              </RequireData>
            ) : null}
            <WeekFootnote
              week={week}
              showBarKey={phase === "ready"}
              hasTargets={hasTargets}
              showTargets={showTargets}
            />
          </div>
        </div>
      </div>
    </section>
  );
}

/**
 * The muscles card of a warm-ups-only session: the backend counts no work
 * set, so nothing went to the week. Says that plainly, and shows what the
 * exercise trains — the map at reduced strength, the muscles named — so the
 * card still tells the coach what the warm-ups prepared.
 */
export function WarmupsOnlyCard({
  exercise,
  title,
}: {
  exercise: ExerciseMuscles | null;
  /** A heading inside the card (see `titleInCard`). */
  title?: string;
}) {
  const { t } = useTranslation();
  // The same grid as `SessionMusclesCard`, so a warm-ups-only session reads
  // like any other: narrow, a small map beside the headline and the text under
  // both; from 44rem, the map's own full-height column.
  return (
    <section className={`@container min-w-0 overflow-hidden ${LOOK.panel}`}>
      {title ? <CardHeading title={title} /> : null}
      <div className={`grid ${exercise ? MUSCLES_GRID : "grid-cols-1"}`}>
        {exercise ? (
          <div className={MAP_CELL}>
            <div className="w-full max-w-[13rem] opacity-60">
              <MuscleMap
                fluid
                bodyFill="var(--surface-base-muted)"
                muscleFill={muscleFillFor(exercise.usage)}
              />
            </div>
            <p className="body-small hidden text-center text-foreground-muted @[44rem]:block">
              {t("What the exercise trains")}
            </p>
          </div>
        ) : null}

        <div className="min-w-0 self-center p-5 @[44rem]:self-start @[44rem]:p-6 @[44rem]:pb-0">
          <p className={LABEL}>{t("Warm-ups only")}</p>
          <p className="heading-portal mt-1 text-foreground-default">{t("No work sets")}</p>
        </div>

        <div
          className={`min-w-0 px-5 pb-5 @[44rem]:px-6 @[44rem]:pb-6 ${
            exercise ? "col-span-2 @[44rem]:col-span-1 @[44rem]:col-start-2" : ""
          }`}
        >
          <p className="body-normal mt-1 max-w-[36rem] text-foreground-muted">
            {t(
              "Warm-up sets prepare the muscles but don’t count toward the week’s sets, so this session added none.",
            )}
          </p>
          {exercise ? (
            <div className="mt-6 flex flex-col gap-4">
              <MuscleChips label={t("Main muscles")} names={exercise.primary} strong />
              {exercise.assisting.length > 0 ? (
                <MuscleChips label={t("Assisting")} names={exercise.assisting} />
              ) : null}
            </div>
          ) : null}
        </div>
      </div>
    </section>
  );
}

function MuscleChips({
  label,
  names,
  strong = false,
}: {
  label: string;
  names: readonly string[];
  strong?: boolean;
}) {
  return (
    <div className="min-w-0">
      <p className={LABEL}>{label}</p>
      <ul className="mt-2 flex flex-wrap gap-1.5">
        {names.map((name) => (
          <li
            key={name}
            className={`body-small rounded-full border border-surface-stroke-muted px-2.5 py-0.5 ${
              strong ? "text-foreground-default" : "text-foreground-muted"
            }`}
          >
            {name}
          </li>
        ))}
      </ul>
    </div>
  );
}

// The map's key: the main work and the assisting muscles, in the map's tints.
function MapKey() {
  const { t } = useTranslation();
  const item = (usage: number, label: string) => (
    <li className="flex items-center gap-1.5 whitespace-nowrap">
      <span
        aria-hidden
        className="size-2 shrink-0 rounded-full"
        style={{ backgroundColor: muscleUsageColor(usage) }}
      />
      {label}
    </li>
  );
  return (
    <ul className="body-small flex flex-wrap justify-center gap-x-4 gap-y-1 text-foreground-muted">
      {item(1, t("Main work"))}
      {item(MUSCLE_USAGE_TIER_BOUNDS.mediumHigh, t("Assisting"))}
    </ul>
  );
}

// Where the main work leaves the week's target: reached, or how far to go.
// For several main muscles only when they agree — all reached, or all the same
// sets short ("each"); "1.5 to go" for one of two would read as both.
type TargetStatus = { reached: true } | { reached: false; toGo: number; each: boolean };

function targetStatusOf(
  primary: readonly SessionMuscleRowVm[],
  phase: WeekPhase,
): TargetStatus | null {
  if (phase !== "ready") return null;
  const statuses = primary.map((row): TargetStatus | null => {
    const target = row.week?.target ?? null;
    if (!row.week || target == null) return null;
    const bar = sessionMuscleBar(row.sessionSets, row.week);
    const weekSets = bar.session + bar.others;
    return weekSets >= target
      ? { reached: true }
      : { reached: false, toGo: roundSets(target - weekSets), each: primary.length > 1 };
  });
  if (statuses.length === 0 || statuses.some((status) => status == null)) return null;
  if (statuses.every((status) => status?.reached)) return { reached: true };
  const first = statuses[0];
  const allSame =
    first != null &&
    !first.reached &&
    statuses.every((status) => status != null && !status.reached && status.toGo === first.toGo);
  return allSame ? first : null;
}

// The session in a glance: the main work, the sets it added to the week, and —
// top right — where that leaves the week's target.
function MuscleHeadline({ rows, phase }: { rows: readonly SessionMuscleRowVm[]; phase: WeekPhase }) {
  const { t } = useTranslation();
  const { primary } = sessionMuscleFocus(rows);
  const primarySets = primary[0]?.sessionSets ?? null;
  const status = targetStatusOf(primary, phase);

  return (
    <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-3">
      <div className="min-w-0">
        <p className={LABEL}>{t("Main work")}</p>
        <p className="heading-portal mt-1 text-foreground-default">
          {primary.map((row) => row.name).join(" · ")}
        </p>
        {/* Nothing added yet (a live session before its first work set): no
            "+0" line. */}
        {primarySets != null && primarySets > 0 ? (
          <p className="body-normal mt-0.5 text-foreground-muted">
            <span className="stat-medium-digits tabular-nums" style={{ color: SESSION_COLOR }}>
              +{primarySets}
            </span>{" "}
            {primary.length > 1
              ? t(
                  "{count, plural, one {set each, added to the week} other {sets each, added to the week}}",
                  { count: primarySets },
                )
              : t("{count, plural, one {set added to the week} other {sets added to the week}}", {
                  count: primarySets,
                })}
          </p>
        ) : null}
      </div>
      {status ? (
        status.reached ? (
          <p className="body-small inline-flex shrink-0 items-center gap-1.5 rounded-full bg-foreground-platinum-green/12 py-1 pl-2 pr-3 text-foreground-platinum-green">
            <CheckCircleFillIcon className="size-3.5 shrink-0" />
            {t("Weekly target reached")}
          </p>
        ) : (
          <p className="body-small inline-flex shrink-0 items-center gap-1.5 rounded-full bg-surface-base-muted py-1 pl-2 pr-3 text-foreground-default">
            <TargetIcon className="size-3.5 shrink-0 text-foreground-muted" />
            {status.each
              ? t("{count, plural, one {# set} other {# sets}} each to the weekly target", {
                  count: status.toGo,
                })
              : t("{count, plural, one {# set} other {# sets}} to the weekly target", {
                  count: status.toGo,
                })}
          </p>
        )
      ) : null}
    </div>
  );
}

// "5.11" — the week's first and last day, in the portal's week-range grammar.
function dayMonth(date: Date): string {
  return `${date.getDate()}.${date.getMonth() + 1}`;
}

function WeekCaption({ week }: { week: SessionWeekFigures }) {
  const { t } = useTranslation();
  const end = new Date(weekEndExclusive(week.start));
  end.setDate(end.getDate() - 1);
  return (
    <span>
      {week.isCurrentWeek ? t("This week") : t("Week")}{" "}
      <span className="text-foreground-more-muted">
        {dayMonth(new Date(week.start))} – {dayMonth(end)}
      </span>
    </span>
  );
}

// A value's position on the shared axis, as a CSS percentage.
function axisPercent(value: number, axis: SetsAxis): string {
  return `${Math.min(100, Math.max(0, (value / axis.max) * 100))}%`;
}

// The axis's gridlines, behind the bars of a row.
function Gridlines({ axis }: { axis: SetsAxis }) {
  return (
    <>
      {axis.ticks.map((tick) => (
        <span
          key={tick}
          aria-hidden
          className="absolute inset-y-0 w-px -translate-x-1/2 bg-surface-stroke-muted"
          style={{ left: axisPercent(tick, axis) }}
        />
      ))}
    </>
  );
}

// The weekly target as a reference line: dashed, dark, the same in every row
// that has a target, explained in the footnote's key.
const TARGET_LINE =
  "absolute inset-y-0 w-0 -translate-x-1/2 border-l-2 border-dashed border-foreground-default";

function SessionMuscleRow({
  row,
  phase,
  axis,
  main,
  narrowIcons,
}: {
  row: SessionMuscleRowVm;
  phase: WeekPhase;
  axis: SetsAxis;
  /** One of the session's main muscles: its name reads first. */
  main: boolean;
  narrowIcons: boolean;
}) {
  const { t } = useTranslation();
  const bar = phase === "ready" && row.week ? sessionMuscleBar(row.sessionSets, row.week) : null;
  const weekSets = bar ? roundSets(bar.session + bar.others) : null;
  const target = row.week?.target ?? null;
  // Without the week's figures the bar is the session's sets alone.
  const sessionValue = bar ? bar.session : (row.sessionSets ?? 0);
  const othersValue = bar ? bar.others : 0;

  return (
    // From 34rem the bar fills the row's height, so the gridlines and target
    // lines run through the table unbroken.
    <li className={narrowIcons ? ICON_ROW_GRID : `${ROW_GRID} py-1.5 @[34rem]:py-0`}>
      {narrowIcons ? (
        // Narrow: the muscle's icon, its name for screen readers.
        <span className="flex items-center @[34rem]:hidden">
          <LottieCircle
            media={MUSCLE_ICON_MEDIA[row.key]}
            variant="icon"
            size={32}
            surfaceClassName="bg-surface-base-muted"
          />
          <span className="sr-only">{row.name}</span>
        </span>
      ) : null}
      <span
        className={`min-w-0 items-center gap-2 ${narrowIcons ? "hidden @[34rem]:flex" : "flex"}`}
      >
        <span
          aria-hidden
          className="size-2 shrink-0 rounded-full"
          style={{ backgroundColor: muscleUsageColor(row.usage) }}
        />
        <span
          className={`truncate ${
            main ? "body-prominent text-foreground-default" : "body-normal text-foreground-default"
          }`}
        >
          {row.name}
        </span>
      </span>

      {/* The figures: what this session added, and the week against its
          target. Short on screen (the column heads name them), in full for
          screen readers. */}
      <span
        className={`flex justify-end gap-2 tabular-nums ${narrowIcons ? "order-3" : "@[34rem]:order-3"}`}
      >
        <span className={`stat-small ${SESSION_COL}`} style={{ color: SESSION_COLOR }}>
          {row.sessionSets != null && row.sessionSets > 0 ? (
            <>
              <span aria-hidden>+{row.sessionSets}</span>
              <span className="sr-only">
                {t("+{count, plural, one {# set} other {# sets}}", { count: row.sessionSets })}
              </span>
            </>
          ) : null}
        </span>
        <span className={`stat-small text-foreground-muted ${WEEK_COL}`}>
          {phase === "loading" ? (
            <span className="inline-block h-4 w-12 animate-pulse rounded bg-surface-base-muted" />
          ) : weekSets != null ? (
            <>
              <span aria-hidden>
                {target != null ? `${weekSets} / ${roundSets(target)}` : weekSets}
              </span>
              <span className="sr-only">
                {target != null
                  ? t("{done} / {target} sets", { done: weekSets, target: roundSets(target) })
                  : t("{count, plural, one {# set} other {# sets}} in total", { count: weekSets })}
              </span>
            </>
          ) : null}
        </span>
      </span>

      {/* The bar: from 0 on the shared axis — this session, then the rest of
          its week stacked on it — with the target as a dashed line. */}
      <div
        aria-hidden
        className={`relative ${
          narrowIcons
            ? "order-2 col-span-1 h-10"
            : "col-span-2 h-5 @[34rem]:order-2 @[34rem]:col-span-1 @[34rem]:h-10"
        }`}
      >
        {phase === "loading" ? (
          <div
            className="absolute inset-x-0 top-1/2 -translate-y-1/2 animate-pulse bg-surface-base-muted"
            style={{ height: MUSCLE_BAR_H, borderRadius: MUSCLE_BAR_R }}
          />
        ) : (
          <>
            <Gridlines axis={axis} />
            <div
              className="absolute inset-x-0 top-1/2 flex -translate-y-1/2"
              style={{ height: MUSCLE_BAR_H }}
            >
              {sessionValue > 0 ? (
                <div
                  className="h-full"
                  style={{
                    width: axisPercent(sessionValue, axis),
                    backgroundColor: SESSION_COLOR,
                    borderRadius: othersValue > 0 ? `${MUSCLE_BAR_R} 0 0 ${MUSCLE_BAR_R}` : MUSCLE_BAR_R,
                  }}
                />
              ) : null}
              {othersValue > 0 ? (
                <div
                  className="h-full"
                  style={{
                    width: axisPercent(othersValue, axis),
                    backgroundColor: OTHERS_COLOR,
                    borderRadius: sessionValue > 0 ? `0 ${MUSCLE_BAR_R} ${MUSCLE_BAR_R} 0` : MUSCLE_BAR_R,
                  }}
                />
              ) : null}
            </div>
            {phase === "ready" && target != null ? (
              <span className={TARGET_LINE} style={{ left: axisPercent(target, axis) }} />
            ) : null}
          </>
        )}
      </div>
    </li>
  );
}

// The axis under the bars: a label at every gridline, in sets.
function SetsAxisRow({ axis, narrowIcons = false }: { axis: SetsAxis; narrowIcons?: boolean }) {
  return (
    <div aria-hidden className={`${narrowIcons ? ICON_ROW_GRID : ROW_GRID} pt-1`}>
      <span className={narrowIcons ? "block" : "hidden @[34rem]:block"} />
      <span className={narrowIcons ? "order-3 block" : "hidden @[34rem]:order-3 @[34rem]:block"} />
      <div
        className={`body-small relative h-4 tabular-nums text-foreground-more-muted ${
          narrowIcons ? "order-2 col-span-1" : "col-span-2 @[34rem]:order-2 @[34rem]:col-span-1"
        }`}
      >
        {axis.ticks.map((tick, index) => (
          <span
            key={tick}
            className={`absolute top-0 ${
              index === 0 ? "" : index === axis.ticks.length - 1 ? "-translate-x-full" : "-translate-x-1/2"
            }`}
            style={{ left: axisPercent(tick, axis) }}
          >
            {tick}
          </span>
        ))}
      </div>
    </div>
  );
}

// Under the table, one muted line: the week, the key to the bars and the
// target line (once the week's figures are in), and how a set is counted.
function WeekFootnote({
  week,
  showBarKey,
  hasTargets,
  showTargets,
}: {
  week: SessionWeekFigures | null;
  showBarKey: boolean;
  hasTargets: boolean;
  showTargets: boolean;
}) {
  const { t } = useTranslation();
  const dot = (color: string) => (
    <span aria-hidden className="size-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />
  );
  return (
    <div className="body-small mt-4 flex flex-col gap-1 text-foreground-muted">
      <ul className="flex flex-wrap items-center gap-x-4 gap-y-1">
        {week ? (
          <li>
            <WeekCaption week={week} />
          </li>
        ) : null}
        {showBarKey ? (
          <>
            <li className="flex items-center gap-1.5 whitespace-nowrap">
              {dot(SESSION_COLOR)}
              {t("This session")}
            </li>
            <li className="flex items-center gap-1.5 whitespace-nowrap">
              {dot(OTHERS_COLOR)}
              {t("Other sessions that week")}
            </li>
          </>
        ) : null}
        {showTargets ? (
          <li className="flex items-center gap-1.5 whitespace-nowrap">
            <span aria-hidden className="h-3 w-0 border-l-2 border-dashed border-foreground-default" />
            {t("Weekly target")}
          </li>
        ) : null}
      </ul>
      {showBarKey && !hasTargets ? (
        <p className="text-foreground-more-muted">
          {t("No weekly targets: the bars show the week’s sets.")}
        </p>
      ) : null}
      <p className="text-foreground-more-muted">
        {t("A set counts in full for the main muscle and in part for the muscles that assist.")}
      </p>
    </div>
  );
}

// Pulsing placeholder in the section's layout — shown while the session's
// history stats load. `withMix` keeps the character card for a session that
// will have one; `beside` renders as it will once loaded. `titleInCard`
// mirrors the loaded section's prop, so the title doesn't jump from above the
// card into it when the stats arrive.
export function SessionTrainedSectionSkeleton({
  withMix,
  beside = null,
  titleInCard = false,
}: {
  withMix: boolean;
  beside?: ReactNode;
  titleInCard?: boolean;
}) {
  const { t } = useTranslation();
  const character = withMix ? (
    <section aria-busy="true" className={CARD}>
      <div className="h-5 w-36 animate-pulse rounded-md bg-surface-base-muted" />
      <div className="mt-4 space-y-2">
        <div className="h-2.5 w-full animate-pulse rounded-full bg-surface-base-muted" />
        <div className="h-2.5 w-full animate-pulse rounded-full bg-surface-base-muted" />
      </div>
      <div className="mt-4 grid grid-cols-3 gap-2">
        {Array.from({ length: 3 }).map((_, i) => (
          <div key={i} className="space-y-1.5">
            <span className="block h-6 w-12 animate-pulse rounded bg-surface-base-muted" />
            <span className="block h-4 w-20 animate-pulse rounded bg-surface-base-muted" />
          </div>
        ))}
      </div>
    </section>
  ) : null;
  return (
    <TrainedFrame
      title={titleInCard ? null : t("What this session did")}
      character={character}
      beside={beside}
    >
      <section
        aria-busy="true"
        className={`@container min-w-0 overflow-hidden ${LOOK.panel}`}
      >
        {titleInCard ? <CardHeading title={t("What this session did")} /> : null}
        <div className="flex flex-col @[44rem]:flex-row">
          <div className={MAP_STAGE}>
            <div className="flex w-full max-w-[13rem] gap-1">
              <div className="aspect-[1/2] flex-1 animate-pulse rounded-2xl bg-surface-base-muted" />
              <div className="aspect-[1/2] flex-1 animate-pulse rounded-2xl bg-surface-base-muted" />
            </div>
          </div>
          <div className="flex min-w-0 flex-1 flex-col gap-2 p-5 @[44rem]:p-6">
            <span className="block h-3 w-20 animate-pulse rounded bg-surface-base-muted" />
            <span className="block h-8 w-56 animate-pulse rounded-md bg-surface-base-muted" />
            <div className="mt-6 flex flex-col gap-4">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="flex items-center gap-4">
                  <span className="block h-4 w-28 animate-pulse rounded bg-surface-base-muted" />
                  <span className="block h-1.5 flex-1 animate-pulse rounded-full bg-surface-base-muted" />
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </TrainedFrame>
  );
}
