import { useEffect, useRef } from "preact/hooks";
import type { AgentVisualizerHandle } from "../AgentVisualizer";
import type { AgentState } from "../types";

interface Props {
  state: AgentState;
  connected: boolean;
  connecting: boolean;
  audioLevel: number;
  viewActive: boolean;
  onPointerDown(): void;
  onPointerUp(): void;
}

export function AgentIndicator({
  state,
  connected,
  connecting,
  audioLevel,
  viewActive,
  onPointerDown,
  onPointerUp,
}: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const vizRef = useRef<AgentVisualizerHandle | null>(null);
  const latestStateRef = useRef({ state, connected, connecting, audioLevel });

  latestStateRef.current = { state, connected, connecting, audioLevel };

  useEffect(() => {
    let cancelled = false;
    let localViz: AgentVisualizerHandle | null = null;

    const loadVisualizer = async () => {
      if (!containerRef.current) return;
      const { createAgentVisualizer } = await import("../AgentVisualizer");
      if (cancelled || !containerRef.current) return;

      localViz = createAgentVisualizer(containerRef.current);
      vizRef.current = localViz;

      const latest = latestStateRef.current;
      localViz.setState(latest.state);
      localViz.setConnected(latest.connected);
      localViz.setConnecting(latest.connecting);
      localViz.setAudioLevel(latest.audioLevel);
    };

    loadVisualizer().catch(() => {});

    return () => {
      cancelled = true;
      localViz?.destroy();
      if (vizRef.current === localViz) vizRef.current = null;
    };
  }, []);

  useEffect(() => {
    vizRef.current?.setState(state);
  }, [state]);

  useEffect(() => {
    vizRef.current?.setConnected(connected);
  }, [connected]);

  useEffect(() => {
    vizRef.current?.setConnecting(connecting);
  }, [connecting]);

  useEffect(() => {
    vizRef.current?.setAudioLevel(audioLevel);
  }, [audioLevel]);

  return (
    <div
      id="agentIndicator"
      class={`agentIndicator${viewActive ? " visible" : ""} ${state}`}
      data-ptt="1"
    >
      <div
        id="agentViz"
        class="agentViz"
        data-ptt="1"
        ref={containerRef}
        onPointerDown={onPointerDown}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
      />
    </div>
  );
}
