import type { ReactNode } from "react";
import { WALL_TEXT } from "./wall-type";

// The look of the Live Hub's surfaces, as recipes. A screen of the Live Hub
// takes its containers, its labels and its numbers from here and sets none of
// its own, so the hub, the lobby, the boards, the result and the gym display
// are drawn by one hand — and a change of the look is a change of this file.
//
// The rules behind the recipes:
//
//   1. One hero per region. In a card, a row or a scene exactly one thing is
//      the largest: the number of a lift, the code of a lobby. Everything
//      else steps down by at least a size.
//   2. Round means it can be pressed. A button, a tab, a choice and an avatar
//      are round. What only informs has corners: a panel, a row, a chip, a
//      place. So nothing that looks like a button is a label.
//   3. A container is drawn once. A panel has one line around it and never
//      holds a second panel: groups inside it are parted by a rule.
//   4. A number is a figure: semibold, tabular, tight, with its unit small and
//      muted behind it. A label is small capitals. There is no third style.
//   5. Colour is meaning (`tones.ts`), and a row carries at most one.

/** The class recipes. Combine one with layout classes; do not restyle it. */
export const LOOK = {
  /** A container: the card of a lift, a list with its title, a form's group. */
  panel: "rounded-2xl border border-surface-stroke bg-surface-base",
  /** One of several equals in a list: a row of a board, a device, a lift. */
  row: "rounded-2xl bg-surface-base",
  /** The line that parts two groups of one panel, and two rows of a table. */
  rule: "border-surface-stroke",
  /** The label over a group or over a value: small capitals. */
  eyebrow: "stat-small uppercase tracking-[0.08em] text-foreground-muted",
  /** A second line under a name or a number. */
  caption: "body-small text-foreground-muted",
  /** A name: of an athlete, a device, a session. */
  name: "heading-normal text-foreground-default",
  /** The label on a gym display: the wall's label size, in small capitals. */
  wallEyebrow: `${WALL_TEXT.label} uppercase tracking-[0.06em] text-foreground-muted`,
  /** A second line on a gym display: the wall's label size, quiet. */
  wallCaption: `${WALL_TEXT.label} font-normal text-foreground-muted`,
} as const;

// ── A number with its unit ───────────────────────────────────────────────────

/**
 * How large a figure is.
 *
 * On a page: `hero` (the one number a screen is about), `large` (the number
 * of a card), `medium` (a value in a group of values), `small` (a value in a
 * row of a table).
 *
 * On a gym display the sizes are the wall's (`wall-type.ts`): `wallLift`,
 * `wallRow`, `wallLine`.
 */
export type FigureSize =
  | "hero"
  | "large"
  | "medium"
  | "small"
  | "wallLift"
  | "wallRow"
  | "wallLine";

// A figure that stands in a column (a row of a board, a value in a table) has
// tabular digits, so the numbers line up under each other. A figure that
// stands alone — the number of a card, of a scene — has the font's own digits:
// tabular ones leave a gap around every 1, and at that size "110" falls apart.
const FIGURE: Record<FigureSize, { number: string; unit: string }> = {
  hero: {
    number:
      "text-[length:calc(56px*var(--text-scale,1))] font-semibold leading-none tracking-[-0.03em] proportional-nums",
    unit: "heading-normal ml-[0.25em]",
  },
  large: {
    number:
      "text-[length:calc(34px*var(--text-scale,1))] font-semibold leading-none tracking-[-0.025em] proportional-nums",
    unit: "heading-section ml-[0.3em]",
  },
  medium: {
    number: "stat-medium-digits tracking-[-0.02em]",
    unit: "stat-small ml-[0.3em]",
  },
  small: {
    number: "stat-normal tracking-[-0.01em]",
    unit: "stat-small ml-[0.3em]",
  },
  wallLift: {
    // After the role's own `tabular-nums`, so it wins.
    number: `${WALL_TEXT.liftNumber} tracking-[-0.03em] [font-variant-numeric:proportional-nums]`,
    unit: `${WALL_TEXT.liftLine} ml-[0.25em]`,
  },
  wallRow: {
    number: `${WALL_TEXT.rowNumber} tracking-[-0.025em]`,
    unit: `${WALL_TEXT.label} ml-[0.3em]`,
  },
  wallLine: {
    number: `${WALL_TEXT.liftLine} font-semibold tabular-nums tracking-[-0.01em]`,
    unit: `${WALL_TEXT.label} ml-[0.3em]`,
  },
};

/**
 * A number with its unit: the number semibold, the unit small and muted
 * behind it on the same baseline. Every number of the Live Hub is drawn
 * by this part, so "172.5 KG" looks the same in a row, on a card and on a
 * wall.
 *
 * A figure never wraps and is never cut: give it the room, or a smaller size.
 */
export function Figure({
  value,
  unit,
  size = "medium",
  muted = false,
  minChars = 0,
  className = "",
}: {
  /** The number as it prints. A dash stands for "none". */
  value: ReactNode;
  unit?: ReactNode;
  size?: FigureSize;
  /** A figure that is not the point: a value before, an attempt that is past. */
  muted?: boolean;
  /**
   * The room the number keeps, in characters, with the number set to its
   * right edge: give every figure of a column the length of the longest, and
   * the numbers and what stands in front of them line up.
   */
  minChars?: number;
  className?: string;
}) {
  const look = FIGURE[size];
  return (
    <span
      className={`inline-flex shrink-0 items-baseline whitespace-nowrap ${className}`}
    >
      <span
        className={`${look.number} ${
          muted ? "text-foreground-muted" : "text-foreground-default"
        } ${minChars > 0 ? "inline-block text-right" : ""}`}
        style={minChars > 0 ? { minWidth: `${minChars}ch` } : undefined}
      >
        {value}
      </span>
      {unit != null && unit !== "" && (
        <span className={`font-normal text-foreground-muted ${look.unit}`}>
          {unit}
        </span>
      )}
    </span>
  );
}

// ── A label ──────────────────────────────────────────────────────────────────

/** The label over a group or a value. One line, never wrapped. */
export function Eyebrow({
  children,
  className = "",
  as: Tag = "p",
}: {
  children: ReactNode;
  className?: string;
  /** A fixed choice of tags: an open `ElementType` does not type-check in
   *  every app that takes the part. */
  as?: "p" | "span" | "div" | "h2" | "h3" | "h4" | "dt";
}) {
  return (
    <Tag className={`truncate ${LOOK.eyebrow} ${className}`}>{children}</Tag>
  );
}

// ── A value with its label ───────────────────────────────────────────────────

// The sizes of a gym display. A value at one of them has its label and its
// caption at the wall's label size too: a label at the page's 11 px under a
// number sized for a hall cannot be read from where the number can.
const WALL_SIZES: ReadonlySet<FigureSize> = new Set([
  "wallLift",
  "wallRow",
  "wallLine",
]);

/**
 * A value under its label: "PEAK VELOCITY" over "1.92 M/S". For a group of
 * values that stand side by side; the group is a `<dl>`.
 *
 * `caption` is one quiet line under the value: what it is measured against
 * ("vs 82.5 kg last time"), whom it belongs to, a share ("3 of 8 athletes").
 * It may wrap; an empty one draws nothing.
 *
 * At a wall size (`wallLift`, `wallRow`, `wallLine`) the label and the caption
 * take the wall's label size (`wall-type.ts`) and follow the display's
 * profile with the number.
 */
export function Stat({
  label,
  value,
  unit,
  caption,
  size = "medium",
  className = "",
  testID,
}: {
  label: ReactNode;
  value: ReactNode;
  unit?: ReactNode;
  /** A second, quiet line under the value. */
  caption?: ReactNode;
  size?: FigureSize;
  className?: string;
  /** Becomes `data-testid`. */
  testID?: string;
}) {
  const wall = WALL_SIZES.has(size);
  const captioned = caption != null && caption !== "";
  return (
    <div
      data-testid={testID}
      // The wall's label has its own line height, so it needs no gap.
      className={`flex min-w-0 flex-col ${wall ? "" : "gap-1"} ${className}`}
    >
      <dt className={`truncate ${wall ? LOOK.wallEyebrow : LOOK.eyebrow}`}>
        {label}
      </dt>
      <dd className={captioned ? "min-w-0" : undefined}>
        <Figure value={value} unit={unit} size={size} />
        {captioned && (
          <p className={wall ? LOOK.wallCaption : `${LOOK.caption} mt-1`}>
            {caption}
          </p>
        )}
      </dd>
    </div>
  );
}

// ── A container ──────────────────────────────────────────────────────────────

const PAD = { none: "", sm: "p-3", md: "p-4", lg: "p-6" } as const;

/**
 * A container with one line around it. `title` is its label, `aside` stands
 * at the right of the title (a count, a small control). A panel never holds a
 * panel: part its groups with {@link LOOK.rule}.
 */
export function Panel({
  title,
  aside,
  pad = "md",
  className = "",
  children,
  as: Tag = "section",
  testID,
}: {
  title?: ReactNode;
  aside?: ReactNode;
  pad?: keyof typeof PAD;
  className?: string;
  children: ReactNode;
  as?: "section" | "div" | "aside" | "article" | "li";
  /** Becomes `data-testid`. */
  testID?: string;
}) {
  return (
    <Tag
      data-testid={testID}
      className={`${LOOK.panel} ${PAD[pad]} ${className}`}
    >
      {(title != null || aside != null) && (
        <div className="mb-3 flex shrink-0 items-center justify-between gap-3">
          {title != null ? <Eyebrow>{title}</Eyebrow> : <span />}
          {aside}
        </div>
      )}
      {children}
    </Tag>
  );
}
