import { useEffect, type ReactNode } from 'react';
import { Canvas, type CanvasProps } from '@react-three/fiber';
import { isWebGLSupported } from '../lib/webgl-detect';
import { useCaptureStore } from '../store/captureStore';
import WebglErrorBoundary from './WebglErrorBoundary';

interface SceneCanvasProps extends CanvasProps {
  fallback: ReactNode;
}

function CanvasInner({ fallback: _, shadows, ...canvasProps }: SceneCanvasProps) {
  const registerCanvas = useCaptureStore((s) => s.registerCanvas);
  const unregisterCanvas = useCaptureStore((s) => s.unregisterCanvas);

  useEffect(() => () => unregisterCanvas(), [unregisterCanvas]);

  // Suprimir avisos de depreciação conhecidos do Three.js (r185) que o R3F ainda aciona
  useEffect(() => {
    const originalWarn = console.warn;
    console.warn = (...args) => {
      if (typeof args[0] === 'string' && (args[0].includes('THREE.Clock') || args[0].includes('THREE.WebGLShadowMap'))) {
        return;
      }
      originalWarn(...args);
    };
    return () => {
      console.warn = originalWarn;
    };
  }, []);

  // O R3F v9 usa PCFSoftShadowMap por padrão, que está deprecado no Three r185.
  // Mudar para PCFShadowMap (1) via propriedade shadows.
  const shadowConfig = shadows === true ? { type: 1 as any } : shadows;

  return (
    <Canvas
      frameloop="demand"
      {...canvasProps}
      shadows={shadowConfig}
      onCreated={(state) => {
        registerCanvas(state.gl.domElement);
        canvasProps.onCreated?.(state);
      }}
    />
  );
}

export default function SceneCanvas({ fallback, style, className, ...rest }: SceneCanvasProps) {
  if (!isWebGLSupported()) {
    return (
      <div
        style={{ width: '100%', height: '100%', minHeight: '500px', borderRadius: 'var(--radius-lg)', overflow: 'hidden', ...style }}
        className={className}
      >
        {fallback}
      </div>
    );
  }

  return (
    <div
      style={{ width: '100%', height: '100%', minHeight: '500px', borderRadius: 'var(--radius-lg)', overflow: 'hidden', ...style }}
      className={`${className ?? ''} glass-panel`}
    >
      <WebglErrorBoundary fallback={fallback}>
        <CanvasInner {...rest} fallback={fallback} />
      </WebglErrorBoundary>
    </div>
  );
}
