import { useEffect, useRef } from 'react';

interface Props {
  className?: string;
}

export default function Live2DCat({ className }: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    let mounted = true;
    const canvas = canvasRef.current;
    if (!canvas) return;

    let app: any = null;

    const init = async () => {
      try {
        const pixi = await import('pixi.js');
        const { Live2DModel } = await import('pixi-live2d-display/cubism4');
        (Live2DModel as any).registerTicker(pixi.Ticker as any);

        const w = canvas.clientWidth || 120;
        const h = canvas.clientHeight || 120;

        // Use explicit CanvasRenderer to avoid WebGL context conflict with KiraAvatar
        app = new pixi.Application({
          view: canvas,
          width: w,
          height: h,
          antialias: true,
          resolution: Math.min(window.devicePixelRatio || 1, 2),
          backgroundAlpha: 0,
          autoDensity: true,
          // Use WebGL1 context (more compatible with separate contexts)
          preferWebGLVersion: 1,
        } as any);
        if (!mounted) { app.destroy(true); return; }

        const model = await Live2DModel.from('/live2d/models/little-cat/LittleCat.model3.json', {
          autoInteract: false,
        });
        if (!mounted) { app.destroy(true); return; }

        const sw = app.screen.width;
        const sh = app.screen.height;
        const s = Math.min((sw * 0.85) / model.width, (sh * 0.85) / model.height);
        model.scale.set(s);
        model.anchor.set(0.5, 0.5);
        model.position.set(sw / 2, sh / 2);

        app.stage.addChild(model as any);
        (model as any).isInteractive = () => false;

        try { model.motion('Idle'); } catch { /* */ }
      } catch (e) {
        console.warn('[Live2DCat]', e);
      }
    };

    init();

    return () => {
      mounted = false;
      if (app) { app.destroy(true, { children: true }); }
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      className={className}
      style={{ display: 'block' }}
    />
  );
}
