// EL3AB Juice Engine — particles, shake, counters, haptics, glow, bounce
import { emoji } from './theme.js';

// ============ PARTICLES ============
const particleContainer = document.createElement('div');
particleContainer.id = 'particles';
particleContainer.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:9999;overflow:hidden;';
document.body.appendChild(particleContainer);

export function burst(x, y, options = {}) {
  const { count = 12, colors = ['var(--gold)', 'var(--gold-soft)', '#FFE082'], size = 8, spread = 120, duration = 800, gravity = true, type = 'circle' } = options;

  for (let i = 0; i < count; i++) {
    const el = document.createElement('div');
    const color = colors[Math.floor(Math.random() * colors.length)];
    const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5) * 0.5;
    const velocity = spread * (0.5 + Math.random() * 0.5);
    const dx = Math.cos(angle) * velocity;
    const dy = Math.sin(angle) * velocity - (gravity ? 60 : 0);
    const s = size * (0.5 + Math.random() * 0.8);
    const rotation = Math.random() * 360;

    if (type === 'star') {
      el.innerHTML = emoji('particle_star', '✦', s * 2);
      el.style.cssText = `position:absolute;left:${x}px;top:${y}px;font-size:${s * 2}px;color:${color};pointer-events:none;z-index:9999;`;
    } else {
      el.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:${s}px;height:${s}px;background:${color};border-radius:${type === 'square' ? '2px' : '50%'};pointer-events:none;z-index:9999;`;
    }

    particleContainer.appendChild(el);

    el.animate([
      { transform: `translate(0,0) scale(1) rotate(0deg)`, opacity: 1 },
      { transform: `translate(${dx}px,${dy + (gravity ? 200 : 0)}px) scale(0) rotate(${rotation}deg)`, opacity: 0 }
    ], { duration: duration + Math.random() * 300, easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', fill: 'forwards' })
    .onfinish = () => el.remove();
  }
}

export function coinBurst(x, y, count = 8) {
  burst(x, y, { count, colors: ['var(--gold)', 'var(--gold-soft)', 'var(--gold-soft)', '#FFC107'], size: 10, spread: 100, type: 'circle' });
}

export function starBurst(x, y, count = 6) {
  burst(x, y, { count, colors: ['var(--gold)', 'var(--gold-soft)', '#FFF'], size: 8, spread: 80, type: 'star' });
}

export function confetti(x, y, count = 30) {
  burst(x, y, { count, colors: ['var(--error)', 'var(--blue)', 'var(--emerald)', 'var(--warning)', 'var(--purple)', 'var(--pink)'], size: 8, spread: 200, duration: 1200, type: 'square' });
}

// ============ COIN FLY TO TARGET ============
export function coinFlyTo(fromX, fromY, targetSelector, count = 5) {
  const target = document.querySelector(targetSelector);
  if (!target) return;
  const rect = target.getBoundingClientRect();
  const toX = rect.left + rect.width / 2;
  const toY = rect.top + rect.height / 2;

  for (let i = 0; i < count; i++) {
    const el = document.createElement('div');
    const startX = fromX + (Math.random() - 0.5) * 40;
    const startY = fromY + (Math.random() - 0.5) * 40;
    el.style.cssText = `position:fixed;left:${startX}px;top:${startY}px;width:12px;height:12px;background:var(--gold);border-radius:50%;box-shadow:0 0 6px var(--gold);z-index:9999;pointer-events:none;`;
    particleContainer.appendChild(el);

    el.animate([
      { transform: 'scale(1)', left: startX + 'px', top: startY + 'px', opacity: 1 },
      { transform: 'scale(0.6)', left: toX + 'px', top: toY + 'px', opacity: 0.8 }
    ], { duration: 600 + i * 80, easing: 'cubic-bezier(0.4, 0, 0.2, 1)', fill: 'forwards', delay: i * 60 })
    .onfinish = () => { el.remove(); if (i === count - 1) pulseElement(target); };
  }
}

// ============ SCREEN SHAKE ============
export function shake(element, intensity = 4, duration = 300) {
  const el = element || document.getElementById('game');
  if (!el) return;
  const keyframes = [];
  const steps = Math.floor(duration / 30);
  for (let i = 0; i < steps; i++) {
    const progress = i / steps;
    const decay = 1 - progress;
    const x = (Math.random() - 0.5) * intensity * decay * 2;
    const y = (Math.random() - 0.5) * intensity * decay * 2;
    keyframes.push({ transform: `translate(${x}px, ${y}px)` });
  }
  keyframes.push({ transform: 'translate(0,0)' });
  el.animate(keyframes, { duration, easing: 'linear' });
}

// ============ NUMBER COUNTER ============
export function countTo(element, target, options = {}) {
  const { duration = 600, prefix = '', suffix = '', color } = options;
  if (!element) return;
  const start = parseInt(element.textContent.replace(/[^0-9-]/g, '')) || 0;
  const diff = target - start;
  if (diff === 0) { element.textContent = prefix + target + suffix; return; }

  const startTime = performance.now();
  if (color) element.style.color = color;

  function tick(now) {
    const progress = Math.min((now - startTime) / duration, 1);
    const eased = 1 - Math.pow(1 - progress, 3);
    const current = Math.round(start + diff * eased);
    element.textContent = prefix + current + suffix;
    if (progress < 1) requestAnimationFrame(tick);
    else { element.textContent = prefix + target + suffix; pulseElement(element); }
  }
  requestAnimationFrame(tick);
}

// ============ HAPTIC ============
export function haptic(pattern = 10) {
  if (navigator.vibrate) {
    navigator.vibrate(Array.isArray(pattern) ? pattern : [pattern]);
  }
}

export function hapticLight() { haptic(8); }
export function hapticMedium() { haptic(15); }
export function hapticHeavy() { haptic([20, 30, 20]); }
export function hapticSuccess() { haptic([10, 50, 10, 50, 30]); }
export function hapticError() { haptic([50, 30, 50]); }

// ============ GLOW / PULSE ============
export function pulseElement(el, color = 'var(--gold)', duration = 400) {
  if (!el) return;
  el.animate([
    { transform: 'scale(1)', boxShadow: `0 0 0px ${color}` },
    { transform: 'scale(1.1)', boxShadow: `0 0 20px ${color}` },
    { transform: 'scale(1)', boxShadow: `0 0 0px ${color}` }
  ], { duration, easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' });
}

export function glowElement(el, color = 'var(--gold)') {
  if (!el) return;
  el.style.boxShadow = `0 0 12px ${color}`;
  el.style.transition = 'box-shadow 0.3s';
  setTimeout(() => { el.style.boxShadow = ''; }, 1500);
}

// ============ BOUNCE / SLAM ============
export function slamIn(el, options = {}) {
  if (!el) return;
  const { scale = 1.3, duration = 400 } = options;
  el.animate([
    { transform: `scale(${scale})`, opacity: 0 },
    { transform: 'scale(0.95)', opacity: 1, offset: 0.6 },
    { transform: 'scale(1.02)', offset: 0.8 },
    { transform: 'scale(1)', opacity: 1 }
  ], { duration, easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)', fill: 'forwards' });
}

export function bounceIn(el, delay = 0) {
  if (!el) return;
  el.style.opacity = '0';
  setTimeout(() => {
    el.style.opacity = '1';
    el.animate([
      { transform: 'scale(0) translateY(20px)', opacity: 0 },
      { transform: 'scale(1.08)', opacity: 1, offset: 0.6 },
      { transform: 'scale(0.96)', offset: 0.8 },
      { transform: 'scale(1)', opacity: 1 }
    ], { duration: 450, easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)', fill: 'forwards' });
  }, delay);
}

export function slideUpBounce(el, delay = 0) {
  if (!el) return;
  el.style.opacity = '0';
  setTimeout(() => {
    el.style.opacity = '1';
    el.animate([
      { transform: 'translateY(40px)', opacity: 0 },
      { transform: 'translateY(-4px)', opacity: 1, offset: 0.7 },
      { transform: 'translateY(0)', opacity: 1 }
    ], { duration: 400, easing: 'cubic-bezier(0.16, 1, 0.3, 1)', fill: 'forwards' });
  }, delay);
}

export function stagger(elements, animFn, baseDelay = 0, interval = 60) {
  elements.forEach((el, i) => animFn(el, baseDelay + i * interval));
}

// ============ FLASH ============
export function flash(color = '#fff', duration = 150) {
  const el = document.createElement('div');
  el.style.cssText = `position:fixed;inset:0;background:${color};z-index:9998;pointer-events:none;`;
  document.body.appendChild(el);
  el.animate([{ opacity: 0.6 }, { opacity: 0 }], { duration, fill: 'forwards' })
    .onfinish = () => el.remove();
}

// ============ SCREEN FLASH (full-screen color overlay) ============
export function screenFlash(color = 'rgba(255,255,255,0.2)', duration = 400) {
  const el = document.createElement('div');
  el.style.cssText = `position:fixed;inset:0;background:${color};pointer-events:none;z-index:9998;`;
  document.body.appendChild(el);
  el.animate([{opacity:1},{opacity:0}], {duration}).onfinish = () => el.remove();
}

// ============ FLOATING / BREATHING ============
export function breathe(el, options = {}) {
  if (!el) return;
  const { scale = 1.02, duration = 2000, glow = false, glowColor = 'var(--gold)' } = options;
  const keyframes = glow
    ? [{ transform: 'scale(1)', boxShadow: `0 0 4px ${glowColor}` }, { transform: `scale(${scale})`, boxShadow: `0 0 16px ${glowColor}` }]
    : [{ transform: 'scale(1)' }, { transform: `scale(${scale})` }];
  return el.animate(keyframes, { duration, iterations: Infinity, direction: 'alternate', easing: 'ease-in-out' });
}

export function floatY(el, amount = 6, duration = 3000) {
  if (!el) return;
  return el.animate([
    { transform: 'translateY(0)' },
    { transform: `translateY(-${amount}px)` }
  ], { duration, iterations: Infinity, direction: 'alternate', easing: 'ease-in-out' });
}
