import { Suspense, useMemo } from 'react';
import { Canvas, useLoader } from '@react-three/fiber';
import { OrbitControls, Grid } from '@react-three/drei';
import * as THREE from 'three';
import { TextureLoader } from 'three';

function HeightMesh({ url, emboss, depth, inverted, smoothing }) {
  const texture = useLoader(TextureLoader, url);
  const mat = useMemo(() => new THREE.MeshStandardMaterial({
    color: '#bfe3f0', metalness: 0.2, roughness: 0.4,
    displacementMap: texture, displacementScale: inverted ? -emboss : emboss,
    bumpMap: texture, bumpScale: depth * 0.5, transparent: false
  }), [texture, emboss, depth, inverted]);
  const segments = useMemo(() => Math.max(64, Math.round(200 * (1 - smoothing))), [smoothing]);
  return (
    <mesh material={mat} rotation={[-Math.PI / 2.2, 0, 0]} castShadow receiveShadow>
      <planeGeometry args={[8, 8, segments, segments]} />
    </mesh>
  );
}

export default function HeightMapPreview({ imageUrl, emboss = 1.2, depth = 0.8, inverted = false, smoothing = 0.3 }) {
  return (
    <div className="viewport-grid relative h-72 w-full overflow-hidden rounded-2xl border border-white/[0.07]">
      {imageUrl ? (
        <Canvas shadows dpr={[1, 2]} camera={{ position: [0, 6, 9], fov: 42 }}>
          <color attach="background" args={['#070b0f']} />
          <ambientLight intensity={0.5} />
          <directionalLight position={[5, 8, 5]} intensity={1.1} castShadow />
          <Suspense fallback={null}>
            <HeightMesh url={imageUrl} emboss={emboss} depth={depth} inverted={inverted} smoothing={smoothing} />
          </Suspense>
          <Grid args={[24, 24]} cellSize={0.5} sectionSize={2} fadeDistance={20} cellColor="#173139" sectionColor="#234a55" />
          <OrbitControls enablePan enableDamping dampingFactor={0.1} maxPolarAngle={Math.PI / 1.8} />
        </Canvas>
      ) : (
        <div className="grid h-full place-items-center text-center text-sm text-slate-500">
          <div className="max-w-xs">
            <b className="block text-amber-200">3D Preview — final geometry not yet generated</b>
            <p className="mt-2">Upload a drawing to preview a browser-based height map. Real displacement geometry is produced by the geometry engine.</p>
          </div>
        </div>
      )}
      <div className="scanline" />
      {imageUrl && (
        <div className="pointer-events-none absolute left-3 top-3 rounded border border-white/10 bg-black/45 px-2 py-1 text-[10px] text-amber-200/80 backdrop-blur">Browser preview — simulation only</div>
      )}
    </div>
  );
}