import React, { useCallback } from 'react';
import { vuStore } from '../stores/vuStore';

const logger = console;

export default function useVuHelpers() {

  const createQualifiedId = useCallback(mixer => {
    return (mixer.mode ? 'M' : 'P') + mixer.id;
  }, []);

  // Legacy renderVU for backward compatibility
  const renderVU = useCallback((userOptions = {}) => {
    const renderVUDefaults = {
      vuType: 'vertical',
      lightCount: 12,
      lightWidth: 3,
      lightHeight: 17
    };

    const options = { ...renderVUDefaults, ...userOptions };
    const { vuType, lightCount, lightWidth, lightHeight } = options;

    const lights = [];
    for (let i = 0; i < lightCount; i++) {
      lights.push(
        <td
          key={i}
          className="vulight vu-off"
          style={{
            width: vuType === 'horizontal' ? lightWidth : 'auto',
            height: vuType === 'horizontal' ? 'auto' : lightHeight
          }}
        />
      );
    }

    const tableClass = `vu ${vuType}`;
    const tableStyle = vuType === 'horizontal' ? { display: 'inline-block' } : {};

    return (
      <table className={tableClass} style={tableStyle}>
        {vuType === 'vertical' ? (
          <tbody>
            {lights.map((light, index) => (
              <tr key={index}>{light}</tr>
            ))}
          </tbody>
        ) : (
          <tbody>
            <tr>{lights}</tr>
          </tbody>
        )}
      </table>
    );
  }, []);

  // Legacy updateVU for backward compatibility
  const updateVU = useCallback((containerRef, value) => {
    if (!containerRef?.current) return;

    const $track = containerRef.current;
    const $table = $track.querySelector('table');
    if (!$table) return;

    const horizontal = $table.classList.contains('horizontal');
    const $lights = $track.querySelectorAll('td.vulight');

    const lightCount = $lights.length;
    const lights = Math.round(value * lightCount);
    const redSwitch = Math.round(lightCount * 0.6666667);

    // Remove all light classes
    $lights.forEach($light => {
      $light.classList.remove('vu-green-off', 'vu-green-on', 'vu-red-off', 'vu-red-on', 'vu-off');
    });

    // Set the lights
    for (let i = 0; i < lightCount; i++) {
      let colorClass = 'vu-green-';
      let state = 'on';
      if (i >= redSwitch) {
        colorClass = 'vu-red-';
      }
      if (i >= lights) {
        state = 'off';
      }

      const lightIndex = horizontal ? i : lightCount - i - 1;
      if ($lights[lightIndex]) {
        $lights[lightIndex].classList.add(colorClass + state);
      }
    }
  }, []);

  return {
    // External store methods (new)
    updateVuState: vuStore.updateLevel,
    removeVuState: vuStore.removeLevel,
    vuStore, // Expose full store for advanced usage

    // Legacy functions for backward compatibility
    createQualifiedId,
    renderVU,
    updateVU,
  };
}
