import type { ReactNode } from 'react';
import { cn } from '@/lib/cn';

/**
 * Living-Codex display primitives: a thin HP/resource Meter, a tinted Badge, an
 * initials Avatar, and an embossed ability-score StatCoin. Token-driven so they
 * follow the theme + the --app-accent-hue reskin.
 */

export function Meter({ value, max, tone, height = 7 }: { value: number; max: number; tone?: string; height?: number }) {
  const pct = Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0));
  return (
    <div className="overflow-hidden rounded-full border border-line bg-surface-2" style={{ height }}>
      <span className="block h-full rounded-full transition-[width] duration-300 ease-out" style={{ width: `${pct}%`, background: tone ?? 'var(--app-accent)' }} />
    </div>
  );
}

export type BadgeTone = 'default' | 'gold' | 'ember' | 'verdigris' | 'arcane' | 'success';
const badgeTone: Record<BadgeTone, string> = {
  default: 'border-line text-muted bg-elevated',
  gold: 'border-accent/60 text-accent-deep bg-accent-glow',
  ember: 'border-danger/45 text-danger bg-danger-glow',
  verdigris: 'border-verdigris/45 text-verdigris',
  arcane: 'border-info/45 text-info',
  success: 'border-success/45 text-success',
};
export function Badge({ tone = 'default', children, className }: { tone?: BadgeTone; children: ReactNode; className?: string }) {
  return <span className={cn('inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium', badgeTone[tone], className)}>{children}</span>;
}

export function Avatar({ name, size = 40, tone }: { name: string; size?: number; tone?: string }) {
  const initials = name.split(/\s+/).map((w) => w[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || '?';
  const t = tone ?? 'var(--app-accent)';
  return (
    <div
      className="grid shrink-0 place-items-center rounded-full font-display font-semibold"
      style={{
        width: size, height: size, fontSize: size * 0.36, color: t,
        background: `color-mix(in oklch, ${t}, var(--app-panel) 78%)`,
        border: `1.5px solid color-mix(in oklch, ${t}, transparent 55%)`,
      }}
      aria-hidden
    >
      {initials}
    </div>
  );
}

export function StatCoin({ label, value, mod, active }: { label: string; value: number | string; mod: string; active?: boolean }) {
  return (
    <div className={cn('flex flex-col items-center gap-0.5 rounded-xl border bg-panel px-2 py-2 text-center', active ? 'border-accent shadow-[0_0_0_3px_var(--app-accent-glow)]' : 'border-line')}>
      <div className="smallcaps" style={{ fontSize: 10 }}>{label}</div>
      <div className="font-display font-semibold leading-none text-ink" style={{ fontSize: 26 }}>{value}</div>
      <div className="font-mono text-[13px] font-semibold text-accent-deep">{mod}</div>
    </div>
  );
}
