import { memo } from "react";

import FormattedNumber, { type FormattedNumberProps } from "./FormattedNumber";

export type ScoreProps = PrecomputedScoreProps | ComputedScoreProps;

export interface PrecomputedScoreProps {
	/** The score to display. */
	score: number;
	/** Forwarded to FormattedNumber. */
	compact?: FormattedNumberProps["compact"];
	/** Whether to show the unit "Benis" after the number. Defaults to `false`. */
	showUnit?: boolean;
}

export interface ComputedScoreProps {
	/** number of upvotes */
	up: number;
	/** number of downvotes */
	down: number;
	/** Forwarded to FormattedNumber. */
	compact?: FormattedNumberProps["compact"];
	/** Whether to show the unit "Benis" after the number. Defaults to `false`. */
	showUnit?: boolean;

	/** Used as a discriminator between `ComputedScoreProps` and `PrecomputedScoreProps` */
	score?: undefined;
}

const style = {
	wordBreak: "keep-all",
} as const;

const formatter = new Intl.NumberFormat("de");

/**
 * Base-component that just displays a score. If you need to handle logic with hidden scores, use `MaybeHiddenScore`.
 *
 * Using <Score />, the score is never hidden. This is useful for displaying scores in the Profile etc.
 */
export default memo(function Score(props: ScoreProps) {
	const score =
		typeof props.score !== "undefined"
			? props.score
			: props.up - props.down;
	return (
		<span
			title={
				props.score === undefined
					? `${formatter.format(props.up)} plus, ${formatter.format(props.down)} minus`
					: undefined
			}
			style={style}
		>
			<FormattedNumber value={score} compact={props.compact} />
			{props.showUnit && " Benis"}
		</span>
	);
});
