import { useCallback } from 'react';
import { useSearchParams } from 'react-router';
import { Music } from 'lucide-react';
import { TerminalView } from 'officerdev';
import { AudioStreamPlayer } from './AudioStreamPlayer';

export const CliampPanelHeader = () => {
  const [searchParams] = useSearchParams();
  const playPath = searchParams.get('play') ?? '';
  const fileName = playPath.split('/').pop() ?? 'cliamp';

  return (
    <>
      <Music className="h-4 w-4 shrink-0 opacity-60" />
      <span className="text-xs font-medium truncate flex-1">{fileName}</span>
      <AudioStreamPlayer wsUrl="/api/cliamp/audio/ws" />
    </>
  );
};

export const CliampPanelBody = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const playPath = searchParams.get('play') ?? '';

  const wsPath = `/api/cliamp/ws?files=${encodeURIComponent(playPath)}`;

  const handleExit = useCallback(() => {
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      next.delete('play');
      return next;
    });
  }, [setSearchParams]);

  return <TerminalView className="h-full w-full" wsPath={wsPath} onExit={handleExit} autoFocus />;
};
