"use client";

import { useEffect, useRef, useState } from "react";
import * as THREE from "three";

interface VantaEffectProps {
  effectType?: "globe" | "net" | "waves" | "birds" | "fog" | "cells" | "dots";
  options?: {
    mouseControls?: boolean;
    touchControls?: boolean;
    gyroControls?: boolean;
    color?: number;
    color2?: number;
    backgroundColor?: number;
    size?: number;
    speed?: number;
    [key: string]: any;
  };
  className?: string;
  style?: React.CSSProperties;
}

export default function VantaEffect({
  effectType = "globe",
  options = {},
  className = "",
  style = {},
}: VantaEffectProps) {
  const vantaRef = useRef<HTMLDivElement>(null);
  const [vantaEffect, setVantaEffect] = useState<{ destroy: () => void } | null>(null);

  useEffect(() => {
    let effect: { destroy: () => void } | undefined;

    const loadVantaEffect = async () => {
      try {
        let vantaModule;
        
        switch (effectType) {
          case "globe":
            vantaModule = await import("vanta/dist/vanta.globe.min");
            break;
          case "net":
            vantaModule = await import("vanta/dist/vanta.net.min");
            break;
          case "waves":
            vantaModule = await import("vanta/dist/vanta.waves.min");
            break;
          case "birds":
            vantaModule = await import("vanta/dist/vanta.birds.min");
            break;
          case "fog":
            vantaModule = await import("vanta/dist/vanta.fog.min");
            break;
          case "cells":
            vantaModule = await import("vanta/dist/vanta.cells.min");
            break;
          case "dots":
            vantaModule = await import("vanta/dist/vanta.dots.min");
            break;
          default:
            vantaModule = await import("vanta/dist/vanta.globe.min");
        }

        if (!vantaEffect && vantaRef.current && vantaModule) {
          const defaultOptions = {
            el: vantaRef.current,
            THREE,
            mouseControls: true,
            touchControls: true,
            gyroControls: false,
            ...options,
          };

          const vantaEffectInstance = (vantaModule as any).default(defaultOptions);
          effect = vantaEffectInstance;
          setVantaEffect(vantaEffectInstance);
        }
      } catch (error) {
        console.error(`Failed to load Vanta ${effectType} effect:`, error);
      }
    };

    loadVantaEffect();

    return () => {
      if (effect) {
        effect.destroy();
      }
    };
  }, [effectType]);

  const defaultStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    position: "absolute",
    top: 0,
    left: 0,
    zIndex: 0,
    pointerEvents: "none",
    ...style,
  };

  return (
    <div
      ref={vantaRef}
      className={className}
      style={defaultStyle}
    />
  );
}

