// Primitives: Sparkline, RingChart, Funnel, Tooltip, Avatar, etc.

const { useState, useEffect, useRef, useMemo } = React;

// ----- Sparkline -----
function Sparkline({ data, color = 'var(--accent)', width = 80, height = 24, fill = true, animated = false }) {
  if (!data || !data.length) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const stepX = width / (data.length - 1);
  const points = data.map((v, i) => [i * stepX, height - ((v - min) / range) * (height - 2) - 1]);
  const path = points.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const areaPath = `${path} L${width},${height} L0,${height} Z`;
  const id = useMemo(() => 'sg' + Math.random().toString(36).slice(2, 9), []);
  return (
    <svg width={width} height={height} className="sparkline" overflow="visible">
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {fill && <path d={areaPath} fill={`url(#${id})`} />}
      <path d={path} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={points[points.length-1][0]} cy={points[points.length-1][1]} r="2.2" fill={color} />
    </svg>
  );
}

// ----- Ring chart -----
function RingChart({ value, total, size = 140, thickness = 12, color = 'var(--success)', bg = 'rgba(255,255,255,0.06)', label, sublabel, children }) {
  const radius = (size - thickness) / 2;
  const circ = 2 * Math.PI * radius;
  const pct = total > 0 ? value / total : 0;
  const dash = circ * pct;
  return (
    <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={radius} stroke={bg} strokeWidth={thickness} fill="none" />
        <circle cx={size/2} cy={size/2} r={radius} stroke={color} strokeWidth={thickness}
                fill="none" strokeDasharray={`${dash} ${circ - dash}`} strokeLinecap="round"
                style={{ transition: 'stroke-dasharray 0.6s ease' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        {children || (
          <>
            <div className="num" style={{ fontSize: 28, fontWeight: 600, color: 'var(--text-1)' }}>{label}</div>
            {sublabel && <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>{sublabel}</div>}
          </>
        )}
      </div>
    </div>
  );
}

// ----- Funnel bar row -----
function FunnelRow({ label, value, pct, color, total }) {
  return (
    <div className="funnel-row">
      <div style={{ color: 'var(--text-2)' }}>{label}</div>
      <div style={{ position: 'relative', height: 22, background: 'rgba(148,163,184,0.06)', borderRadius: 6, overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, bottom: 0,
          width: `${pct}%`,
          background: `linear-gradient(90deg, ${color}, ${color}cc)`,
          borderRadius: 6,
          display: 'flex', alignItems: 'center', paddingLeft: 8,
          fontSize: 11, color: '#001018', fontWeight: 600,
          transition: 'width 0.6s ease'
        }}>
          {pct >= 18 && <span className="num">{value} ({pct}%)</span>}
        </div>
        {pct < 18 && (
          <span className="num" style={{ position: 'absolute', left: `calc(${pct}% + 8px)`, top: '50%', transform: 'translateY(-50%)', fontSize: 11, color: 'var(--text-2)' }}>
            {value} ({pct}%)
          </span>
        )}
      </div>
      <div style={{ textAlign: 'right', color: 'var(--text-3)', fontSize: 11 }} className="num">{value}</div>
    </div>
  );
}

// ----- Avatar (initials) -----
function Avatar({ name, size = 28, color }) {
  const initials = (name || '?').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  // Hash to pick from palette
  const palette = ['#22D3EE','#A78BFA','#F472B6','#34D399','#60A5FA','#FB923C','#F59E0B','#10B981'];
  let h = 0; for (let i = 0; i < (name||'').length; i++) h = (h * 31 + name.charCodeAt(i)) | 0;
  const c = color || palette[Math.abs(h) % palette.length];
  return (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: `linear-gradient(135deg, ${c}33, ${c}55)`,
      border: `1px solid ${c}55`,
      color: c,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.36, fontWeight: 600, fontFamily: 'var(--font-display)',
      flexShrink: 0
    }}>{initials}</div>
  );
}

// ----- Score chip -----
function ScoreChip({ score }) {
  let color = '#22D3EE';
  if (score >= 80) color = '#10B981';
  else if (score >= 65) color = '#34D399';
  else if (score >= 50) color = '#F59E0B';
  else color = '#F43F5E';
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '2px 8px 2px 4px',
      background: `${color}1f`, border: `1px solid ${color}40`,
      borderRadius: 999, fontSize: 11, fontWeight: 600,
      color
    }}>
      <span style={{ width: 16, height: 16, borderRadius: '50%', background: color, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, color: '#001018' }}>•</span>
      <span className="num">{score}</span>
    </div>
  );
}

// ----- Status pill helper -----
function StatusPill({ status }) {
  const cls = window.VELUNA_DATA.statusPill[status] || 'pill-neutral';
  const label = window.VELUNA_DATA.statusLabel[status] || status;
  return (
    <span className={`pill ${cls}`}>
      <span className="pill-dot" />
      {label}
    </span>
  );
}

// ----- Veluna logo -----
function VelunaLogo({ size = 36, hideText = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 40 40">
        <defs>
          <linearGradient id="vlogo" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="var(--accent)"/>
            <stop offset="100%" stopColor="#A78BFA"/>
          </linearGradient>
        </defs>
        <path d="M6 6 L20 34 L34 6 L26 6 L20 18 L14 6 Z" fill="url(#vlogo)" />
        <path d="M14 6 L20 18 L26 6" fill="none" stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>
      </svg>
      {!hideText && (
        <div style={{ lineHeight: 1, fontFamily: 'var(--font-display)' }}>
          <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '0.02em', color: 'var(--text-1)' }}>VELUNA</div>
          <div style={{ fontSize: 9, fontWeight: 500, letterSpacing: '0.18em', color: 'var(--text-3)', marginTop: 2 }}>GROWTH STACK</div>
        </div>
      )}
    </div>
  );
}

// ----- Tooltip wrapper -----
function withTooltip(children, text) {
  const [show, setShow] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  return (
    <span style={{ position: 'relative', display: 'inline-block' }}
          onMouseEnter={(e) => { setPos({ x: e.clientX, y: e.clientY }); setShow(true); }}
          onMouseLeave={() => setShow(false)}>
      {children}
      {show && <span className="tt" style={{ left: pos.x, top: pos.y, position: 'fixed' }}>{text}</span>}
    </span>
  );
}

window.Sparkline = Sparkline;
window.RingChart = RingChart;
window.FunnelRow = FunnelRow;
window.Avatar = Avatar;
window.ScoreChip = ScoreChip;
window.StatusPill = StatusPill;
window.VelunaLogo = VelunaLogo;
window.withTooltip = withTooltip;
