const ANIMATION_BY_CATEGORY = {
  'Globos':           'animRiseUp',
  'Flores':           'animBounceIn',
  'Mesas':            'animSlideRight',
  'Manteles':         'animSlideRight',
  'Pedestales':       'animDropDown',
  'Backdrops':        'animFadeIn',
  'Accesorios':       'animFloatIn',
  'Letras luminosas': 'animFlipInY',
  'Luces':            'animFadeIn',
};

const ANIM_DURATION_MS = 480;

function SceneCanvas({ sceneAssets = [], assets = [], finalImage = null, autoPlay = true, onComplete }) {
  const [playing, setPlaying] = React.useState(autoPlay);
  const [showFinal, setShowFinal] = React.useState(false);
  const [replayKey, setReplayKey] = React.useState(0);
  const [outPlaying, setOutPlaying] = React.useState(false);

  const resolvedAssets = React.useMemo(() =>
    sceneAssets
      .map(sa => {
        const asset = assets.find(a => String(a.id) === String(sa.assetId));
        return asset ? { ...sa, asset } : null;
      })
      .filter(Boolean),
    [sceneAssets, assets]
  );

  const maxDelay = resolvedAssets.reduce((max, sa) => Math.max(max, sa.delay || 0), 0);
  const totalDuration = maxDelay + ANIM_DURATION_MS;

  // After all enter animations finish, trigger exit animations then show final image
  React.useEffect(() => {
    if (!playing || !resolvedAssets.length) return;
    setShowFinal(false);
    setOutPlaying(false);

    const hasOut = resolvedAssets.some(sa => sa.animOut && sa.animOut !== 'none');

    if (hasOut) {
      // Start exit animations after entrance completes
      const outTimer = setTimeout(() => setOutPlaying(true), totalDuration + 300);
      // Show final after exit animations
      const finalTimer = setTimeout(() => {
        setShowFinal(true);
        if (onComplete) onComplete();
      }, totalDuration + 300 + ANIM_DURATION_MS + 200);
      return () => { clearTimeout(outTimer); clearTimeout(finalTimer); };
    } else {
      const timer = setTimeout(() => {
        setShowFinal(true);
        if (onComplete) onComplete();
      }, totalDuration + 200);
      return () => clearTimeout(timer);
    }
  }, [playing, replayKey, totalDuration]);

  const handleReplay = () => {
    setPlaying(false);
    setShowFinal(false);
    setOutPlaying(false);
    setTimeout(() => { setPlaying(true); setReplayKey(k => k + 1); }, 50);
  };

  if (!resolvedAssets.length) {
    if (finalImage) {
      return React.createElement('img', {
        src: finalImage,
        style: { width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }
      });
    }
    return null;
  }

  return React.createElement('div', {
    style: { position: 'relative', width: '100%', paddingTop: '75%' }
  },
    React.createElement('div', {
      key: replayKey,
      style: {
        position: 'absolute', inset: 0,
        overflow: 'hidden',
        borderRadius: 'inherit',
        background: 'var(--bg, #FAF0E8)',
      }
    },
      resolvedAssets.map((sa, i) => {
        const animIn = sa.animIn || ANIMATION_BY_CATEGORY[sa.asset.category] || 'animFadeIn';
        const animOut = sa.animOut && sa.animOut !== 'none' ? sa.animOut : null;
        const delayS = ((sa.delay || 0) / 1000).toFixed(2);

        let animation;
        if (outPlaying && animOut) {
          animation = `${animOut} ${ANIM_DURATION_MS}ms ease both`;
        } else if (playing) {
          animation = `${animIn} ${ANIM_DURATION_MS}ms cubic-bezier(0.34,1.3,0.64,1) ${delayS}s both`;
        } else {
          animation = 'none';
        }

        return React.createElement('img', {
          key: `${sa.assetId}-${i}`,
          src: sa.asset.image,
          alt: sa.asset.name,
          style: {
            position: 'absolute',
            left: `${sa.x || 0}%`,
            top: `${sa.y || 0}%`,
            width: `${(sa.scale || 1) * 80}px`,
            zIndex: (sa.z || 0) + 1,
            animation,
            opacity: playing ? undefined : 1,
            objectFit: 'contain',
            pointerEvents: 'none',
            userSelect: 'none',
          }
        });
      }),

      finalImage && showFinal && React.createElement('img', {
        src: finalImage,
        style: {
          position: 'absolute', inset: 0,
          width: '100%', height: '100%',
          objectFit: 'cover',
          animation: 'fadeInOverlay 0.6s ease both',
          zIndex: 999,
        }
      }),

      showFinal && React.createElement('button', {
        onClick: handleReplay,
        style: {
          position: 'absolute', bottom: 10, right: 10,
          zIndex: 1000,
          background: 'rgba(255,255,255,0.85)',
          border: '1px solid var(--border, #E8D8CC)',
          borderRadius: 20,
          padding: '4px 12px',
          fontSize: 12,
          cursor: 'pointer',
          color: 'var(--text, #3A2A20)',
        }
      }, '↺ Ver de nuevo')
    )
  );
}

window.SceneCanvas = SceneCanvas;
