// Shared UI primitives
const { useState, useEffect, useRef, useMemo } = React;

function cx(...a) { return a.filter(Boolean).join(' '); }

function Chip({ children, tone = 'default', className = '' }) {
  const tones = {
    default: '', red: 'chip-red', yellow: 'chip-yellow',
    green: 'chip-green', blue: 'chip-blue', ink: 'chip-ink',
  };
  return <span className={`chip ${tones[tone] || ''} ${className}`}>{children}</span>;
}

function Label({ children, className = '' }) {
  return <div className={`label ${className}`}>{children}</div>;
}

function Btn({ children, variant = 'default', size, onClick, disabled, className = '', style }) {
  const variants = { default:'', primary:'btn-primary', yellow:'btn-yellow', ink:'btn-ink', ghost:'btn-ghost' };
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`btn ${variants[variant]||''} ${size==='sm'?'btn-sm':''} ${className}`}
      style={{ ...(disabled?{opacity:0.4,cursor:'not-allowed'}:null), ...style }}
    >{children}</button>
  );
}

// A brutalist hatched placeholder for "product image"
function ImgPlaceholder({ label, tone = 'ink', size = 120, className = '' }) {
  const bg = tone === 'red' ? 'hatch-red' : tone === 'yellow' ? 'hatch-yellow' : 'hatch';
  return (
    <div
      className={`${bg} ${className}`}
      style={{
        width: size, height: size, border: '3px solid var(--ink)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', flexShrink: 0,
      }}
    >
      <div style={{
        background: 'var(--paper)', padding: '4px 8px', border: '2px solid var(--ink)',
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700,
        letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink)',
      }}>{label}</div>
    </div>
  );
}

// Confidence breakdown: stacked horizontal bar + list
function ConfidenceViz({ data, big = false }) {
  const steps = [
    { key: 'product_identification', label: 'ID',         color: '#E30613' },
    { key: 'variant_match',          label: 'VARIANT',    color: '#FFD400' },
    { key: 'th_market_coverage',     label: 'TH COV',     color: '#2E5BFF' },
    { key: 'price_source_quality',   label: 'SRC QUAL',   color: '#17A34A' },
    { key: 'synthesis_reasoning',    label: 'REASON',     color: '#0A0A0A' },
  ];
  const overall = data.overall;
  const tone = overall >= 0.75 ? 'green' : overall >= 0.55 ? 'yellow' : 'red';
  const toneLabel = overall >= 0.75 ? 'AUTO-PERSIST' : overall >= 0.55 ? 'REVIEW ADVISED' : 'LOG ONLY';

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 10 }}>
        <div className="big-num mono" style={{ fontSize: big ? 64 : 36 }}>
          {(overall * 100).toFixed(0)}<span style={{ fontSize: big ? 24 : 14, marginLeft: 2 }}>%</span>
        </div>
        <Chip tone={tone}>{toneLabel}</Chip>
        <Label style={{ marginLeft: 'auto' }}>CALIBRATED CONFIDENCE</Label>
      </div>
      {/* Stacked bar */}
      <div style={{
        display: 'flex', height: big ? 22 : 16, border: '3px solid var(--ink)',
        background: 'var(--paper)', position: 'relative',
      }}>
        {steps.map((s, i) => {
          const v = data[s.key] || 0;
          return (
            <div key={s.key} style={{
              flex: v, background: s.color,
              borderRight: i < steps.length - 1 ? '3px solid var(--ink)' : 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: s.color === '#FFD400' ? '#0A0A0A' : '#fff',
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.04em',
            }}>
              {v > 0.15 ? `${(v*100).toFixed(0)}` : ''}
            </div>
          );
        })}
      </div>
      {/* Legend / detail rows */}
      <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 12px' }}>
        {steps.map(s => {
          const v = data[s.key] || 0;
          return (
            <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11 }}>
              <div style={{ width: 12, height: 12, background: s.color, border: '2px solid var(--ink)', flexShrink: 0 }} />
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', fontWeight: 700 }}>{s.label}</span>
              <span className="mono" style={{ marginLeft: 'auto', fontWeight: 700 }}>{(v*100).toFixed(0)}%</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// A compact bar for confidence (used in history)
function ConfBar({ value, width = 80 }) {
  const pct = value * 100;
  const color = value >= 0.75 ? '#17A34A' : value >= 0.55 ? '#FFD400' : '#E30613';
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      <div style={{ width, height: 10, border: '2px solid var(--ink)', background: 'var(--paper)', position: 'relative' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: color }} />
      </div>
      <span className="mono" style={{ fontSize: 11, fontWeight: 700, minWidth: 28 }}>{pct.toFixed(0)}</span>
    </div>
  );
}

// Sparkline
function Sparkline({ values, width = 80, height = 24, color = 'var(--ink)' }) {
  const max = Math.max(...values), min = Math.min(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * width;
    const y = height - ((v - min) / range) * height;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" />
    </svg>
  );
}

Object.assign(window, { cx, Chip, Label, Btn, ImgPlaceholder, ConfidenceViz, ConfBar, Sparkline });
