'use client';

/**
 * useVisualization - Hook for managing audio visualization settings
 *
 * Persists settings in localStorage for user preferences
 * Uses React Context for shared state between components
 */

import { createContext, useContext, useCallback, useMemo, type ReactNode } from 'react';
import { useLocalStorage } from '../../_shared';

// =============================================================================
// TYPES
// =============================================================================

export type VisualizationVariant = 'glow' | 'orbs' | 'spotlight' | 'mesh' | 'none';
export type VisualizationIntensity = 'subtle' | 'medium' | 'strong';
export type VisualizationColorScheme = 'primary' | 'vibrant' | 'cool' | 'warm';

export interface VisualizationSettings {
  /** Enable reactive cover animation */
  enabled: boolean;
  /** Visual effect variant */
  variant: VisualizationVariant;
  /** Effect intensity */
  intensity: VisualizationIntensity;
  /** Color scheme */
  colorScheme: VisualizationColorScheme;
  /** Playback volume (0-1) */
  volume: number;
  /** Loop playback */
  isLooping: boolean;
}

export interface UseVisualizationReturn {
  /** Current settings */
  settings: VisualizationSettings;
  /** Toggle visualization on/off */
  toggle: () => void;
  /** Set specific setting */
  setSetting: <K extends keyof VisualizationSettings>(
    key: K,
    value: VisualizationSettings[K]
  ) => void;
  /** Cycle to next variant */
  nextVariant: () => void;
  /** Cycle to next intensity */
  nextIntensity: () => void;
  /** Cycle to next color scheme */
  nextColorScheme: () => void;
  /** Reset to defaults */
  reset: () => void;
}

// Backward compatibility alias
export type UseAudioVisualizationReturn = UseVisualizationReturn;

// =============================================================================
// CONSTANTS
// =============================================================================

const STORAGE_KEY = 'audio-player-settings';

const DEFAULT_SETTINGS: VisualizationSettings = {
  enabled: true,
  variant: 'spotlight',
  intensity: 'medium',
  colorScheme: 'primary',
  volume: 1,
  isLooping: false,
};

const VARIANTS: VisualizationVariant[] = ['spotlight', 'glow', 'orbs', 'mesh', 'none'];
const INTENSITIES: VisualizationIntensity[] = ['subtle', 'medium', 'strong'];
const COLOR_SCHEMES: VisualizationColorScheme[] = ['primary', 'vibrant', 'cool', 'warm'];

// =============================================================================
// CONTEXT
// =============================================================================

const VisualizationContext = createContext<UseVisualizationReturn | null>(null);

// =============================================================================
// PROVIDER
// =============================================================================

export interface VisualizationProviderProps {
  children: ReactNode;
}

export function VisualizationProvider({ children }: VisualizationProviderProps) {
  const value = useVisualizationState();
  return (
    <VisualizationContext.Provider value={value}>
      {children}
    </VisualizationContext.Provider>
  );
}

// =============================================================================
// INTERNAL HOOK (creates the actual state)
// =============================================================================

function useVisualizationState(): UseVisualizationReturn {
  const [settings, setSettings] = useLocalStorage<VisualizationSettings>(
    STORAGE_KEY,
    DEFAULT_SETTINGS
  );

  const toggle = useCallback(() => {
    setSettings((prev) => ({ ...prev, enabled: !prev.enabled }));
  }, [setSettings]);

  const setSetting = useCallback(
    <K extends keyof VisualizationSettings>(
      key: K,
      value: VisualizationSettings[K]
    ) => {
      setSettings((prev) => ({ ...prev, [key]: value }));
    },
    [setSettings]
  );

  const nextVariant = useCallback(() => {
    setSettings((prev) => {
      const currentIndex = VARIANTS.indexOf(prev.variant);
      const nextIndex = (currentIndex + 1) % VARIANTS.length;
      return { ...prev, variant: VARIANTS[nextIndex] };
    });
  }, [setSettings]);

  const nextIntensity = useCallback(() => {
    setSettings((prev) => {
      const currentIndex = INTENSITIES.indexOf(prev.intensity);
      const nextIndex = (currentIndex + 1) % INTENSITIES.length;
      return { ...prev, intensity: INTENSITIES[nextIndex] };
    });
  }, [setSettings]);

  const nextColorScheme = useCallback(() => {
    setSettings((prev) => {
      const currentIndex = COLOR_SCHEMES.indexOf(prev.colorScheme);
      const nextIndex = (currentIndex + 1) % COLOR_SCHEMES.length;
      return { ...prev, colorScheme: COLOR_SCHEMES[nextIndex] };
    });
  }, [setSettings]);

  const reset = useCallback(() => {
    setSettings(DEFAULT_SETTINGS);
  }, [setSettings]);

  return useMemo(
    () => ({
      settings,
      toggle,
      setSetting,
      nextVariant,
      nextIntensity,
      nextColorScheme,
      reset,
    }),
    [settings, toggle, setSetting, nextVariant, nextIntensity, nextColorScheme, reset]
  );
}

// =============================================================================
// HOOK (uses context when available)
// =============================================================================

export function useVisualization(): UseVisualizationReturn {
  const context = useContext(VisualizationContext);

  // Always call the fallback hooks (React hooks rules require consistent calls)
  const fallbackState = useVisualizationState();

  // If inside a provider, use shared context; otherwise use fallback
  return context ?? fallbackState;
}

// Backward compatibility alias
export const useAudioVisualization = useVisualization;

// =============================================================================
// VARIANT INFO
// =============================================================================

export const VARIANT_INFO: Record<VisualizationVariant, { label: string; icon: string }> = {
  spotlight: { label: 'Spotlight', icon: '💫' },
  glow: { label: 'Glow', icon: '✨' },
  orbs: { label: 'Orbs', icon: '🔮' },
  mesh: { label: 'Mesh', icon: '🌈' },
  none: { label: 'Off', icon: '⭕' },
};

export const INTENSITY_INFO: Record<VisualizationIntensity, { label: string }> = {
  subtle: { label: 'Subtle' },
  medium: { label: 'Medium' },
  strong: { label: 'Strong' },
};

export const COLOR_SCHEME_INFO: Record<VisualizationColorScheme, { label: string; preview: string }> = {
  primary: { label: 'Primary', preview: '🔵' },
  vibrant: { label: 'Vibrant', preview: '🌈' },
  cool: { label: 'Cool', preview: '💙' },
  warm: { label: 'Warm', preview: '🔥' },
};
