// instruments.jsx — analytical widgets (gauges, dials, sparklines, eval bar)
// extracted from the Codex direction so every surface (home, dashboard, play,
// exercises) can use them. All take their colour from CSS vars; work in dark
// or light context automatically.

const { useState: useStateI, useEffect: useEffectI, useRef: useRefI } = React;

// ──────────────────────────────────────────────────────────────────────
// 1. BRASS GAUGE — labelled horizontal bar with glowing fill
//    <BrassGauge label="VISION" value={62} color="var(--gold)" />
// ──────────────────────────────────────────────────────────────────────
function BrassGauge({ label, value, color = 'var(--gold)', delta, dark = false }){
  const labelColor = dark ? 'rgba(255,247,230,.55)' : 'var(--ink-muted)';
  const trackBg    = dark ? 'rgba(255,247,230,.12)' : 'rgba(25,23,20,.08)';
  return (
    <div style={{ marginTop: 14 }}>
      <div style={{
        display:'flex', justifyContent:'space-between', alignItems:'baseline',
        fontFamily:'JetBrains Mono, monospace',
        fontSize: 10, fontWeight: 800, letterSpacing:'.18em',
        color: labelColor, textTransform:'uppercase',
      }}>
        <span>{label}</span>
        <span>
          <span style={{ color: color, letterSpacing: 0, marginRight: delta ? 8 : 0 }}>{value}%</span>
          {delta != null && (
            <span style={{
              color: delta >= 0 ? 'var(--olive)' : 'var(--rose)',
              fontSize: 9, letterSpacing: 0,
            }}>{delta >= 0 ? '↑' : '↓'} {Math.abs(delta)}</span>
          )}
        </span>
      </div>
      <div style={{
        marginTop: 6, height: 6, borderRadius: 3,
        background: trackBg, overflow:'hidden',
        position:'relative',
      }}>
        <span style={{
          position:'absolute', left: 0, top: 0, height:'100%',
          width: `${value}%`,
          background: `linear-gradient(90deg, ${color}, color-mix(in srgb, ${color} 60%, white))`,
          boxShadow: `0 0 8px ${color}`,
          transition: 'width 1.4s var(--ease-out)',
        }} />
        {/* subtle tick marks */}
        {[25, 50, 75].map(p => (
          <span key={p} style={{
            position:'absolute', left: `${p}%`, top: 0, bottom: 0,
            width: 1, background: dark ? 'rgba(255,247,230,.08)' : 'rgba(25,23,20,.08)',
          }} />
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 2. RATING DIAL — half-circle needle gauge for Maia rating
//    <RatingDial value={1700} min={200} max={2000} dark />
// ──────────────────────────────────────────────────────────────────────
function RatingDial({ value = 1500, min = 200, max = 2000, dark = false, label = 'Maia · sparring' }){
  const pct = (value - min) / (max - min);
  const angle = -180 + pct * 180;
  const fg = dark ? '#fff7e6' : 'var(--ink)';
  return (
    <div style={{ position:'relative', width:'100%' }}>
      <div style={{
        display:'flex', justifyContent:'space-between',
        fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        fontWeight: 800, letterSpacing:'.18em', textTransform:'uppercase',
        color: dark ? 'rgba(255,247,230,.55)' : 'var(--ink-muted)',
      }}>
        <span>{label}</span>
        <span style={{ color: 'var(--rose)' }}>● {value}</span>
      </div>
      <div style={{ position:'relative', width:'100%', height: 100, marginTop: 6 }}>
        <svg viewBox="-110 -110 220 110" style={{ width:'100%', height:'100%' }}>
          <defs>
            <linearGradient id={`rd-${label.replace(/\s/g,'')}`} x1="0" x2="1">
              <stop offset="0%" stopColor="var(--blue)" />
              <stop offset="50%" stopColor="var(--gold)" />
              <stop offset="100%" stopColor="var(--rose)" />
            </linearGradient>
          </defs>
          <path d="M -100 0 A 100 100 0 0 1 100 0" fill="none"
            stroke={dark ? 'rgba(255,247,230,.14)' : 'rgba(25,23,20,.10)'}
            strokeWidth="10" strokeLinecap="round" />
          <path d="M -100 0 A 100 100 0 0 1 100 0" fill="none"
            stroke={`url(#rd-${label.replace(/\s/g,'')})`}
            strokeWidth="5" strokeLinecap="round"
            strokeDasharray={`${pct * 314} 314`}
            style={{ transition: 'stroke-dasharray 1.2s var(--ease-out)' }} />
          {/* tick marks */}
          {Array.from({ length: 9 }, (_, i) => {
            const a = (-180 + i * 22.5) * Math.PI / 180;
            const r1 = 95, r2 = i % 2 === 0 ? 86 : 90;
            return (
              <line key={i}
                x1={Math.cos(a) * r1} y1={Math.sin(a) * r1}
                x2={Math.cos(a) * r2} y2={Math.sin(a) * r2}
                stroke={dark ? 'rgba(255,247,230,.3)' : 'rgba(25,23,20,.25)'}
                strokeWidth={i % 2 === 0 ? 1.2 : .8} />
            );
          })}
          {/* needle */}
          <g style={{ transition: 'transform 1.2s var(--ease-out)' }}
             transform={`rotate(${angle})`}>
            <line x1="0" y1="0" x2="86" y2="0"
              stroke="var(--gold)" strokeWidth="2.5" strokeLinecap="round" />
            <circle cx="0" cy="0" r="6" fill="var(--gold)" />
            <circle cx="0" cy="0" r="2" fill={dark ? '#181519' : 'var(--paper-card)'} />
          </g>
        </svg>
        <div style={{
          position:'absolute', left:0, right:0, bottom: 4, textAlign:'center',
          fontFamily:'Fraunces, serif', fontWeight: 700,
          fontSize: 30, letterSpacing:'-.03em', color: fg,
        }}>{value}</div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 3. SPARKLINE — animated draw of a path
//    <Sparkline points={[...]} color="var(--gold)" height={80} />
// ──────────────────────────────────────────────────────────────────────
function Sparkline({ points = [], color = 'var(--gold)', height = 80, fill = true, label }){
  const max = Math.max(...points), min = Math.min(...points);
  const range = max - min || 1;
  const w = 320;
  const xs = points.map((_, i) => (i / (points.length - 1)) * w);
  const ys = points.map(p => height - 10 - ((p - min) / range) * (height - 20));
  const path = xs.map((x, i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${ys[i].toFixed(1)}`).join(' ');
  const area = `${path} L ${w} ${height} L 0 ${height} Z`;
  const id = `spark-${color.replace(/[^a-z]/gi,'')}-${Math.random().toString(36).slice(2,7)}`;
  return (
    <svg viewBox={`0 0 ${w} ${height}`} style={{ width:'100%', height }}>
      <defs>
        <linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"   stopColor={color} stopOpacity=".4" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {fill && <path d={area} fill={`url(#${id})`} />}
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      {/* endpoint */}
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r="3.5" fill={color} />
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r="6"
        fill="none" stroke={color} strokeOpacity=".4" strokeWidth="1.5">
        <animate attributeName="r" from="3.5" to="12" dur="2s" repeatCount="indefinite" />
        <animate attributeName="opacity" from=".5" to="0" dur="2s" repeatCount="indefinite" />
      </circle>
    </svg>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 4. EVAL BAR — vertical Stockfish eval indicator
//    <EvalBar value={1.2} max={5} height={300} />
// ──────────────────────────────────────────────────────────────────────
function EvalBar({ value = 0, max = 5, height = 300, depth = 22 }){
  // value range: -max to +max; positive = white advantage
  const pct = Math.max(0, Math.min(1, (value + max) / (2 * max)));
  const whiteHeight = pct * 100;
  return (
    <div style={{
      position:'relative', height,
      width: 36, borderRadius: 8,
      overflow:'hidden', border: '1px solid var(--line-strong)',
      boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)',
    }}>
      <div style={{ position:'absolute', inset: 0, background:'#1a1612' }} />
      <div style={{
        position:'absolute', left: 0, right: 0, bottom: 0,
        height: `${whiteHeight}%`,
        background:'linear-gradient(180deg, #fffaf2, #f6ecda)',
        transition: 'height 1.4s var(--ease-out)',
      }} />
      {/* center line */}
      <div style={{
        position:'absolute', left: 0, right: 0, top: '50%',
        height: 1, background: 'var(--gold)', opacity: .6,
      }} />
      {/* value badge */}
      <span style={{
        position:'absolute', left: '50%', top: `${100 - whiteHeight}%`,
        transform: 'translate(-50%, -50%)',
        fontFamily:'JetBrains Mono, monospace', fontSize: 10, fontWeight: 800,
        padding:'3px 6px', borderRadius: 5,
        background: value >= 0 ? '#1a1612' : '#fffaf2',
        color: value >= 0 ? 'var(--gold)' : 'var(--ink)',
        border: `1px solid ${value >= 0 ? 'rgba(255,247,230,.3)' : 'var(--line-strong)'}`,
        whiteSpace:'nowrap',
      }}>{value > 0 ? '+' : ''}{value.toFixed(1)}</span>
      {/* depth */}
      <span style={{
        position:'absolute', left: -28, top: '50%', transform: 'translateY(-50%) rotate(-90deg)',
        fontFamily:'JetBrains Mono, monospace', fontSize: 9, fontWeight: 800,
        letterSpacing:'.2em', textTransform:'uppercase', color:'var(--ink-muted)',
        whiteSpace:'nowrap',
      }}>D · {depth}</span>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 5. MOVE LIST — algebraic notation column
// ──────────────────────────────────────────────────────────────────────
function MoveList({ moves = [], current = -1, dark = false }){
  const bg = dark ? 'rgba(255,247,230,.04)' : 'var(--paper-200)';
  const border = dark ? 'rgba(255,247,230,.10)' : 'var(--line)';
  const muted = dark ? 'rgba(255,247,230,.55)' : 'var(--ink-muted)';
  const text = dark ? '#fff7e6' : 'var(--ink)';
  return (
    <div style={{
      padding: 14, borderRadius: 14,
      background: bg, border: `1px solid ${border}`,
      fontFamily:'JetBrains Mono, monospace', fontSize: 12,
      maxHeight: 220, overflow: 'auto',
    }}>
      <div style={{ display:'grid', gridTemplateColumns: '24px 1fr 1fr', gap: 8, rowGap: 6 }}>
        {moves.map((pair, i) => (
          <React.Fragment key={i}>
            <span style={{ color: muted, fontWeight: 700 }}>{i + 1}.</span>
            <span style={{
              padding: '2px 8px', borderRadius: 4,
              color: i * 2 === current ? 'var(--gold)' : text,
              background: i * 2 === current ? 'rgba(227,155,68,.12)' : 'transparent',
              fontWeight: 700,
            }}>{pair[0]}</span>
            <span style={{
              padding: '2px 8px', borderRadius: 4,
              color: i * 2 + 1 === current ? 'var(--gold)' : text,
              background: i * 2 + 1 === current ? 'rgba(227,155,68,.12)' : 'transparent',
              fontWeight: 700,
            }}>{pair[1] || ''}</span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 6. INSTRUMENT PANEL — composite card wrapper for instruments
// ──────────────────────────────────────────────────────────────────────
function InstrumentCard({ title, hint, children, dark = false, style = {} }){
  const bg = dark
    ? 'linear-gradient(160deg, #181519 0%, #2a1f24 100%)'
    : 'var(--paper-card)';
  const border = dark ? 'rgba(255,247,230,.16)' : 'var(--line-strong)';
  const text = dark ? '#fff7e6' : 'var(--ink)';
  const muted = dark ? 'rgba(255,247,230,.55)' : 'var(--ink-muted)';
  return (
    <div style={{
      padding: 22, borderRadius: 18,
      background: bg, border: `1px solid ${border}`,
      color: text, position:'relative', overflow:'hidden',
      ...style,
    }}>
      <div style={{
        display:'flex', justifyContent:'space-between',
        fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        fontWeight: 800, letterSpacing:'.18em', textTransform:'uppercase',
        color: muted,
        paddingBottom: 8, borderBottom: `1px solid ${border}`,
      }}>
        <span>{title}</span>
        {hint && <span style={{ color: 'var(--gold)' }}>{hint}</span>}
      </div>
      <div style={{ marginTop: 14, position:'relative' }}>
        {children}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// 7. STREAK FLAME — animated flame icon with day count
// ──────────────────────────────────────────────────────────────────────
function StreakFlame({ days = 7, dark = false }){
  const fg = dark ? '#fff7e6' : 'var(--ink)';
  return (
    <div style={{
      display:'inline-flex', alignItems:'center', gap: 10,
      padding:'7px 14px', borderRadius: 999,
      background: 'rgba(227,155,68,.14)',
      border:'1px solid rgba(227,155,68,.3)',
      color: 'var(--gold)',
    }}>
      <svg viewBox="0 0 24 24" width="16" height="16" style={{
        animation: 'pwFlicker 1.6s var(--ease-soft) infinite',
        transformOrigin: 'bottom center',
      }}>
        <path d="M12 2 C 14 6, 18 8, 17 12 C 17 16, 14 18, 12 18 C 10 18, 7 16, 7 12 C 7 9, 9 8, 10 5 C 11 8, 13 7, 12 2 Z"
          fill="var(--gold)" />
        <path d="M12 7 C 13 9, 14 10, 13.5 12 C 13.5 14, 12 15, 12 15 C 12 15, 10.5 14, 10.5 12 C 10.5 10.5, 11.5 10, 12 7 Z"
          fill="#fff7e6" opacity=".5" />
      </svg>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 12,
        fontWeight: 800, letterSpacing:'.06em', color: fg,
      }}>{days}<span style={{ color: 'var(--gold)' }}>d</span></span>
    </div>
  );
}

// keyframe for flame
if (typeof document !== 'undefined' && !document.getElementById('pw-instruments-kf')){
  const s = document.createElement('style');
  s.id = 'pw-instruments-kf';
  s.textContent = `
    @keyframes pwFlicker {
      0%,100% { transform: scaleY(1) rotate(-1deg); }
      35%     { transform: scaleY(1.08) rotate(2deg); }
      65%     { transform: scaleY(.95) rotate(-2deg); }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, {
  BrassGauge, RatingDial, Sparkline, EvalBar, MoveList, InstrumentCard, StreakFlame,
});
