// Shared UI primitives — chips, confidence ring, signal bars, logo mark, etc.

function MFLogo({ size = 18, color = '#c2410c' }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 18 18">
        <rect x="0" y="0" width="8" height="8" fill={color} />
        <rect x="10" y="0" width="8" height="8" fill="none" stroke={color} strokeWidth="1.5" />
        <rect x="0" y="10" width="8" height="8" fill="none" stroke={color} strokeWidth="1.5" />
        <rect x="10" y="10" width="8" height="8" fill={color} />
        <line x1="4" y1="8" x2="4" y2="10" stroke={color} strokeWidth="1.5" />
        <line x1="14" y1="8" x2="14" y2="10" stroke={color} strokeWidth="1.5" />
        <line x1="8" y1="4" x2="10" y2="4" stroke={color} strokeWidth="1.5" />
        <line x1="8" y1="14" x2="10" y2="14" stroke={color} strokeWidth="1.5" />
      </svg>
      <span className="mono" style={{
        fontSize: 12, fontWeight: 600, letterSpacing: '0.14em',
        textTransform: 'uppercase',
      }}>MarketForge</span>
    </span>
  );
}

function StatusChip({ status, label }) {
  const map = {
    match:   { cls: 'ok',   text: label || 'Match' },
    exceeds: { cls: 'info', text: label || 'Exceeds' },
    partial: { cls: 'warn', text: label || 'Partial' },
    mismatch:{ cls: 'miss', text: label || 'Mismatch' },
    unknown: { cls: 'accent', text: label || 'Missing data' },
  };
  const { cls, text } = map[status] || map.unknown;
  return (
    <span className={`chip ${cls}`}>
      <span className="dot" /> {text}
    </span>
  );
}

function ConfidenceRing({ value, size = 128, stroke = 10, label = 'Confidence', delta = null }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(100, value));
  const dash = (pct / 100) * c;
  const color = pct >= 80 ? 'var(--ok)' : pct >= 60 ? 'var(--warn)' : 'var(--miss)';
  return (
    <div style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
      <div style={{ position: 'relative', width: size, height: size }}>
        <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
          <circle cx={size/2} cy={size/2} r={r} stroke="var(--line)" strokeWidth={stroke} fill="none" />
          <circle
            cx={size/2} cy={size/2} r={r}
            stroke={color} strokeWidth={stroke} fill="none"
            strokeDasharray={`${dash} ${c}`} strokeLinecap="butt"
            style={{ transition: 'stroke-dasharray 900ms cubic-bezier(.2,.6,.2,1)' }}
          />
        </svg>
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <div className="mono" style={{
            fontSize: size * 0.28, fontWeight: 500, color: 'var(--ink)', lineHeight: 1,
          }}>{Math.round(pct)}</div>
          <div className="mono-lbl" style={{ marginTop: 4 }}>/ 100</div>
        </div>
      </div>
      <div className="mono-lbl" style={{ textAlign: 'center' }}>
        {label}
        {delta !== null && delta !== 0 && (
          <span style={{
            marginLeft: 6,
            color: delta > 0 ? 'var(--ok)' : 'var(--miss)',
          }}>
            {delta > 0 ? '+' : ''}{delta}
          </span>
        )}
      </div>
    </div>
  );
}

function SignalBar({ label, value, max, weight, tip }) {
  const [hover, setHover] = React.useState(false);
  const pct = (value / max) * 100;
  const color = pct >= 90 ? 'var(--ok)' : pct >= 60 ? 'var(--warn)' : 'var(--miss)';
  return (
    <div
      className="tip-wrap"
      style={{ display: 'block', width: '100%', padding: '6px 0', borderBottom: '1px dashed var(--line)' }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: '0 0 140px', fontSize: 12, color: 'var(--ink-2)' }}>{label}</div>
        <div style={{ flex: 1, height: 6, background: 'var(--paper-3)', borderRadius: 1, position: 'relative', overflow: 'hidden' }}>
          <div style={{
            position: 'absolute', inset: 0, width: `${pct}%`, background: color,
            transition: 'width 700ms cubic-bezier(.2,.6,.2,1)',
          }} />
        </div>
        <div className="mono" style={{ flex: '0 0 64px', textAlign: 'right', fontSize: 11, color: 'var(--ink-3)' }}>
          {value}/{max}
        </div>
      </div>
      {hover && tip && (
        <div className="tip" style={{
          left: '50%', transform: 'translateX(-50%)', bottom: 'auto', top: 'calc(100% + 6px)',
        }}>
          {tip}
          <span style={{
            position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)',
            border: '5px solid transparent', borderBottomColor: 'var(--ink)',
          }} />
          <span style={{ display: 'block', marginTop: 6, opacity: 0.7, fontFamily: 'var(--mono)', fontSize: 10 }}>
            weight: {weight} · score: {value}/{max}
          </span>
        </div>
      )}
    </div>
  );
}

// Small blueprint corner flourish
function CornerTicks({ color = 'var(--ink-4)' }) {
  const tick = { position: 'absolute', background: color, opacity: 0.5 };
  return (
    <>
      <div style={{ ...tick, top: 0, left: 0, width: 10, height: 1 }} />
      <div style={{ ...tick, top: 0, left: 0, width: 1, height: 10 }} />
      <div style={{ ...tick, top: 0, right: 0, width: 10, height: 1 }} />
      <div style={{ ...tick, top: 0, right: 0, width: 1, height: 10 }} />
      <div style={{ ...tick, bottom: 0, left: 0, width: 10, height: 1 }} />
      <div style={{ ...tick, bottom: 0, left: 0, width: 1, height: 10 }} />
      <div style={{ ...tick, bottom: 0, right: 0, width: 10, height: 1 }} />
      <div style={{ ...tick, bottom: 0, right: 0, width: 1, height: 10 }} />
    </>
  );
}

function KnowledgePrompt({ item, mini = false }) {
  return (
    <div style={{
      background: 'var(--accent-soft)',
      border: '1px solid rgba(194,65,12,0.25)',
      borderLeft: '3px solid var(--accent)',
      padding: mini ? '8px 10px' : '10px 14px',
      borderRadius: '2px',
      display: 'flex', alignItems: 'flex-start', gap: 10,
    }}>
      <svg width="14" height="14" viewBox="0 0 14 14" style={{ flexShrink: 0, marginTop: 2 }}>
        <circle cx="7" cy="7" r="6" fill="none" stroke="var(--accent)" strokeWidth="1.2" />
        <text x="7" y="10" textAnchor="middle" fontSize="9" fontFamily="monospace"
          fontWeight="600" fill="var(--accent)">K</text>
      </svg>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
          <span className="mono" style={{
            fontSize: 11, fontWeight: 600, color: 'var(--accent-ink)',
            letterSpacing: '0.06em',
          }}>
            KnowledgeSlot · {item.field}
          </span>
          <span className="chip accent" style={{ fontSize: 9 }}>
            {item.impact === 'high' ? 'HIGH IMPACT' : item.impact === 'medium' ? 'MEDIUM IMPACT' : 'LOW IMPACT'}
          </span>
          <span className="mono-lbl" style={{ color: 'var(--accent-ink)', opacity: 0.8 }}>
            optional · improves matching quality
          </span>
        </div>
        {!mini && (
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.55 }}>
            {item.hint}
          </div>
        )}
      </div>
    </div>
  );
}

function SectionLabel({ n, children, aside }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      paddingBottom: 8, marginBottom: 14,
      borderBottom: '1px solid var(--line)',
    }}>
      {n && <span className="mono-lbl" style={{ color: 'var(--accent)', fontWeight: 600 }}>§ {n}</span>}
      <span className="mono-lbl" style={{ color: 'var(--ink)', fontWeight: 600 }}>{children}</span>
      <span style={{ flex: 1 }} />
      {aside && <span className="mono-lbl" style={{ color: 'var(--ink-3)' }}>{aside}</span>}
    </div>
  );
}

// helper to compute confidence total
function computeConfidence(signals, ks) {
  const totalWeight = signals.reduce((a, s) => a + s.weight, 0);
  const scored = signals.reduce((a, s) => a + (ks ? s.scoreFull : s.scoreBase), 0);
  return Math.round((scored / totalWeight) * 100);
}

Object.assign(window, {
  MFLogo, StatusChip, ConfidenceRing, SignalBar, CornerTicks,
  KnowledgePrompt, SectionLabel, computeConfidence,
});
