// Tweaks panel and audio simulator

function TweaksPanel({ tweaks, setTweaks, visible }) {
  if (!visible) return null;

  const set = (k, v) => setTweaks(prev => ({ ...prev, [k]: v }));

  return (
    <div style={{
      position: 'fixed',
      right: 16, bottom: 16,
      width: 280,
      background: 'rgba(18,16,14,0.96)',
      backdropFilter: 'blur(12px)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 12,
      padding: 18,
      color: '#e8dcb8',
      fontFamily: 'var(--font-ui)',
      fontSize: 12,
      zIndex: 100,
      boxShadow: '0 20px 60px rgba(0,0,0,0.6)',
      maxHeight: '90vh',
      overflowY: 'auto',
    }}>
      <div style={{
        fontFamily: 'var(--font-engrave)', fontSize: 11,
        letterSpacing: '0.3em', color: '#d6a055',
        marginBottom: 14, textTransform: 'uppercase', fontWeight: 700,
      }}>Tweaks</div>

      <Row label="Faceplate">
        <select value={tweaks.variant} onChange={e => {
            const k = e.target.value;
            set('variant', k);
            // Phase 9i (2026-05-04, operator-locked): switching face changes
            // ONLY the visual + the photocell time-constant character.  Knob
            // positions are NEVER auto-changed — that would destroy the
            // user's careful setup.  All faces share the universal default
            // (PR 40 / Gain 40 / Mix 100 / link off / sat off — same as the
            // ParameterLayout defaults that match the operator's unit at
            // neutral).  Per-use-case knob recall is handled separately by
            // the factory/user PresetBar (bottom-left).
            //
            // Silver = scale 1.0/1.0 (your unit, untouched).  Other 4 vary
            // photocell taus within UA-documented ±30% T4B cell variance.
            const profile = (window.VARIANT_DSP_PROFILES || {})[k];
            if (profile && window.juceInvoke) {
              window.juceInvoke('setOptoTimeScale',     profile.aScale,  profile.rScale);
              window.juceInvoke('setOptoOutputHfShelf', profile.outHfDb, profile.outHfFcHz);
              window.juceInvoke('setOptoOutputLfShelf', profile.outLfDb, profile.outLfFcHz);
            }
          }}
          style={selectStyle}>
          {/* All 5 distinct visual variants per the original Claude-Designer
              mockup the operator referenced 2026-05-04.  Silver Teletronix is
              the operator's actual unit; the other 4 are purely cosmetic
              "skin" presets — identical DSP under the hood. */}
          {['silver_teletronix', 'grey', 'studio_black', 'purple', 'me_classics'].map(k => (
            <option key={k} value={k}>{VARIANTS[k].name}</option>
          ))}
        </select>
      </Row>

      <Row label="Knob style">
        <select value={tweaks.knobStyle} onChange={e => set('knobStyle', e.target.value)}
          style={selectStyle}>
          <option value="bakelite">Bakelite (black, LA-2A classic)</option>
          <option value="studio-satin">Studio Satin (brushed silver)</option>
          <option value="davies">Davies 1900H (plastic cylinder, red dot)</option>
          <option value="flat-cap">Flat-Cap Aluminum (low-profile, red dot)</option>
          <option value="cream">Vintage Cream (ivory phenolic, Neve/ISA)</option>
          <option value="anodized">Anodized Black (matte cap, cream notch)</option>
          <option value="sifam">Sifam/Marshall (chunky knurl, amber line)</option>
          <option value="chicken">Chicken-head</option>
          <option value="brass">Brass</option>
        </select>
      </Row>

      <Row label={`Wear · ${Math.round(tweaks.wear * 100)}%`}>
        <input type="range" min="0" max="1" step="0.01" value={tweaks.wear}
          onChange={e => set('wear', +e.target.value)} style={rangeStyle} />
      </Row>

      <Row label={`Tube glow · ${Math.round(tweaks.tubeGlow * 100)}%`}>
        <input type="range" min="0" max="1.4" step="0.01" value={tweaks.tubeGlow}
          onChange={e => set('tubeGlow', +e.target.value)} style={rangeStyle} />
      </Row>

      {/* "Needle color" picker dropped 2026-05-04 (beta9) — operator request.
          Needle ink stays at the per-variant default ('#0a0604' for Silver,
          which reads correctly on every faceplate).  Underlying needleColor
          state still defaults in mentesh2a.jsx so VUMeter renders the dark
          ink consistently. */}

      <Row label="Lighting">
        <div style={{ display: 'flex', gap: 6 }}>
          {['bright', 'dark'].map(l => (
            <button key={l} onClick={() => set('lighting', l)}
              style={{
                ...btnStyle,
                background: tweaks.lighting === l ? '#d6a055' : 'transparent',
                color: tweaks.lighting === l ? '#0a0806' : '#e8dcb8',
              }}>{l}</button>
          ))}
        </div>
      </Row>

      <Row label="">
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
          <input type="checkbox" checked={tweaks.showScrews}
            onChange={e => set('showScrews', e.target.checked)} />
          <span>Show screws</span>
        </label>
      </Row>
      {/* "Show brand mark" toggle dropped 2026-05-04 (beta7+) — operator
          request.  Brand mark is part of the variant identity per spec; not a
          tweak the user should hide.  The underlying showLogo state still
          defaults to true in mentesh2a.jsx — older saved sessions that
          flipped it off will simply re-enable it on next variant change. */}
      <Row label="">
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
          <input type="checkbox" checked={tweaks.showSaturation !== false}
            onChange={e => set('showSaturation', e.target.checked)} />
          <span>Show saturation column</span>
        </label>
      </Row>
    </div>
  );
}

function Row({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      {label && <div style={{
        fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
        opacity: 0.6, marginBottom: 6,
      }}>{label}</div>}
      {children}
    </div>
  );
}

const selectStyle = {
  width: '100%',
  background: 'rgba(255,255,255,0.04)',
  border: '1px solid rgba(255,255,255,0.12)',
  color: '#e8dcb8',
  padding: '6px 8px',
  borderRadius: 4,
  fontFamily: 'inherit',
  fontSize: 12,
};

const rangeStyle = { width: '100%', accentColor: '#d6a055' };

const btnStyle = {
  padding: '4px 10px',
  border: '1px solid rgba(255,255,255,0.15)',
  borderRadius: 4,
  fontFamily: 'inherit', fontSize: 11,
  letterSpacing: '0.1em', textTransform: 'uppercase',
  cursor: 'pointer',
};

// ── Audio simulation: synthesized drum/bass loop feeling envelope ──
function useSimulatedAudio(playing) {
  const [level, setLevel] = React.useState(0);
  React.useEffect(() => {
    if (!playing) { setLevel(0); return; }
    let raf;
    const start = performance.now();
    const tick = () => {
      const t = (performance.now() - start) / 1000;
      // 100 BPM = 1.66 Hz beat. Kick on 1&3, snare on 2&4.
      const beat = t * (100 / 60);
      const phase = beat % 1;
      const beatIdx = Math.floor(beat) % 4;

      // Kick envelope
      const kickEnv = beatIdx === 0 || beatIdx === 2
        ? Math.exp(-phase * 8) : 0;
      // Snare
      const snareEnv = beatIdx === 1 || beatIdx === 3
        ? Math.exp(-phase * 6) * 0.7 : 0;
      // Hats (eighth notes)
      const hatPhase = (beat * 2) % 1;
      const hatEnv = Math.exp(-hatPhase * 12) * 0.25;
      // Bassline sustain
      const bass = 0.3 + 0.1 * Math.sin(t * 2.3);
      // Vocal hump (every 2 bars, a long sustain)
      const vocalPhase = (beat / 4) % 1;
      const vocal = vocalPhase < 0.7 ? Math.sin(vocalPhase * Math.PI / 0.7) * 0.5 : 0;

      const total = Math.min(1, kickEnv + snareEnv + hatEnv + bass * 0.3 + vocal * 0.4);
      setLevel(total);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);
  return level;
}

function TransportBar({ playing, onToggle, audioLevel }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 16,
      padding: '10px 20px',
      background: 'rgba(12,10,8,0.88)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 10,
      fontFamily: 'var(--font-ui)',
      color: '#e8dcb8',
      fontSize: 12,
      backdropFilter: 'blur(8px)',
    }}>
      <button onClick={onToggle} style={{
        width: 40, height: 40,
        borderRadius: '50%',
        border: '1px solid rgba(214,160,85,0.4)',
        background: playing
          ? 'radial-gradient(circle, #d6a055 0%, #8a5820 100%)'
          : 'radial-gradient(circle, #2a2420 0%, #0a0806 100%)',
        color: playing ? '#0a0806' : '#d6a055',
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'all 200ms',
      }}>
        {playing ? (
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <rect x="3" y="2" width="3" height="10" fill="currentColor"/>
            <rect x="8" y="2" width="3" height="10" fill="currentColor"/>
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3 2l9 5-9 5V2z" fill="currentColor"/>
          </svg>
        )}
      </button>
      <div>
        <div style={{ fontSize: 10, letterSpacing: '0.2em', opacity: 0.6, textTransform: 'uppercase' }}>
          Demo Signal
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>
          Drum loop · 100 BPM · -6 dBFS
        </div>
      </div>
      {/* level meter bar */}
      <div style={{
        width: 180, height: 8,
        background: 'rgba(255,255,255,0.05)',
        borderRadius: 2,
        overflow: 'hidden',
        position: 'relative',
      }}>
        <div style={{
          width: `${audioLevel * 100}%`, height: '100%',
          background: audioLevel > 0.8
            ? 'linear-gradient(90deg, #5a8a30 0%, #d6a055 70%, #b8271a 100%)'
            : 'linear-gradient(90deg, #5a8a30 0%, #9aa030 100%)',
          transition: 'width 40ms linear',
        }}/>
      </div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, opacity: 0.7, width: 50 }}>
        {(audioLevel * -24 + 0).toFixed(1)} dB
      </div>
    </div>
  );
}

Object.assign(window, { TweaksPanel, useSimulatedAudio, TransportBar });
