"use client"

import { Canvas, useFrame, useThree } from "@react-three/fiber"
import { useMemo, useRef } from "react"
import * as THREE from "three"

// Vertex shader
const vertexShader = `
varying vec2 vUv;

void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`

// Fragment shader with simplex noise for heat distortion
const fragmentShader = `
uniform float uTime;
uniform float uIntensity;

varying vec2 vUv;

// Simplex noise functions
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }

float snoise(vec2 v) {
  const vec4 C = vec4(0.211324865405187, 0.366025403784439,
                      -0.577350269189626, 0.024390243902439);
  vec2 i  = floor(v + dot(v, C.yy));
  vec2 x0 = v - i + dot(i, C.xx);
  vec2 i1;
  i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
  vec4 x12 = x0.xyxy + C.xxzz;
  x12.xy -= i1;
  i = mod289(i);
  vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0))
                   + i.x + vec3(0.0, i1.x, 1.0));
  vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy),
                          dot(x12.zw,x12.zw)), 0.0);
  m = m*m;
  m = m*m;
  vec3 x = 2.0 * fract(p * C.www) - 1.0;
  vec3 h = abs(x) - 0.5;
  vec3 ox = floor(x + 0.5);
  vec3 a0 = x - ox;
  m *= 1.79284291400159 - 0.85373472095314 * (a0*a0 + h*h);
  vec3 g;
  g.x = a0.x * x0.x + h.x * x0.y;
  g.yz = a0.yz * x12.xz + h.yz * x12.yw;
  return 130.0 * dot(m, g);
}

void main() {
  vec2 uv = vUv;

  // Rising heat effect - stronger at bottom, weaker at top
  float yFactor = 1.0 - uv.y;
  yFactor = pow(yFactor, 1.5); // More concentrated at bottom

  // Multi-octave noise for organic feel
  float noise1 = snoise(vec2(uv.x * 6.0, uv.y * 3.0 - uTime * 0.4)) * 0.5;
  float noise2 = snoise(vec2(uv.x * 12.0, uv.y * 6.0 - uTime * 0.6)) * 0.25;
  float noise3 = snoise(vec2(uv.x * 24.0, uv.y * 12.0 - uTime * 0.8)) * 0.125;

  float distortion = (noise1 + noise2 + noise3) * uIntensity * yFactor;

  // Create subtle color shifts for heat shimmer
  float r = 0.5 + distortion * 0.15;
  float g = 0.5 + distortion * 0.08;
  float b = 0.5 - distortion * 0.05;

  // Alpha based on distortion intensity - subtle effect
  float alpha = abs(distortion) * 0.25 * yFactor;

  // Add slight orange tint to positive distortion (heat)
  if (distortion > 0.0) {
    r += distortion * 0.1;
    g += distortion * 0.05;
  }

  gl_FragColor = vec4(r, g, b, alpha);
}
`

function HeatPlane({ intensity }: { intensity: number }) {
  const meshRef = useRef<THREE.Mesh>(null)
  const { viewport } = useThree()

  const uniforms = useMemo(() => ({
    uTime: { value: 0 },
    uIntensity: { value: intensity },
  }), [intensity])

  useFrame((state) => {
    if (meshRef.current) {
      const material = meshRef.current.material as THREE.ShaderMaterial
      material.uniforms.uTime.value = state.clock.elapsedTime
    }
  })

  return (
    <mesh ref={meshRef} scale={[viewport.width, viewport.height, 1]}>
      <planeGeometry args={[1, 1]} />
      <shaderMaterial
        transparent
        blending={THREE.AdditiveBlending}
        depthWrite={false}
        vertexShader={vertexShader}
        fragmentShader={fragmentShader}
        uniforms={uniforms}
      />
    </mesh>
  )
}

export default function HeatDistortionCanvas({ intensity }: { intensity: number }) {
  return (
    <Canvas
      gl={{
        alpha: true,
        antialias: false,
        powerPreference: "low-power"
      }}
      camera={{ position: [0, 0, 1] }}
      style={{ background: "transparent" }}
      dpr={[1, 1.5]} // Limit pixel ratio for performance
    >
      <HeatPlane intensity={intensity} />
    </Canvas>
  )
}
