// Photoreal analog VU meter — classic cream-face LA-2A / Sifam style
// Matte cream vellum face, black ink, thin black needle, red zone past 0,
// "MENTESH CLASSICS" banner arc at top, large italic "VU" below center.

// 2026-05-04 (beta7+): operator-reported needleColor swatches in Tweaks did
// nothing — VUMeter never accepted a `needleColor` prop, so the four colour
// chips were dead UI.  Wired the prop through to the body / tip / tail
// strokes; the soft shadow stays warm-brown (it's relative to background, not
// to the needle ink).
function VUMeter({ value = 0, size = 280, mode = 'GR', widthFactor = 1,
                   needleColor = '#0a0806' }) {
  const [displayed, setDisplayed] = React.useState(value);

  // Needle physics: spring w/ damping (ballistic-ish)
  React.useEffect(() => {
    let raf;
    let current = displayed;
    let velocity = 0;
    const step = () => {
      const k = 0.11;
      const damp = 0.76;
      const diff = value - current;
      velocity = velocity * damp + diff * k;
      current += velocity;
      setDisplayed(current);
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value]);

  // Map VU value (-20..+3) to needle angle (-50..+50 deg)
  const clamped = Math.max(-20, Math.min(3, displayed));
  const valToAngle = (v) => (v + 8.5) / 11.5 * 50;
  const angle = valToAngle(clamped);

  const W = size;
  const H = size * 0.68;
  const OUTER_W = W * widthFactor;
  const cx = W / 2;
  const cy = H * 1.15;
  const rArc = H * 0.9;

  // VU scale marks — LA-2A layout
  const scaleMarks = [
    { v: -20, l: '20'  },
    { v: -10, l: '10'  },
    { v: -7,  l: '7'   },
    { v: -5,  l: '5'   },
    { v: -3,  l: '3'   },
    { v: -1,  l: '1'   },
    { v: 0,   l: '0'   },
    { v: 1,   l: '+1'  },
    { v: 2,   l: '+2'  },
    { v: 3,   l: '+3'  },
  ];

  // Minor ticks between every integer
  const minorTicks = [];
  for (let v = -20; v <= 3; v += 1) {
    if (!scaleMarks.some(m => m.v === v)) minorTicks.push(v);
  }

  // "MENTESH CLASSICS" curved banner path — arc above the scale
  const bannerR = rArc + 14;
  const bannerPath = `M ${cx - bannerR * Math.sin(32 * Math.PI / 180)} ${cy - bannerR * Math.cos(32 * Math.PI / 180)} A ${bannerR} ${bannerR} 0 0 1 ${cx + bannerR * Math.sin(32 * Math.PI / 180)} ${cy - bannerR * Math.cos(32 * Math.PI / 180)}`;

  return (
    <div style={{
      position: 'relative',
      width: OUTER_W, height: H + 28,
      // Chrome bezel — subtle, polished, like the photo
      background: `
        linear-gradient(180deg, #e8e6e0 0%, #b8b4ac 40%, #8a867e 65%, #4a4640 100%)
      `,
      border: '1px solid #1a1816',
      borderRadius: 8,
      padding: 4,
      boxShadow: `
        inset 0 1px 0 rgba(255,255,255,0.55),
        inset 0 -1px 0 rgba(0,0,0,0.45),
        inset 0 0 0 1px rgba(0,0,0,0.2),
        0 2px 5px rgba(0,0,0,0.55)
      `,
    }}>
      {/* inner chrome ring */}
      <div style={{
        width: '100%', height: '100%',
        background: 'linear-gradient(180deg, #2a2622 0%, #1a1612 100%)',
        borderRadius: 4,
        padding: 2,
        boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.8)',
      }}>
      {/* meter face — matte cream vellum, slightly uneven tone */}
      <div style={{
        width: '100%', height: '100%',
        background: `
          radial-gradient(ellipse at 50% 48%, #fbe896 0%, #f2d472 55%, #c89840 100%)
        `,
        borderRadius: 3,
        position: 'relative',
        overflow: 'hidden',
        boxShadow: `
          inset 0 0 26px rgba(140,80,10,0.35),
          inset 0 1px 2px rgba(0,0,0,0.22)
        `,
      }}>
        {/* paper grain — subtle fibers */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `
            repeating-linear-gradient(37deg, rgba(90,60,20,0.025) 0 1px, transparent 1px 3px),
            repeating-linear-gradient(117deg, rgba(90,60,20,0.02) 0 1px, transparent 1px 4px)
          `,
          mixBlendMode: 'multiply',
          pointerEvents: 'none',
        }}/>

        <svg width="100%" height="100%" viewBox={`${(W - OUTER_W) / 2} 0 ${OUTER_W} ${H}`}
          preserveAspectRatio="xMidYMid meet"
          style={{ display: 'block', position: 'absolute', inset: 0 }}>

          {/* MENTESH CLASSICS curved banner */}
          <defs>
            <path id={`banner-${size}`} d={bannerPath} />
          </defs>
          <text fontSize="8.5" fontFamily="var(--font-engrave), 'Helvetica Neue', sans-serif"
            fontWeight="700" fill="#1a1006" letterSpacing="2.4">
            <textPath href={`#banner-${size}`} startOffset="50%" textAnchor="middle">
              ★ MENTESH ENGINEERING ★
            </textPath>
          </text>

          {/* main black scale arc */}
          <path
            d={`M ${cx - rArc * Math.sin(50 * Math.PI / 180)} ${cy - rArc * Math.cos(50 * Math.PI / 180)} A ${rArc} ${rArc} 0 0 1 ${cx + rArc * Math.sin(50 * Math.PI / 180)} ${cy - rArc * Math.cos(50 * Math.PI / 180)}`}
            stroke="#12100c" strokeWidth="1.1" fill="none"
          />
          {/* red zone arc (0 to +3) */}
          <path
            d={`M ${cx + rArc * Math.sin(0)} ${cy - rArc} A ${rArc} ${rArc} 0 0 1 ${cx + rArc * Math.sin(50 * Math.PI / 180)} ${cy - rArc * Math.cos(50 * Math.PI / 180)}`}
            stroke="#b41410" strokeWidth="2.2" fill="none"
          />

          {/* minor ticks */}
          {minorTicks.map((v) => {
            const a = valToAngle(v) * Math.PI / 180;
            const r1 = rArc;
            const r2 = rArc - 4.5;
            const isRed = v > 0;
            return (
              <line key={`minor-${v}`}
                x1={cx + r1 * Math.sin(a)} y1={cy - r1 * Math.cos(a)}
                x2={cx + r2 * Math.sin(a)} y2={cy - r2 * Math.cos(a)}
                stroke={isRed ? '#b41410' : '#12100c'} strokeWidth="0.55" />
            );
          })}

          {/* major ticks + labels */}
          {scaleMarks.map((m, i) => {
            const a = valToAngle(m.v) * Math.PI / 180;
            const r1 = rArc;
            const r2 = rArc - 11;
            const x1 = cx + r1 * Math.sin(a);
            const y1 = cy - r1 * Math.cos(a);
            const x2 = cx + r2 * Math.sin(a);
            const y2 = cy - r2 * Math.cos(a);
            const tx = cx + (r2 - 10) * Math.sin(a);
            const ty = cy - (r2 - 10) * Math.cos(a);
            const isRed = m.v >= 0;
            return (
              <g key={i}>
                <line x1={x1} y1={y1} x2={x2} y2={y2}
                  stroke={isRed ? '#b41410' : '#12100c'}
                  strokeWidth="1.15" />
                <text x={tx} y={ty + 3} textAnchor="middle"
                  fontSize="8.5" fontFamily="var(--font-engrave), 'Helvetica Neue', sans-serif"
                  fontWeight="700"
                  fill={isRed ? '#b41410' : '#12100c'}>
                  {m.l}
                </text>
              </g>
            );
          })}

          {/* mode line — small caps, below scale */}
          <text x={cx} y={cy - rArc * 0.52}
            textAnchor="middle"
            fontSize="7.5" fontFamily="var(--font-engrave), 'Helvetica Neue', sans-serif"
            fontWeight="700"
            fill="#12100c" letterSpacing="2.2" opacity="0.72">
            {mode === 'GR' ? 'GAIN REDUCTION' : mode === '+4' ? 'OUTPUT +4 dB' : 'OUTPUT +10 dB'}
          </text>

          {/* big VU — bold sans, strong presence */}
          <text x={cx} y={cy - rArc * 0.20}
            textAnchor="middle"
            fontSize="24" fontFamily="'Helvetica Neue', 'Arial Black', sans-serif"
            fontWeight="900"
            fill="#12100c" letterSpacing="1">VU</text>

          {/* needle — thin black with counterweight */}
          <g transform={`rotate(${angle} ${cx} ${cy})`}>
            {/* needle shadow (soft, offset) */}
            <line x1={cx + 0.8} y1={cy + 1} x2={cx + 0.8} y2={cy - rArc + 6}
              stroke="rgba(60,40,10,0.3)" strokeWidth="1.6" strokeLinecap="round" />
            {/* needle body */}
            <line x1={cx} y1={cy} x2={cx} y2={cy - rArc + 6}
              stroke={needleColor} strokeWidth="1.15" strokeLinecap="round" />
            {/* needle tip accent — slight tonal lift for visibility */}
            <line x1={cx} y1={cy - rArc + 14} x2={cx} y2={cy - rArc + 6}
              stroke={needleColor} strokeWidth="1.4" strokeLinecap="round" opacity="0.9" />
            {/* counterweight tail */}
            <rect x={cx - 1.2} y={cy} width="2.4" height="11" fill={needleColor} rx="0.4" />
          </g>

          {/* pivot cap — polished metal */}
          <circle cx={cx} cy={cy} r="4.8"
            fill="url(#pivotGrad)" stroke="#0a0806" strokeWidth="0.4" />
          <circle cx={cx} cy={cy} r="1.8" fill="#1a1410" />
          <circle cx={cx - 1.0} cy={cy - 1.0} r="0.6" fill="rgba(255,240,200,0.8)" />

          <defs>
            <radialGradient id="pivotGrad" cx="40%" cy="40%">
              <stop offset="0%" stopColor="#d8d4cc" />
              <stop offset="50%" stopColor="#7a7670" />
              <stop offset="100%" stopColor="#1a1612" />
            </radialGradient>
          </defs>
        </svg>

        {/* curved glass highlight — top-left soft reflection */}
        <div style={{
          position: 'absolute', inset: 0,
          background: `
            linear-gradient(142deg,
              rgba(255,252,240,0.38) 0%,
              rgba(255,252,240,0.14) 28%,
              rgba(255,252,240,0) 52%,
              rgba(0,0,0,0) 80%,
              rgba(40,20,0,0.12) 100%)
          `,
          pointerEvents: 'none',
          borderRadius: 3,
        }}/>
        {/* vignette */}
        <div style={{
          position: 'absolute', inset: 0,
          boxShadow: 'inset 0 0 20px rgba(80,50,15,0.35)',
          pointerEvents: 'none',
          borderRadius: 3,
        }}/>
        {/* glass edge lip — thin dark ring inside */}
        <div style={{
          position: 'absolute', inset: 0,
          boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.35)',
          pointerEvents: 'none',
          borderRadius: 3,
        }}/>
      </div>
      </div>
    </div>
  );
}

Object.assign(window, { VUMeter });
