import { useEffect, useState } from 'react'
import { isSoundEnabled, onSoundEnabledChange, playPop, setSoundEnabled } from '../../audio/sounds'

// A tiny mute toggle for Petal's cute sounds, tucked at the right of the status
// bar. Bilingual tooltip (she reads Mandarin first), and a soft confirming pop
// when sounds are turned back on so the choice is audible.
export function SoundToggle() {
  const [on, setOn] = useState(isSoundEnabled)

  // Stay in sync if the setting is flipped elsewhere.
  useEffect(() => onSoundEnabledChange(setOn), [])

  const toggle = () => {
    const next = !on
    setSoundEnabled(next)
    setOn(next)
    if (next) playPop() // a little hello when re-enabled
  }

  return (
    <button
      type="button"
      onClick={toggle}
      aria-pressed={on}
      title={on ? '声音开 · Sounds on' : '声音关 · Sounds off'}
      aria-label={on ? 'Mute Petal sounds' : 'Unmute Petal sounds'}
      className="flex items-center justify-center rounded-full px-2 py-1 text-xl leading-none transition-colors"
      style={{ color: on ? 'var(--color-accent)' : 'var(--color-muted)', lineHeight: 1 }}
      onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
      onMouseLeave={(e) =>
        (e.currentTarget.style.color = on ? 'var(--color-accent)' : 'var(--color-muted)')
      }
    >
      <span aria-hidden>{on ? '🔔' : '🔕'}</span>
    </button>
  )
}
