// Animated Trading Candlesticks Background for Client Portal Login
(function(){
  const canvas = document.getElementById('bgCanvas');
  if (!canvas) return;
  
  const ctx = canvas.getContext('2d');
  const container = canvas.parentElement;
  
  let animationId;
  let particles = [];
  let gridLines = [];
  let wavePoints = [];
  let mousePos = { x: 0, y: 0 };
  let time = 0;
  
  // Configuración mejorada
  const config = {
    particleCount: 30,
    gridSpacing: 50,
    waveSpeed: 0.02,
    pulseIntensity: 0.3,
    interactionRadius: 150
  };
  
  class Particle {
    constructor() {
      this.reset();
      this.y = Math.random() * canvas.height;
    }
    
    reset() {
      this.x = -20;
      this.y = Math.random() * canvas.height;
      this.speed = 0.3 + Math.random() * 1.2;
      this.opacity = 0.1 + Math.random() * 0.4;
      this.size = 1.5 + Math.random() * 2.5;
      this.hue = 200 + Math.random() * 60; // Azules y cian
    }
    
    update() {
      this.x += this.speed;
      if (this.x > canvas.width + 20) {
        this.reset();
      }
      
      // Efecto de interacción con mouse
      const dx = this.x - mousePos.x;
      const dy = this.y - mousePos.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < config.interactionRadius) {
        const force = (config.interactionRadius - distance) / config.interactionRadius;
        this.opacity = Math.min(0.8, this.opacity + force * 0.3);
        this.size = Math.min(4, this.size + force * 1.5);
      }
    }
    
    draw() {
      ctx.save();
      ctx.globalAlpha = this.opacity;
      
      // Gradiente radial para las partículas
      const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
      gradient.addColorStop(0, `hsl(${this.hue}, 70%, 60%)`);
      gradient.addColorStop(1, `hsl(${this.hue}, 70%, 30%)`);
      
      ctx.fillStyle = gradient;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fill();
      
      // Efecto de brillo
      ctx.globalAlpha = this.opacity * 0.3;
      ctx.fillStyle = `hsl(${this.hue}, 80%, 80%)`;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size * 0.5, 0, Math.PI * 2);
      ctx.fill();
      
      ctx.restore();
    }
  }
  
  class EnhancedGridLine {
    constructor(isVertical, position) {
      this.isVertical = isVertical;
      this.position = position;
      this.baseOpacity = 0.03 + Math.random() * 0.07;
      this.pulse = Math.random() * Math.PI * 2;
      this.waveOffset = Math.random() * Math.PI * 2;
      this.colorShift = Math.random() * 60;
    }
    
    update() {
      this.pulse += 0.015 + Math.sin(time * 0.001) * 0.01;
      this.waveOffset += 0.008;
    }
    
    draw() {
      // Calcular ondas dinámicas
      const waveIntensity = Math.sin(this.pulse + time * 0.002) * config.pulseIntensity;
      const colorWave = Math.sin(this.waveOffset + time * 0.003) * 30;
      
      // Efecto de proximidad al mouse
      let mouseEffect = 0;
      if (this.isVertical) {
        const distance = Math.abs(this.position - mousePos.x);
        mouseEffect = Math.max(0, (config.interactionRadius - distance) / config.interactionRadius);
      } else {
        const distance = Math.abs(this.position - mousePos.y);
        mouseEffect = Math.max(0, (config.interactionRadius - distance) / config.interactionRadius);
      }
      
      const finalOpacity = this.baseOpacity + waveIntensity + mouseEffect * 0.4;
      const hue = 200 + this.colorShift + colorWave + mouseEffect * 40;
      
      ctx.save();
      ctx.globalAlpha = Math.max(0, Math.min(0.6, finalOpacity));
      
      // Gradiente para las líneas
      let gradient;
      if (this.isVertical) {
        gradient = ctx.createLinearGradient(this.position, 0, this.position, canvas.height);
      } else {
        gradient = ctx.createLinearGradient(0, this.position, canvas.width, this.position);
      }
      
      gradient.addColorStop(0, `hsla(${hue}, 60%, 50%, 0)`);
      gradient.addColorStop(0.3, `hsla(${hue}, 70%, 60%, ${finalOpacity})`);
      gradient.addColorStop(0.7, `hsla(${hue}, 70%, 60%, ${finalOpacity})`);
      gradient.addColorStop(1, `hsla(${hue}, 60%, 50%, 0)`);
      
      ctx.strokeStyle = gradient;
      ctx.lineWidth = 1 + mouseEffect * 2;
      ctx.beginPath();
      
      if (this.isVertical) {
        ctx.moveTo(this.position, 0);
        ctx.lineTo(this.position, canvas.height);
      } else {
        ctx.moveTo(0, this.position);
        ctx.lineTo(canvas.width, this.position);
      }
      
      ctx.stroke();
      
      // Efecto de brillo adicional
      if (mouseEffect > 0.3) {
        ctx.globalAlpha = mouseEffect * 0.2;
        ctx.strokeStyle = `hsl(${hue + 20}, 80%, 80%)`;
        ctx.lineWidth = 3;
        ctx.stroke();
      }
      
      ctx.restore();
    }
  }
  
  class WavePoint {
    constructor() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;
      this.radius = 0;
      this.maxRadius = 80 + Math.random() * 120;
      this.speed = 0.5 + Math.random() * 1;
      this.opacity = 0.8;
      this.hue = 180 + Math.random() * 80;
    }
    
    update() {
      this.radius += this.speed;
      this.opacity = Math.max(0, 1 - (this.radius / this.maxRadius));
      
      if (this.radius > this.maxRadius) {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.radius = 0;
        this.opacity = 0.8;
        this.hue = 180 + Math.random() * 80;
      }
    }
    
    draw() {
      if (this.opacity <= 0) return;
      
      ctx.save();
      ctx.globalAlpha = this.opacity * 0.3;
      ctx.strokeStyle = `hsl(${this.hue}, 60%, 50%)`;
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
      ctx.stroke();
      
      // Anillo interior
      ctx.globalAlpha = this.opacity * 0.1;
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius * 0.7, 0, Math.PI * 2);
      ctx.stroke();
      
      ctx.restore();
    }
  }
  
  function initializeElements() {
    particles = [];
    gridLines = [];
    wavePoints = [];
    
    // Crear partículas mejoradas
    for (let i = 0; i < config.particleCount; i++) {
      particles.push(new Particle());
    }
    
    // Crear cuadrículas mejoradas
    for (let x = 0; x < canvas.width; x += config.gridSpacing) {
      gridLines.push(new EnhancedGridLine(true, x));
    }
    for (let y = 0; y < canvas.height; y += config.gridSpacing) {
      gridLines.push(new EnhancedGridLine(false, y));
    }
    
    // Crear puntos de onda
    for (let i = 0; i < 3; i++) {
      wavePoints.push(new WavePoint());
    }
  }
  
  function animate() {
    time += 16; // Aproximadamente 60fps
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Fondo base con gradiente dinámico
    const bgGradient = ctx.createRadialGradient(
      canvas.width * 0.3, canvas.height * 0.7, 0,
      canvas.width * 0.3, canvas.height * 0.7, canvas.width
    );
    bgGradient.addColorStop(0, 'rgba(11,23,52,0.03)');
    bgGradient.addColorStop(1, 'rgba(15,30,70,0.01)');
    ctx.fillStyle = bgGradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Dibujar ondas expansivas
    wavePoints.forEach(wave => {
      wave.update();
      wave.draw();
    });
    
    // Dibujar cuadrículas mejoradas
    gridLines.forEach(line => {
      line.update();
      line.draw();
    });
    
    // Dibujar partículas mejoradas
    particles.forEach(particle => {
      particle.update();
      particle.draw();
    });
    
    animationId = requestAnimationFrame(animate);
  }
  
  function resize() {
    const rect = container.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
    
    initializeElements();
  }
  
  function start() {
    if (animationId) cancelAnimationFrame(animationId);
    resize();
    animate();
  }
  
  function stop() {
    if (animationId) {
      cancelAnimationFrame(animationId);
      animationId = null;
    }
  }
  
  // Event listeners
  const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(resize) : null;
  if (ro) ro.observe(container);
  window.addEventListener('resize', resize, { passive: true });
  
  // Seguimiento del mouse para efectos interactivos
  canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    mousePos.x = e.clientX - rect.left;
    mousePos.y = e.clientY - rect.top;
  }, { passive: true });
  
  canvas.addEventListener('mouseleave', () => {
    mousePos.x = -1000;
    mousePos.y = -1000;
  }, { passive: true });
  
  // Pausar animaciones cuando la pestaña no está visible
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      stop();
    } else {
      start();
    }
  });
  
  // Inicializar
  start();
})();