'use client';

import { Repeat } from 'lucide-react';
import { useEffect, useState } from 'react';
import { usePlayerAudio, usePlayerControls } from '../../context/selectors';
import { IconButton } from './IconButton';

export function LoopButton() {
  const audio = usePlayerAudio();
  const { toggleLoop } = usePlayerControls();
  const [loop, setLoop] = useState(audio.loop);

  useEffect(() => {
    // <audio> doesn't fire an event for loop changes, but our toggleLoop sets
    // the property directly — so we sync via a small mutation observer pattern:
    // poll on click only by reading audio.loop after toggleLoop runs.
    setLoop(audio.loop);
  }, [audio]);

  return (
    <IconButton
      label={loop ? 'Disable loop' : 'Enable loop'}
      shortcut="L"
      active={loop}
      onClick={() => {
        toggleLoop();
        setLoop(audio.loop);
      }}
    >
      <Repeat size={16} strokeWidth={1.75} />
    </IconButton>
  );
}
