import { useEffect, useRef, useState } from 'react';

// Live call timer. Starts ticking the moment `active` first turns true and
// returns elapsed milliseconds, or null while inactive. The start instant is
// latched in a ref so re-renders while `active` stays true don't restart the
// clock; it DOES reset to null when `active` goes false. Keeping `active`
// stable across a transient connection blip (so the timer doesn't reset
// mid-call) is the caller's job — see CallStatus's `everConnected` latch.
export const useCallDuration = (active: boolean): number | null => {
  const [elapsed, setElapsed] = useState<number | null>(null);
  const startRef = useRef<number | null>(null);

  useEffect(() => {
    if (!active) {
      startRef.current = null;
      setElapsed(null);
      return undefined;
    }
    if (startRef.current === null) {
      startRef.current = Date.now();
    }
    const tick = () => {
      if (startRef.current !== null) {
        setElapsed(Date.now() - startRef.current);
      }
    };
    tick();
    const id = window.setInterval(tick, 1000);
    return () => window.clearInterval(id);
  }, [active]);

  return elapsed;
};

// Compact monospace-friendly call timer: `m:ss` under an hour, `h:mm:ss` over.
// Messenger convention (Telegram/WhatsApp) — not the verbose "N min N sec"
// used for the settled call-log bubble.
export const formatCallTimer = (ms: number): string => {
  const total = Math.max(0, Math.floor(ms / 1000));
  const hours = Math.floor(total / 3600);
  const minutes = Math.floor((total % 3600) / 60);
  const seconds = total % 60;
  const ss = seconds.toString().padStart(2, '0');
  if (hours > 0) {
    const mm = minutes.toString().padStart(2, '0');
    return `${hours}:${mm}:${ss}`;
  }
  return `${minutes}:${ss}`;
};
