'use client';

/**
 * AudioReactiveCover - Album art with audio-reactive animations
 *
 * Uses effects utilities for clean data preparation before render.
 * Click on cover to switch between effect variants.
 *
 * Must be used within HybridAudioProvider context.
 */

import { type ReactNode } from 'react';
import { cn } from '../../../_shared';
import { useHybridAudioLevels, useHybridAudioState } from '../../context/HybridAudioProvider';
import {
  type EffectVariant,
  type EffectIntensity,
  type EffectColorScheme,
  getEffectConfig,
  prepareEffectColors,
  calculateGlowLayers,
  calculateOrbs,
  calculateMeshGradients,
  calculateSpotlight,
  EFFECT_ANIMATIONS,
} from '../../effects';
import { GlowEffect, OrbsEffect, SpotlightEffect, MeshEffect, type GlowEffectData } from './effects';

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

export interface AudioReactiveCoverProps {
  children: ReactNode;
  /** 'sm' | 'md' | 'lg' = fixed sizes; 'full' = stretch to container width (aspect-square) */
  size?: 'sm' | 'md' | 'lg' | 'full';
  variant?: EffectVariant;
  intensity?: EffectIntensity;
  colorScheme?: EffectColorScheme;
  onClick?: () => void;
  className?: string;
}

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

const SIZES = {
  sm: { container: 'w-32 h-32', orbBase: 40 },
  md: { container: 'w-40 h-40', orbBase: 50 },
  lg: { container: 'w-48 h-48', orbBase: 60 },
  full: { container: 'w-full sm:max-w-xs aspect-square mx-auto', orbBase: 60 },
};

// =============================================================================
// COMPONENT
// =============================================================================

export function AudioReactiveCover({
  children,
  size = 'lg',
  variant = 'spotlight',
  intensity = 'medium',
  colorScheme = 'primary',
  onClick,
  className,
}: AudioReactiveCoverProps) {
  // Get audio state from HybridAudioProvider context
  const { isPlaying } = useHybridAudioState();
  const levels = useHybridAudioLevels();

  // =========================================================================
  // PREPARE DATA BEFORE RENDER
  // =========================================================================

  const sizeConfig = SIZES[size];
  const effectConfig = getEffectConfig(intensity);
  const { colors, hueShift } = prepareEffectColors(colorScheme, levels);

  // Calculate scale based on overall level
  const containerScale = 1 + levels.overall * effectConfig.scale;

  // Prepare effect-specific data - NO memoization for real-time reactivity
  const glowData: GlowEffectData | null = variant === 'glow' ? {
    layers: calculateGlowLayers(levels, effectConfig, colors),
    hueShift,
    showPulseRings: levels.bass > 0.5,
    showSparkle: levels.high > 0.4,
  } : null;

  const orbsData = variant === 'orbs'
    ? calculateOrbs(levels, effectConfig, colors, sizeConfig.orbBase)
    : null;

  const meshData = variant === 'mesh'
    ? calculateMeshGradients(levels, effectConfig, colors)
    : null;

  const spotlightData = variant === 'spotlight'
    ? calculateSpotlight(levels, effectConfig, colors, levels.mid * 360)
    : null;

  // =========================================================================
  // RENDER
  // =========================================================================

  return (
    <div
      className={cn('relative', sizeConfig.container, className)}
      style={{
        transform: `scale(${containerScale})`,
        transition: 'transform 0.1s ease-out',
      }}
    >
      {/* Effect layers container - under cover, non-interactive */}
      <div className="absolute inset-0 z-0 pointer-events-none overflow-visible">
        {glowData && (
          <GlowEffect data={glowData} colors={colors} isPlaying={isPlaying} />
        )}

        {orbsData && (
          <OrbsEffect orbs={orbsData} blur={effectConfig.blur} isPlaying={isPlaying} />
        )}

        {spotlightData && (
          <SpotlightEffect data={spotlightData} colors={colors} blur={effectConfig.blur} isPlaying={isPlaying} />
        )}

        {meshData && (
          <MeshEffect gradients={meshData} blur={effectConfig.blur} isPlaying={isPlaying} />
        )}
      </div>

      {/* Content (cover art) */}
      <div
        className="relative w-full h-full rounded-lg overflow-hidden shadow-2xl z-10 bg-background cursor-pointer"
        onClick={onClick}
        role={onClick ? 'button' : undefined}
        tabIndex={onClick ? 0 : undefined}
        onKeyDown={onClick ? (e) => e.key === 'Enter' && onClick() : undefined}
      >
        {children}
      </div>

      {/* Inject animations once */}
      <style dangerouslySetInnerHTML={{ __html: EFFECT_ANIMATIONS }} />
    </div>
  );
}

export default AudioReactiveCover;
