/* Pick Your Frequency — a visible-spectrum selector. Choosing a wavelength retunes
   the beam imagery and the accent palette to that colour. */
function wavelengthToRGB(nm) {
  let r = 0, g = 0, b = 0;
  if (nm >= 380 && nm < 440) { r = -(nm - 440) / 60; b = 1; }
  else if (nm < 490) { g = (nm - 440) / 50; b = 1; }
  else if (nm < 510) { g = 1; b = -(nm - 510) / 20; }
  else if (nm < 580) { r = (nm - 510) / 70; g = 1; }
  else if (nm < 645) { r = 1; g = Math.pow(-(nm - 645) / 65, 1.9); }
  else if (nm <= 780) { r = 1; }
  let f = 1;
  if (nm > 700) f = 0.3 + 0.7 * (780 - nm) / 80;
  else if (nm < 420) f = 0.3 + 0.7 * (nm - 380) / 40;
  const gam = (v) => Math.round(255 * Math.pow(Math.max(0, Math.min(1, v * f)), 0.8));
  return [gam(r), gam(g), gam(b)];
}

const LASER_LINES = [
  { nm: 405, label: 'Diode' },
  { nm: 488, label: 'Argon' },
  { nm: 532, label: 'Nd:YAG' },
  { nm: 633, label: 'HeNe' },
  { nm: 660, label: 'Diode' }
];

function FrequencyPicker({ defaultNm = 633, style }) {
  const [nm, setNm] = React.useState(defaultNm);
  const barRef = React.useRef(null);
  const dragRef = React.useRef(false);

  const MIN = 400, MAX = 700;
  const rgb = wavelengthToRGB(nm);
  const css = 'rgb(' + rgb.join(',') + ')';

  React.useEffect(() => {
    const [r, g, b] = rgb;
    const root = document.documentElement.style;
    // hue distance from the captures' native red
    const max = Math.max(r, g, b), min = Math.min(r, g, b);
    let hue = 0;
    if (max !== min) {
      const d = max - min;
      hue = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
      hue = (hue * 60 + 360) % 360;
    }
    root.setProperty('--beam-filter', 'hue-rotate(' + hue.toFixed(1) + 'deg) saturate(' + (hue > 40 && hue < 300 ? 1.15 : 1) + ')');

    // WCAG-aware derivations: the accent moves, so the colours paired with it must move too.
    const lin = (v) => { const s = v / 255; return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4); };
    const lum = (c) => 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]);
    const ratio = (a, b) => { const la = lum(a), lb = lum(b); return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05); };
    const L = lum(rgb);

    // filled elements: flip the foreground to ink once the accent is bright
    root.setProperty('--text-on-laser', L > 0.35 ? '#000000' : '#ffffff');

    // accent-as-text: lift toward white until it clears 4.5:1 on the canvas floor
    const CANVAS = [5, 5, 6];
    let text = rgb.slice();
    for (let i = 0; i < 24 && ratio(text, CANVAS) < 4.5; i++) {
      text = [text[0] + (255 - text[0]) * 0.12, text[1] + (255 - text[1]) * 0.12, text[2] + (255 - text[2]) * 0.12];
    }
    text = text.map(Math.round);
    root.setProperty('--laser-red-text', 'rgb(' + text.join(',') + ')');
    root.setProperty('--laser-red', css);
    root.setProperty('--laser-red-bright', 'rgb(' + Math.min(255, r + 46) + ',' + Math.min(255, g + 46) + ',' + Math.min(255, b + 46) + ')');
    root.setProperty('--laser-red-deep', 'rgb(' + Math.round(r * 0.66) + ',' + Math.round(g * 0.66) + ',' + Math.round(b * 0.66) + ')');
    root.setProperty('--laser-red-dim', 'rgb(' + Math.round(r * 0.34) + ',' + Math.round(g * 0.34) + ',' + Math.round(b * 0.34) + ')');
    root.setProperty('--laser-red-a35', 'rgba(' + r + ',' + g + ',' + b + ',.35)');
    root.setProperty('--laser-red-a15', 'rgba(' + r + ',' + g + ',' + b + ',.15)');
    root.setProperty('--glow-red-sm', '0 0 12px rgba(' + r + ',' + g + ',' + b + ',.45)');
    root.setProperty('--glow-red-md', '0 0 32px rgba(' + r + ',' + g + ',' + b + ',.35)');
    root.setProperty('--glow-red-lg', '0 0 90px rgba(' + r + ',' + g + ',' + b + ',.28)');
    window.dispatchEvent(new CustomEvent('bo:frequency', { detail: { nm, rgb } }));
  }, [nm]);

  const pick = (clientX) => {
    const bar = barRef.current;
    if (!bar) return;
    const r = bar.getBoundingClientRect();
    const t = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
    setNm(Math.round(MIN + t * (MAX - MIN)));
  };

  React.useEffect(() => {
    const move = (e) => { if (dragRef.current) pick(e.clientX); };
    const up = () => { dragRef.current = false; };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); };
  }, []);

  const stops = [];
  for (let w = MIN; w <= MAX; w += 12) stops.push('rgb(' + wavelengthToRGB(w).join(',') + ') ' + (((w - MIN) / (MAX - MIN)) * 100).toFixed(1) + '%');
  const pct = ((nm - MIN) / (MAX - MIN)) * 100;
  //const nearest = LASER_LINES.reduce((a, b) => (Math.abs(b.nm - nm) < Math.abs(a.nm - nm) ? b : a));
  //const nearest = LASER_LINES.map((a)=>nm==a?a:'')
  const is_laser_line = LASER_LINES.filter((a) => a.nm==nm)
  const nearest = is_laser_line.length ? is_laser_line[0]: {'label':''}
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 7, ...style }}>
      <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, fontWeight: 600, letterSpacing: '.24em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Pick your wavelength</span>
      <div ref={barRef} onMouseDown={(e) => { dragRef.current = true; pick(e.clientX);}} onMouseUp={(e)=>{dragRef.current=false;}}
        role="slider" tabIndex={0} aria-label="Wavelength in nanometres" aria-valuemin={MIN} aria-valuemax={MAX} aria-valuenow={nm} aria-valuetext={nm + ' nanometres'}
        onKeyDown={(e) => {
          const step = e.shiftKey ? 10 : 1;
          if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { setNm((v) => Math.max(MIN, v - step)); e.preventDefault(); }
          else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { setNm((v) => Math.min(MAX, v + step)); e.preventDefault(); }
          else if (e.key === 'Home') { setNm(MIN); e.preventDefault(); }
          else if (e.key === 'End') { setNm(MAX); e.preventDefault(); }
        }}
        style={{ position: 'relative', width: 208, height: 16, borderRadius: 'var(--radius-xs)', background: 'linear-gradient(to right, ' + stops.join(', ') + ')', border: '1px solid var(--ink-hairline)', cursor: 'none', outline: 'none' }}
        onFocus={(e) => { e.currentTarget.style.boxShadow = '0 0 0 3px var(--laser-red-a15)'; }}
        onBlur={(e) => { e.currentTarget.style.boxShadow = 'none'; }}>
        <div style={{ position: 'absolute', top: -3, bottom: -3, left: pct + '%', width: 2, marginLeft: -1, background: '#fff', boxShadow: '0 0 8px ' + css + ', 0 0 16px ' + css }} />
        {LASER_LINES.map((l) => (
          <div key={l.nm} title={l.label + ' ' + l.nm + ' nm'} style={{ position: 'absolute', bottom: -6, left: (((l.nm - MIN) / (MAX - MIN)) * 100) + '%', width: 1, height: 3, marginLeft: -0.5, background: 'var(--text-faint)' }} />
        ))}
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.1em', color: 'var(--text-secondary)' }}>
        {nm} NM<span style={{ color: 'var(--text-faint)' }}> · {nearest.label.toUpperCase()}</span>
      </span>
    </div>
  );
}
// function wvl_stops(dragRef,css){
//   const test =0;
//   console.log('reaches func')
//   return(
//         dragRef.current &&(<div style={{ position: 'absolute', top: -3, bottom: -3, left: 10 + '%', width: 400, marginLeft: -1, background: '#531b1b', boxShadow: '0 0 8px ' + css + ', 0 0 16px ' + css }} />
//         ))
//       }

window.FrequencyPicker = FrequencyPicker;
