import { useEffect, useRef, useState } from "react";
import { Volume2, VolumeX } from "lucide-react";
import { Button } from "@/components/ui/button";
import { createCrowdBed } from "@/lib/stadium-acoustics";
import { haptic } from "@/lib/haptics";
import type { ArenaId } from "@/lib/stadium-scoring";

export function SeatAmbience({
  arena,
  watching,
  playCount,
}: {
  arena: ArenaId;
  watching: number;
  playCount: number;
}) {
  const bed = useRef<ReturnType<typeof createCrowdBed> | null>(null);
  const [muted, setMuted] = useState(false);
  const lastPlays = useRef(playCount);

  useEffect(() => {
    const next = createCrowdBed(arena);
    bed.current = next;
    next.start();
    haptic("tap");
    return () => {
      next.stop();
      bed.current = null;
    };
  }, [arena]);

  useEffect(() => {
    if (playCount > lastPlays.current) {
      bed.current?.cheer(0.55 + Math.min(0.4, watching / 40));
      haptic("cheer");
    }
    lastPlays.current = playCount;
  }, [playCount, watching]);

  function toggle() {
    const next = !muted;
    setMuted(next);
    bed.current?.setMuted(next);
    if (!next) haptic("tap");
  }

  return (
    <Button
      size="sm"
      variant="outline"
      className="border-sidebar-border bg-navy/80 text-sidebar-foreground"
      onClick={toggle}
    >
      {muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}
      {muted ? "Crowd off" : "Crowd on"}
    </Button>
  );
}
