import { BONE_WEIGHT_READINGS, formatLiang } from '@/lib/bazi/boneWeight';
import { DIRECTION_DEGREES, DIRECTION_NAMES, directionKinds, type KuaResult } from '@/lib/bazi/kua';
import { useLocale, useMessages } from '@/i18n/client';
import { cn } from '@/lib/cn';

const MIN = 21;
const MAX = 71;

/** A horizontal scale from 2,1 to 7,1 tael split into the reading bands, with the person's weight marked. */
export function BoneWeightScale({ totalQian }: { totalQian: number }) {
  const locale = useLocale();
  const t = useMessages().insights;
  const readings = BONE_WEIGHT_READINGS[locale];
  const pct = (q: number) => ((q - MIN) / (MAX - MIN)) * 100;
  const at = Math.min(100, Math.max(0, pct(totalQian)));
  return (
    <div className="pt-9">
      <div className="relative">
        <div
          className="absolute -top-9 flex -translate-x-1/2 flex-col items-center"
          style={{ left: `${at}%` }}
        >
          <span className="rounded-full bg-ink px-2.5 py-1 text-xs font-semibold text-white tabular-nums">
            {formatLiang(totalQian).liang}
          </span>
          <span className="h-2 w-px bg-ink" />
        </div>
        <div className="flex h-3 overflow-hidden rounded-full">
          {readings.map((r, i) => (
            <div
              key={r.min}
              className="h-full"
              style={{
                width: `${((r.max - r.min + 1) / (MAX - MIN + 1)) * 100}%`,
                backgroundColor: `hsl(${30 + i * 4}, ${55 + i * 3}%, ${82 - i * 5}%)`,
              }}
              title={`${formatLiang(r.min).liang}–${formatLiang(r.max).liang}: ${r.title}`}
            />
          ))}
        </div>
      </div>
      <div className="mt-2 flex justify-between text-[11px] text-subtle tabular-nums">
        <span>2,1 · {t.light}</span>
        <span>4,6</span>
        <span>{t.heavy} · 7,1</span>
      </div>
    </div>
  );
}

/** Eight-direction compass: good directions in green tones, the rest in red, labelled with their Ba Zhai name. */
export function KuaCompass({ kua, className }: { kua: KuaResult; className?: string }) {
  const locale = useLocale();
  const t = useMessages().insights;
  const kinds = directionKinds(locale);
  const names = DIRECTION_NAMES[locale];
  const c = 150;
  const R = 128;
  const r0 = 42;
  const polar = (deg: number, rad: number) => {
    const a = ((deg - 90) * Math.PI) / 180;
    return { x: c + rad * Math.cos(a), y: c + rad * Math.sin(a) };
  };
  const wedge = (deg: number) => {
    const a1 = polar(deg - 22.5, R);
    const a2 = polar(deg + 22.5, R);
    const b1 = polar(deg + 22.5, r0);
    const b2 = polar(deg - 22.5, r0);
    return `M${a1.x} ${a1.y} A${R} ${R} 0 0 1 ${a2.x} ${a2.y} L${b1.x} ${b1.y} A${r0} ${r0} 0 0 0 ${b2.x} ${b2.y} Z`;
  };
  const GOOD = ['#15803D', '#22A35A', '#4CBB7A', '#86D3A4'];
  const BAD = ['#F4A4A9', '#EC7A82', '#DF4C57', '#B91C2B'];

  return (
    <svg viewBox="0 0 300 300" className={className} role="img" aria-label={t.compass}>
      {kua.directions.map(({ kind, direction }) => {
        const info = kinds[kind];
        const deg = DIRECTION_DEGREES[direction];
        const fill = info.good ? GOOD[info.rank - 1] : BAD[info.rank - 5];
        // Stack the abbreviation over the Ba Zhai name at the wedge's centre.
        const mid = polar(deg, (R + r0) / 2 + 4);
        const dir = { x: mid.x, y: mid.y - 6 };
        const label = { x: mid.x, y: mid.y + 9 };
        return (
          <g key={kind}>
            <path d={wedge(deg)} fill={fill} stroke="#fff" strokeWidth="2" />
            <text x={dir.x} y={dir.y} textAnchor="middle" dominantBaseline="middle" className="fill-white text-[13px] font-bold">
              {names[direction].short}
            </text>
            <text x={label.x} y={label.y} textAnchor="middle" dominantBaseline="middle" className="fill-white text-[8.5px] font-medium">
              {info.name}
            </text>
          </g>
        );
      })}
      <circle cx={c} cy={c} r={r0 - 4} className="fill-surface" stroke="#E7E9F0" />
      <text x={c} y={c - 6} textAnchor="middle" className="fill-subtle text-[9px] tracking-widest uppercase">
        {t.kua}
      </text>
      <text x={c} y={c + 16} textAnchor="middle" className="fill-ink text-[26px] font-semibold">
        {kua.kua}
      </text>
    </svg>
  );
}

export function DirectionBadge({ good, className, children }: { good: boolean; className?: string; children: React.ReactNode }) {
  return (
    <span
      className={cn(
        'rounded-full px-2 py-0.5 text-[11px] font-medium',
        good ? 'bg-wood/10 text-wood' : 'bg-fire/10 text-fire',
        className,
      )}
    >
      {children}
    </span>
  );
}
