import React, { useEffect, useRef, memo } from 'react';
import { vuStore } from '../../stores/vuStore';

const SessionTrackVU = memo(function SessionTrackVU({
  lightCount = 16,
  orientation = 'vertical',
  lightWidth = 15,
  lightHeight = 10,
  mixers
}) {
  const containerRef = useRef(null);
  const lightsRef = useRef([]);
  const mixerIdRef = useRef(null);
  const rafIdRef = useRef(null);

  // Update mixerId when mixers prop changes
  useEffect(() => {
    const mixer = mixers?.vuMixer;
    mixerIdRef.current = mixer ? `${mixer.mode ? 'M' : 'P'}${mixer.id}` : null;

    return () => {
      // Cleanup VU state on unmount
      if (mixerIdRef.current) {
        vuStore.removeLevel(mixerIdRef.current);
      }
    };
  }, [mixers]);

  // Animation loop for direct DOM updates - separate from React lifecycle
  useEffect(() => {
    const updateVisuals = () => {
      const mixerId = mixerIdRef.current;

      if (!mixerId) {
        rafIdRef.current = requestAnimationFrame(updateVisuals);
        return;
      }

      const data = vuStore.getLevelSnapshot(mixerId);
      const level = data?.level ?? 0;
      const clipping = data?.clipping ?? false;
      const activeLights = Math.round(level * lightCount);

      // Direct DOM manipulation - no React involvement
      for (let i = 0; i < lightCount; i++) {
        const light = lightsRef.current[i];
        if (!light) continue;

        const positionFromBottom = lightCount - 1 - i;
        const isActive = positionFromBottom < activeLights;

        // Use className assignment for efficient class manipulation
        // (faster than classList.add/remove for multiple classes)
        if (isActive) {
          if (clipping || positionFromBottom >= Math.floor(lightCount * 0.75)) {
            light.className = 'vu-light vu-bg-danger';
          } else if (positionFromBottom >= Math.floor(lightCount * 0.5)) {
            light.className = 'vu-light vu-bg-warning';
          } else {
            light.className = 'vu-light vu-bg-success';
          }
        } else {
          light.className = 'vu-light vu-bg-secondary';
        }
      }

      rafIdRef.current = requestAnimationFrame(updateVisuals);
    };

    rafIdRef.current = requestAnimationFrame(updateVisuals);

    return () => {
      if (rafIdRef.current) {
        cancelAnimationFrame(rafIdRef.current);
      }
    };
  }, [lightCount]);

  // Render ONCE - never re-renders for VU updates
  return (
    <div ref={containerRef} className="vu">
      <div className="d-flex flex-column" style={{ height: `${lightCount * (lightHeight + 1)}px` }}>
        {Array.from({ length: lightCount }).map((_, i) => (
          <div
            key={i}
            ref={el => lightsRef.current[i] = el}
            className="vu-light vu-bg-secondary"
            style={{
              height: `${lightHeight}px`,
              width: '25px',
              marginTop: '1px',
              borderRadius: '2px',
              border: '1px solid #eee'
            }}
          />
        ))}
      </div>
    </div>
  );
});

export default SessionTrackVU;
