"use client";

import { type PointerEvent, useState } from "react";
import type { CCRegressionModel } from "@enode/core/coaching/objects";
import {
  PEAK_LOAD_ZONE_PCT,
  PEAK_POWER_ZONE_HALF_WIDTH_PCT,
  profileOneRepMax,
  profilePeakPowerLoad,
  profileVelocityAt,
} from "@enode/core/coaching/velocity-profile";
import { SESSION_RM1_VELOCITY_GATE } from "@enode/core/coaching/rm1";
import { metricCategoryColorHex } from "@enode/core/metrics/category-colors";
import { useTranslation } from "@enode/core/translations/hooks";
import { SessionDetailsCard } from "@enode/ui/session-details/session-details-card";
import { StatDivider, StatFigure } from "./details-facts-card";

// Insights → Details: the athlete's load–velocity profile for the exercise.
// The profile's landmarks (estimated 1RM, peak power with its load, the
// minimum velocity threshold) as large figures, then one chart over the load axis:
// - the fitted velocity curve (left axis, m/s) and the mean power it implies
//   (P = load · g · v, right axis, W), with the peak-power and peak-load zones
//   filled under the velocity curve;
// - the session's measured reps: every counted rep's mean velocity at its
//   set's load (velocity only — the power curve is the model's);
// - TODAY's velocity line, dashed, from the best rep per load: a least-squares
//   line through them with two or more loads, else the profile's slope through
//   the one load lifted — how the athlete moves today against the profile;
// - the band around the profile where a set moves the session 1RM
//   (`estimateCommonSessionRm1`): a set is compared with the profile at its
//   load and its offset, in kg, counts within ±10 % of the 1RM (each set at
//   up to ±5 %). The offset is along the load axis, so in m/s the band is
//   ±10 % × 1RM × |slope|, the same height everywhere. The card has the profile, not the exercise 1RM the
//   rule takes as its base, so the profile's 1RM stands in for it;
// - the active set's load as a vertical line in the primary colour, its
//   velocity and power marked on the curves with dashed guides to their axes
//   (as the technique chart's crosshair), so they don't read as reps;
//   hovering (or dragging a finger over) the chart reads load, velocity and
//   power.
//
// Presentational: the host resolves the model (gated with `isUsableProfile`)
// and the measured reps, and formats loads in the athlete's units.

// The curves wear their metric category colours (velocity, power), as every
// metric chart in the app; the zones use power and force, as in the load
// keyboard's profile strip. Raw hex so SVG fills resolve in every build.
// Read at render time, not module load: the palette follows light/dark.
const velocityHex = () => metricCategoryColorHex("velocity");
const powerHex = () => metricCategoryColorHex("power");
const forceHex = () => metricCategoryColorHex("force");
const GRAVITY = 9.81;

const clampPct = (v: number) => Math.min(Math.max(v, 0), 100);
const formatVelocity = (v: number) => Math.max(0, v).toFixed(2);
const formatWatts = (w: number) => String(Math.round(Math.max(0, w)));

// A "nice" tick step (1, 2, 2.5 or 5 × 10ⁿ) giving about `count` intervals
// over 0…max.
function niceStep(max: number, count: number): number {
  if (!(max > 0)) return 1;
  const raw = max / count;
  const magnitude = 10 ** Math.floor(Math.log10(raw));
  const normalized = raw / magnitude;
  const nice =
    normalized <= 1
      ? 1
      : normalized <= 2
        ? 2
        : normalized <= 2.5
          ? 2.5
          : normalized <= 5
            ? 5
            : 10;
  return nice * magnitude;
}

// Ticks from 0 up to the first step at or above `max`; the axis ends there.
function niceTicks(max: number, count: number): number[] {
  const step = niceStep(max, count);
  const ticks: number[] = [];
  for (let v = 0; v < max + step * 0.999; v += step) {
    ticks.push(Number(v.toFixed(6)));
  }
  return ticks;
}

/** One measured rep: its set's load and its mean velocity. */
export type ProfileMeasuredRep = {
  // Stored units (kg).
  load: number;
  // The rep's mean velocity, m/s.
  velocity: number;
};

/**
 * Today's load–velocity line from the best rep per load: least squares over
 * those points with two or more distinct loads (when the fit falls with load),
 * else the profile's slope through the fastest point. Null without a point.
 */
export function todayVelocityLine(
  reps: readonly ProfileMeasuredRep[],
  profileSlope: number,
): { slope: number; intercept: number } | null {
  const bestByLoad = new Map<number, number>();
  for (const rep of reps) {
    const best = bestByLoad.get(rep.load);
    if (best == null || rep.velocity > best)
      bestByLoad.set(rep.load, rep.velocity);
  }
  const points = [...bestByLoad.entries()];
  if (points.length === 0) return null;
  if (points.length >= 2) {
    const n = points.length;
    const meanX = points.reduce((sum, [x]) => sum + x, 0) / n;
    const meanY = points.reduce((sum, [, y]) => sum + y, 0) / n;
    const sxx = points.reduce((sum, [x]) => sum + (x - meanX) ** 2, 0);
    const sxy = points.reduce(
      (sum, [x, y]) => sum + (x - meanX) * (y - meanY),
      0,
    );
    const slope = sxx > 0 ? sxy / sxx : NaN;
    if (Number.isFinite(slope) && slope < 0) {
      return { slope, intercept: meanY - slope * meanX };
    }
  }
  // One load (or a fit that doesn't fall with load): the profile's slope
  // through the fastest of the points.
  const [x, y] = points.reduce((a, b) => (b[1] > a[1] ? b : a));
  return { slope: profileSlope, intercept: y - profileSlope * x };
}

/**
 * @param model - the fitted profile; pass only a model that passes
 *   `isUsableProfile`, or `null` for the card's empty state.
 * @param currentLoad - the active set's load in stored units (kg), marked on
 *   the profile curves; `null` hides the marker.
 * @param measuredReps - the session's counted reps as measured (load + mean
 *   velocity); drawn as points, and today's line is fitted from the best rep
 *   per load.
 * @param formatLoad - formats a stored load for display, unit included
 *   (e.g. "100 kg", "BW +10 kg").
 * @param loadAxis - converts a stored load to the display unit for the load
 *   axis's tick numbers, with that unit's symbol for the axis title.
 */
export function VelocityProfileCard({
  model,
  currentLoad,
  measuredReps,
  formatLoad,
  loadAxis,
}: {
  model: CCRegressionModel | null;
  currentLoad: number | null;
  measuredReps: readonly ProfileMeasuredRep[];
  formatLoad: (storedLoad: number) => string;
  loadAxis: { toDisplay: (storedLoad: number) => number; unit: string };
}) {
  const { t } = useTranslation();
  const [hoverPct, setHoverPct] = useState<number | null>(null);

  if (!model) {
    return (
      <SessionDetailsCard title={t("Velocity profile")}>
        <p className="body-small text-foreground-muted">
          {t(
            "The athlete's velocity profile appears once enough sets of this exercise have been recorded.",
          )}
        </p>
      </SessionDetailsCard>
    );
  }

  const oneRepMax = profileOneRepMax(model);
  const peakPowerLoad = profilePeakPowerLoad(model);
  const measured = measuredReps.filter(
    (r) =>
      Number.isFinite(r.load) &&
      r.load > 0 &&
      Number.isFinite(r.velocity) &&
      r.velocity > 0,
  );

  // The load axis runs to the heavier of the model's 1RM and the loads lifted,
  // so no measured rep falls off the right edge.
  const xMax = Math.max(oneRepMax, ...measured.map((r) => r.load));
  const toPct = (load: number) => (xMax > 0 ? (load / xMax) * 100 : 0);
  const loadAtPct = (pct: number) => (pct / 100) * xMax;
  const velocityAtPct = (pct: number) =>
    Math.max(0, profileVelocityAt(model, loadAtPct(pct)));
  const powerAtPct = (pct: number) =>
    loadAtPct(pct) * GRAVITY * velocityAtPct(pct);
  const todayLine = todayVelocityLine(measured, model.cA1);
  const velocityTodayAtPct = todayLine
    ? (pct: number) =>
        Math.max(0, todayLine.slope * loadAtPct(pct) + todayLine.intercept)
    : null;

  const peakPowerPct = toPct(peakPowerLoad);
  const peakWatts = powerAtPct(peakPowerPct);
  // %1RM stays against the model's 1RM, as the load keyboard's strip states it.
  const currentShare =
    currentLoad != null && Number.isFinite(currentLoad) && oneRepMax > 0
      ? (currentLoad / oneRepMax) * 100
      : null;
  const markerPct =
    currentLoad != null && Number.isFinite(currentLoad)
      ? clampPct(toPct(currentLoad))
      : null;

  return (
    <SessionDetailsCard
      title={t("Velocity profile")}
      aside={
        currentShare != null
          ? t("Current load ≈{pct}% of 1RM", { pct: Math.round(currentShare) })
          : null
      }
    >
      {/* On a narrow card the max velocity drops out (the velocity axis
          shows it): 1RM and peak power keep their large digits. */}
      <div className="@container">
        <div className="flex items-stretch">
          <StatFigure
            label={t("Est. 1RM")}
            color={forceHex()}
            value={formatLoad(oneRepMax)}
            caption={t("at {velocity} m/s", {
              velocity: formatVelocity(model.minimum),
            })}
          />
          <StatDivider />
          <StatFigure
            label={t("Peak power")}
            color={powerHex()}
            value={t("{watts} W", { watts: formatWatts(peakWatts) })}
            caption={t("at {load}", { load: formatLoad(peakPowerLoad) })}
          />
          <StatDivider wideOnly />
          {/* The minimum velocity threshold: the velocity the profile puts
              at 1RM. */}
          <StatFigure
            label={t("MVT")}
            color={velocityHex()}
            value={formatVelocity(model.minimum)}
            caption={t("m/s at 1RM")}
            wideOnly
          />
        </div>
      </div>

      <ProfileChart
        rm1Band={
          model.cA1 < 0 && oneRepMax > 0
            ? SESSION_RM1_VELOCITY_GATE * oneRepMax * -model.cA1
            : null
        }
        velocityAtPct={velocityAtPct}
        powerAtPct={powerAtPct}
        velocityTodayAtPct={velocityTodayAtPct}
        maxVelocity={Math.max(model.cA0, ...measured.map((r) => r.velocity))}
        peakWatts={peakWatts}
        peakPowerPct={peakPowerPct}
        oneRepMaxPct={toPct(oneRepMax)}
        xMaxDisplay={loadAxis.toDisplay(xMax)}
        loadUnit={loadAxis.unit}
        markerPct={markerPct}
        measured={measured.map((r) => ({
          pct: clampPct(toPct(r.load)),
          velocity: r.velocity,
        }))}
        hoverPct={hoverPct}
        onHover={setHoverPct}
        // The readout's load always with one decimal ("34.0 kg"), in the
        // load axis's unit.
        formatLoadAtPct={(pct) =>
          `${loadAxis.toDisplay(loadAtPct(pct)).toFixed(1)} ${loadAxis.unit}`
        }
      />

      {/* The figures above carry the curves' and zones' colours (1RM =
          peak-load zone, peak power, max velocity), so the legend keeps only
          what they don't explain. */}
      <div className="body-small mt-3 flex flex-wrap gap-x-4 gap-y-1 text-foreground-muted">
        {measured.length > 0 ? (
          <span className="flex items-center gap-1.5">
            <span
              aria-hidden
              className="size-2 rounded-full bg-foreground-default opacity-50"
            />
            {t("Measured reps")}
          </span>
        ) : null}
        {model.cA1 < 0 ? (
          <LegendSwatch color={velocityHex()} label={t("Session 1RM range")} />
        ) : null}
        {velocityTodayAtPct ? (
          <LegendLine color={velocityHex()} label={t("Today")} dashed />
        ) : null}
      </div>
    </SessionDetailsCard>
  );
}

function LegendLine({
  color,
  label,
  dashed = false,
}: {
  color: string;
  label: string;
  dashed?: boolean;
}) {
  return (
    <span className="flex items-center gap-1.5">
      <span
        aria-hidden
        className="h-0 w-3"
        style={{ borderTop: `2px ${dashed ? "dashed" : "solid"} ${color}` }}
      />
      {label}
    </span>
  );
}

function LegendSwatch({ color, label }: { color: string; label: string }) {
  return (
    <span className="flex items-center gap-1.5">
      <span
        aria-hidden
        className="size-2.5 rounded-sm"
        style={{ backgroundColor: color, opacity: 0.35 }}
      />
      {label}
    </span>
  );
}

const TICK =
  "body-small pointer-events-none absolute whitespace-nowrap tabular-nums text-foreground-muted";

// The profile in a 5:2 plot: velocity against the left axis, power against the
// right, load along the bottom with faint lines at its ticks. Shapes are SVG in
// a stretched 100×100 box (strokes keep their width via `non-scaling-stroke`);
// labels and markers are HTML positioned by percent, so text never stretches
// with the box.
function ProfileChart({
  rm1Band,
  velocityAtPct,
  powerAtPct,
  velocityTodayAtPct,
  maxVelocity,
  peakWatts,
  peakPowerPct,
  oneRepMaxPct,
  xMaxDisplay,
  loadUnit,
  markerPct,
  measured,
  hoverPct,
  onHover,
  formatLoadAtPct,
}: {
  // Half-height (m/s) of the session-1RM band around the profile.
  rm1Band: number | null;
  velocityAtPct: (pct: number) => number;
  powerAtPct: (pct: number) => number;
  velocityTodayAtPct: ((pct: number) => number) | null;
  // The highest velocity / power to fit under the axes' tops.
  maxVelocity: number;
  peakWatts: number;
  // Positions on the load axis, 0–100.
  peakPowerPct: number;
  oneRepMaxPct: number;
  // The load axis's end in display units.
  xMaxDisplay: number;
  loadUnit: string;
  markerPct: number | null;
  measured: { pct: number; velocity: number }[];
  hoverPct: number | null;
  onHover: (pct: number | null) => void;
  formatLoadAtPct: (pct: number) => string;
}) {
  const { t } = useTranslation();

  const velocityTicks = niceTicks(maxVelocity * 1.05, 5);
  const powerTicks = niceTicks(peakWatts * 1.05, 4);
  // A flat plot holds about five numbers per side; past that every other
  // tick is labelled (the curve still runs against all of them).
  const labelled = (ticks: number[]) =>
    ticks.length > 5 ? ticks.filter((_, i) => i % 2 === 0) : ticks;
  const velocityTop = velocityTicks[velocityTicks.length - 1] || 1;
  const powerTop = powerTicks[powerTicks.length - 1] || 1;
  // Load ticks in display units, inside 0…xMax.
  const loadStep = niceStep(xMaxDisplay, 5);
  const loadTicks: number[] = [];
  for (let v = 0; v <= xMaxDisplay + 1e-6; v += loadStep) {
    loadTicks.push(Number(v.toFixed(6)));
  }
  const loadPct = (display: number) =>
    xMaxDisplay > 0 ? (display / xMaxDisplay) * 100 : 0;

  const yVelocity = (v: number) => 100 - clampPct((v / velocityTop) * 100);
  const yPower = (w: number) => 100 - clampPct((w / powerTop) * 100);
  const velocityY = (pct: number) => yVelocity(velocityAtPct(pct));
  const powerY = (pct: number) => yPower(powerAtPct(pct));
  const curvePoints = (y: (pct: number) => number, from = 0, to = 100) =>
    Array.from({ length: 41 }, (_, i) => {
      const pct = from + ((to - from) * i) / 40;
      return `${pct},${y(pct)}`;
    }).join(" ");
  // A band of ±`half` m/s around the profile, clipped to the plot.
  const bandAround = (half: number) => {
    const upper = curvePoints((pct) => yVelocity(velocityAtPct(pct) + half));
    const lower = Array.from({ length: 41 }, (_, i) => {
      const pct = 100 - (100 * i) / 40;
      return `${pct},${yVelocity(Math.max(0, velocityAtPct(pct) - half))}`;
    }).join(" ");
    return `${upper} ${lower}`;
  };
  // A zone filled from the baseline up to the velocity curve.
  const zoneUnderVelocity = (from: number, to: number) =>
    `${from},100 ${curvePoints(velocityY, from, to)} ${to},100`;

  // The zones are shares of the model's 1RM, placed on the load axis.
  const zoneHalf = (PEAK_POWER_ZONE_HALF_WIDTH_PCT / 100) * oneRepMaxPct;
  const powerStart = clampPct(peakPowerPct - zoneHalf);
  const powerEnd = clampPct(peakPowerPct + zoneHalf);
  const peakLoadStart = clampPct((PEAK_LOAD_ZONE_PCT / 100) * oneRepMaxPct);

  function readPointer(e: PointerEvent<HTMLDivElement>) {
    const rect = e.currentTarget.getBoundingClientRect();
    if (rect.width === 0) return;
    onHover(clampPct(((e.clientX - rect.left) / rect.width) * 100));
  }

  const curve = (points: string, color: string, dashed = false) => (
    <polyline
      points={points}
      fill="none"
      stroke={color}
      strokeWidth={dashed ? 1.5 : 2}
      strokeDasharray={dashed ? "5 4" : undefined}
      strokeLinecap="round"
      strokeLinejoin="round"
      vectorEffect="non-scaling-stroke"
    />
  );

  return (
    <div className="mt-4">
      {/* Side margins hold the two axes' numbers, the bottom one the load's. */}
      <div
        className="relative mb-6 ml-9 mr-9 aspect-[5/2] touch-pan-y select-none"
        onPointerMove={readPointer}
        onPointerDown={readPointer}
        onPointerLeave={() => onHover(null)}
        onPointerCancel={() => onHover(null)}
      >
        <svg
          viewBox="0 0 100 100"
          preserveAspectRatio="none"
          className="absolute inset-0 size-full overflow-visible"
          aria-hidden
        >
          {loadTicks.map((tick) => (
            <line
              key={tick}
              x1={loadPct(tick)}
              x2={loadPct(tick)}
              y1={0}
              y2={100}
              className="stroke-surface-stroke-muted"
              strokeOpacity={0.6}
              strokeWidth={1}
              vectorEffect="non-scaling-stroke"
            />
          ))}
          <polygon
            points={zoneUnderVelocity(powerStart, powerEnd)}
            fill={powerHex()}
            fillOpacity={0.22}
          />
          <polygon
            points={zoneUnderVelocity(peakLoadStart, clampPct(oneRepMaxPct))}
            fill={forceHex()}
            fillOpacity={0.22}
          />
          {rm1Band ? (
            <polygon
              points={bandAround(rm1Band)}
              fill={velocityHex()}
              fillOpacity={0.12}
            />
          ) : null}
          {/* Baseline and the power axis on the right. */}
          <line
            x1={0}
            x2={100}
            y1={100}
            y2={100}
            className="stroke-surface-stroke"
            strokeWidth={1}
            vectorEffect="non-scaling-stroke"
          />
          <line
            x1={100}
            x2={100}
            y1={0}
            y2={100}
            className="stroke-surface-stroke"
            strokeWidth={1}
            vectorEffect="non-scaling-stroke"
          />
          {hoverPct != null ? (
            <line
              x1={hoverPct}
              x2={hoverPct}
              y1={0}
              y2={100}
              className="stroke-foreground-muted"
              strokeWidth={1}
              strokeDasharray="3 3"
              vectorEffect="non-scaling-stroke"
            />
          ) : null}
          {markerPct != null ? (
            <>
              <line
                x1={markerPct}
                x2={markerPct}
                y1={0}
                y2={100}
                className="stroke-primary-fill"
                strokeWidth={1.5}
                vectorEffect="non-scaling-stroke"
              />
              <line
                x1={0}
                x2={markerPct}
                y1={velocityY(markerPct)}
                y2={velocityY(markerPct)}
                stroke={velocityHex()}
                strokeWidth={1}
                strokeDasharray="3 3"
                vectorEffect="non-scaling-stroke"
              />
              <line
                x1={markerPct}
                x2={100}
                y1={powerY(markerPct)}
                y2={powerY(markerPct)}
                stroke={powerHex()}
                strokeWidth={1}
                strokeDasharray="3 3"
                vectorEffect="non-scaling-stroke"
              />
            </>
          ) : null}
          {velocityTodayAtPct
            ? curve(
                curvePoints((p) => yVelocity(velocityTodayAtPct(p))),
                velocityHex(),
                true,
              )
            : null}
          {curve(curvePoints(powerY), powerHex())}
          {curve(curvePoints(velocityY), velocityHex())}
        </svg>

        {/* Axes: velocity left, power right, load below. */}
        {labelled(velocityTicks).map((tick) => (
          <span
            key={`v${tick}`}
            className={`${TICK} right-full mr-2 -translate-y-1/2`}
            style={{ top: `${100 - (tick / velocityTop) * 100}%` }}
          >
            {tick.toFixed(2)}
          </span>
        ))}
        {labelled(powerTicks).map((tick) => (
          <span
            key={`p${tick}`}
            className={`${TICK} left-full ml-2 -translate-y-1/2`}
            style={{ top: `${100 - (tick / powerTop) * 100}%` }}
          >
            {Math.round(tick)}
          </span>
        ))}
        {loadTicks.map((tick) => (
          <span
            key={`l${tick}`}
            className={`${TICK} top-full mt-1 -translate-x-1/2`}
            style={{ left: `${loadPct(tick)}%` }}
          >
            {Number.isInteger(tick) ? tick : tick.toFixed(1)}
          </span>
        ))}

        {/* The measured reps — off the curve where the athlete moved faster
            or slower than the profile says. */}
        {measured.map((point, i) => (
          <Dot
            key={i}
            left={point.pct}
            top={yVelocity(point.velocity)}
            className="size-2 bg-foreground-default opacity-50"
          />
        ))}
        {markerPct != null ? (
          <>
            {/* In the curves' colours, as the technique chart's crosshair
                points — the measured reps stay ink-coloured. */}
            <Dot
              left={markerPct}
              top={velocityY(markerPct)}
              className="size-2.5 ring-2 ring-surface-base"
              color={velocityHex()}
            />
            <Dot
              left={markerPct}
              top={powerY(markerPct)}
              className="size-2.5 ring-2 ring-surface-base"
              color={powerHex()}
            />
          </>
        ) : null}

        {hoverPct != null ? (
          <>
            <Ring
              left={hoverPct}
              top={velocityY(hoverPct)}
              color={velocityHex()}
            />
            <Ring left={hoverPct} top={powerY(hoverPct)} color={powerHex()} />
            {/* The readout travels with the indicator, on its roomier side. */}
            <div
              className="pointer-events-none absolute top-2 rounded-lg bg-surface-base px-2.5 py-1.5 shadow-floating ring-1 ring-surface-stroke-muted"
              style={{
                left: `${hoverPct}%`,
                transform:
                  hoverPct > 55
                    ? "translateX(calc(-100% - 10px))"
                    : "translateX(10px)",
              }}
            >
              {/* Load, then velocity (profile / today), then power — no
                  names and no colour marks; every number in tabular digits. */}
              <span className="body-small block whitespace-nowrap font-semibold tabular-nums text-foreground-default">
                {formatLoadAtPct(hoverPct)}
              </span>
              <span className="body-small block whitespace-nowrap tabular-nums text-foreground-default">
                {formatVelocity(velocityAtPct(hoverPct))}
                {velocityTodayAtPct ? (
                  <>
                    {" / "}
                    <span className="font-semibold">
                      {formatVelocity(velocityTodayAtPct(hoverPct))}
                    </span>
                  </>
                ) : null}{" "}
                {t("m/s")}
              </span>
              <span className="body-small block whitespace-nowrap tabular-nums text-foreground-default">
                {t("{watts} W", { watts: formatWatts(powerAtPct(hoverPct)) })}
              </span>
            </div>
          </>
        ) : null}
      </div>
      <p className="body-small text-center text-foreground-muted">
        {t("Load ({unit})", { unit: loadUnit })}
      </p>
    </div>
  );
}

function Dot({
  left,
  top,
  className,
  color,
}: {
  left: number;
  top: number;
  className: string;
  /** A fill colour; without it the class sets one. */
  color?: string;
}) {
  return (
    <span
      aria-hidden
      className={`pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 rounded-full ${className}`}
      style={{ left: `${left}%`, top: `${top}%`, backgroundColor: color }}
    />
  );
}

// The hover position on a curve: a hollow ring in the curve's colour.
function Ring({
  left,
  top,
  color,
}: {
  left: number;
  top: number;
  color: string;
}) {
  return (
    <span
      aria-hidden
      className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 bg-surface-base/60"
      style={{ left: `${left}%`, top: `${top}%`, borderColor: color }}
    />
  );
}
