'use client'
// src/components/projects/SensorMarker.tsx
// Input: sensor, position [x,y,z], selected, onClick
// Output: r3f sphere mesh cliquable, pulsant si online, coloré selon status
// Rationale: capteurs positionnés dans la scène 3D, cliquables pour ouvrir le panneau

import { useRef, useState } from 'react'
import { useFrame } from '@react-three/fiber'
import { Html } from '@react-three/drei'
import type { Mesh } from 'three'
import type { Sensor } from '@/types'

const STATUS_COLORS: Record<string, string> = {
  online:      '#34D399',
  offline:     '#4E6070',
  warning:     '#FBBF24',
  calibrating: '#60A5FA',
}

// Pour les statuts r3f (hex → color string)
const STATUS_EMISSIVE: Record<string, string> = {
  online:      '#34D399',
  offline:     '#000000',
  warning:     '#FBBF24',
  calibrating: '#60A5FA',
}

export interface SensorMarkerProps {
  sensor: Sensor
  position: [number, number, number]
  selected: boolean
  onClick: (id: string) => void
}

export function SensorMarker({ sensor, position, selected, onClick }: SensorMarkerProps) {
  const meshRef = useRef<Mesh>(null)
  const haloRef = useRef<Mesh>(null)
  const [hovered, setHovered] = useState(false)

  const color = STATUS_COLORS[sensor.status] ?? '#4E6070'
  const emissive = STATUS_EMISSIVE[sensor.status] ?? '#000000'
  const isPulsing = sensor.status === 'online'

  useFrame(({ clock }) => {
    if (!meshRef.current) return
    const t = clock.getElapsedTime()

    // Pulse scale si online
    if (isPulsing) {
      const pulse = 1 + Math.sin(t * 2.5) * 0.1
      meshRef.current.scale.setScalar(hovered ? 1.4 * pulse : pulse)
    } else {
      meshRef.current.scale.setScalar(hovered ? 1.4 : 1.0)
    }

    // Halo pulsant si sélectionné
    if (haloRef.current) {
      if (selected) {
        const haloPulse = 1.5 + Math.sin(t * 2.5) * 0.3
        haloRef.current.scale.setScalar(haloPulse)
        // @ts-ignore — opacity on material
        haloRef.current.material.opacity = 0.3 + Math.sin(t * 2.5) * 0.1
      } else {
        haloRef.current.scale.setScalar(0)
        // @ts-ignore
        haloRef.current.material.opacity = 0
      }
    }
  })

  return (
    <group position={position}>
      {/* Halo sélection */}
      <mesh ref={haloRef} scale={0}>
        <sphereGeometry args={[0.18, 12, 12]} />
        <meshStandardMaterial
          color={color}
          emissive={emissive}
          emissiveIntensity={0.8}
          transparent
          opacity={0}
          depthWrite={false}
        />
      </mesh>

      {/* Sphère principale */}
      <mesh
        ref={meshRef}
        onClick={(e) => { e.stopPropagation(); onClick(sensor.id) }}
        onPointerOver={(e) => {
          e.stopPropagation()
          setHovered(true)
          document.body.style.cursor = 'pointer'
        }}
        onPointerOut={() => {
          setHovered(false)
          document.body.style.cursor = 'default'
        }}
      >
        <sphereGeometry args={[0.12, 16, 16]} />
        <meshStandardMaterial
          color={color}
          emissive={emissive}
          emissiveIntensity={selected ? 1.2 : 0.5}
          roughness={0.3}
          metalness={0.2}
        />
      </mesh>

      {/* Tooltip HTML au hover */}
      {hovered && (
        <Html
          center
          distanceFactor={8}
          style={{ pointerEvents: 'none' }}
        >
          <div
            style={{
              background: '#172030',
              border: '1px solid #1E2D3D',
              borderRadius: 6,
              padding: '4px 8px',
              whiteSpace: 'nowrap',
              color: '#E2EAF4',
              fontSize: 11,
              fontFamily: 'Inter, sans-serif',
              boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
              transform: 'translateY(-24px)',
            }}
          >
            <div style={{ fontWeight: 500 }}>{sensor.label}</div>
            <div style={{ color: '#8A9BB0', fontFamily: 'JetBrains Mono, monospace', fontSize: 10 }}>
              {sensor.lastValue} {sensor.unit}
            </div>
          </div>
        </Html>
      )}
    </group>
  )
}
