"use client";

import { useEffect, useRef, useState, type MouseEvent } from "react";
import { Icon } from "@/components/ui/Icon";

function fmt(sec: number): string {
  if (!isFinite(sec) || sec < 0) return "0:00";
  const m = Math.floor(sec / 60);
  const s = Math.floor(sec % 60);
  return `${m}:${String(s).padStart(2, "0")}`;
}

// Statische Wellenform-Balken (rein dekorativ, deterministisch).
const BARS = [0.4, 0.7, 0.5, 0.9, 0.6, 1, 0.55, 0.8, 0.45, 0.7, 0.6, 0.95, 0.5, 0.75, 0.4, 0.85, 0.6, 0.5];

/** Eigenes Sprachnachrichten-Modul mit Play/Pause, Wellenform & Seek. */
export function VoicePlayer({
  src,
  durationMs,
  mine = false,
}: {
  src: string;
  durationMs?: number | null;
  mine?: boolean;
}) {
  const ref = useRef<HTMLAudioElement>(null);
  const [playing, setPlaying] = useState(false);
  const [cur, setCur] = useState(0);
  const [dur, setDur] = useState(durationMs ? durationMs / 1000 : 0);

  useEffect(() => {
    const a = ref.current;
    if (!a) return;
    const onTime = () => setCur(a.currentTime);
    const onMeta = () => {
      if (isFinite(a.duration) && a.duration > 0) setDur(a.duration);
    };
    const onEnd = () => {
      setPlaying(false);
      setCur(0);
    };
    a.addEventListener("timeupdate", onTime);
    a.addEventListener("loadedmetadata", onMeta);
    a.addEventListener("ended", onEnd);
    a.addEventListener("pause", () => setPlaying(false));
    a.addEventListener("play", () => setPlaying(true));
    return () => {
      a.removeEventListener("timeupdate", onTime);
      a.removeEventListener("loadedmetadata", onMeta);
      a.removeEventListener("ended", onEnd);
    };
  }, []);

  const toggle = () => {
    const a = ref.current;
    if (!a) return;
    if (a.paused) {
      const p = a.play();
      if (p && typeof p.catch === "function") p.catch(() => setPlaying(false));
    } else {
      a.pause();
    }
  };

  const seek = (e: MouseEvent<HTMLDivElement>) => {
    const a = ref.current;
    if (!a || !dur) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
    a.currentTime = ratio * dur;
    setCur(a.currentTime);
  };

  const pct = dur ? Math.min(100, (cur / dur) * 100) : 0;
  const activeBars = Math.round((pct / 100) * BARS.length);

  return (
    <div className={`voice-player ${mine ? "is-me" : ""}`}>
      <audio ref={ref} src={src} preload="auto" />
      <button type="button" className="voice-play" onClick={toggle} aria-label={playing ? "Pause" : "Abspielen"}>
        <Icon name={playing ? "pause" : "play"} size={15} />
      </button>
      <div className="voice-wave" onClick={seek} role="slider" aria-label="Position" aria-valuenow={Math.round(pct)}>
        {BARS.map((h, i) => (
          <span key={i} className="voice-bar" data-on={i < activeBars} style={{ height: `${Math.round(h * 100)}%` }} />
        ))}
      </div>
      <span className="voice-player-time">{fmt(cur > 0 ? cur : dur)}</span>
    </div>
  );
}
