import { archetypeColor } from '@/lib/archetypes';
import ArchetypeBadge from '@/components/vyndr/ArchetypeBadge';

export interface BlendSegment {
  archetype: string;
  weight: number;
}

interface ArchetypeBlendProps {
  blend: BlendSegment[];
  size?: 'sm' | 'md';
  showLegend?: boolean;
  caption?: string;
}

/**
 * ArchetypeBlend (Session 42) — the production-DNA bar. Ported from the
 * design's ArchetypeBlend.dc.html. Each segment's width is that archetype's
 * share of the player's statistical value; the widest is PRIMARY.
 */
export default function ArchetypeBlend({
  blend,
  size = 'md',
  showLegend = true,
  caption = '',
}: ArchetypeBlendProps) {
  const sm = size === 'sm';
  const raw = (Array.isArray(blend) ? blend : []).slice(0, 4);
  const total = raw.reduce((s, b) => s + (Number(b.weight) || 0), 0) || 1;
  const pct = (w: number) => Math.round(((Number(w) || 0) / total) * 100);

  const barH = sm ? 6 : 10;
  const gap = sm ? 7 : 13;
  const pctSize = sm ? 10 : 13;
  const capSize = sm ? 11 : 12.5;
  const roleW = sm ? 54 : 66;
  const ROLECOL = ['#C6CBD6', '#6B6F7E', '#6B6F7E', '#5A5E6B'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap, width: '100%' }}>
      <div style={{ position: 'relative', display: 'flex', height: barH, borderRadius: 99, overflow: 'hidden', gap: 1.5, background: '#07070D', border: '1px solid #15151F' }}>
        {raw.map((b, i) => (
          <span
            key={i}
            title={`${b.archetype} — ${pct(b.weight)}% of production profile`}
            style={{
              width: `${(Math.max(0, Number(b.weight) || 0) / total) * 100}%`,
              background: archetypeColor(b.archetype),
              boxShadow: `inset 0 0 0 100px ${i === 0 ? 'transparent' : 'rgba(0,0,0,0.18)'}`,
            }}
          />
        ))}
      </div>

      {showLegend && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '9px 16px', alignItems: 'center' }}>
          {raw.map((b, i) => (
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span className="mono" style={{ fontSize: 8, fontWeight: 700, letterSpacing: '0.08em', color: ROLECOL[i] || '#5A5E6B', width: roleW, textAlign: 'right' }}>
                {i === 0 ? 'PRIMARY' : i === raw.length - 1 && raw.length > 2 ? 'TERTIARY' : 'SUPPORTING'}
              </span>
              <ArchetypeBadge archetype={b.archetype} size={sm ? 'sm' : 'md'} variant={i === 0 ? 'full' : 'ghost'} />
              <span className="mono" style={{ fontSize: pctSize, fontWeight: 700, color: i === 0 ? '#FFFFFF' : '#9499A8' }}>
                {pct(b.weight)}%
              </span>
            </span>
          ))}
        </div>
      )}

      {caption && (
        <div style={{ fontFamily: 'var(--sans)', fontSize: capSize, lineHeight: 1.5, color: '#7E8390' }}>{caption}</div>
      )}
    </div>
  );
}
