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

/**
 * 音乐嵌入（迁移自 public/js/music-embed.js）：
 * 读取 settings 的 music_embed_enabled / music_embed_code / music_embed_position /
 * music_embed_autohide / music_embed_idle_timeout，支持自动隐藏与悬停展开。
 * 全局组件，挂在 Layout 内。
 */
export default function MusicEmbed({ settings }) {
  const [collapsed, setCollapsed] = useState(false);
  const timerRef = useRef(null);

  const enabled = settings.music_embed_enabled === '1';
  const code = settings.music_embed_code || '';
  const position = settings.music_embed_position || 'right';
  const autoHide = settings.music_embed_autohide === '1';
  const idleTimeout = (parseInt(settings.music_embed_idle_timeout, 10) || 10) * 1000;

  const clearTimer = () => {
    if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
  };

  const expand = () => {
    clearTimer();
    setCollapsed(false);
    if (autoHide) timerRef.current = setTimeout(() => setCollapsed(true), idleTimeout);
  };

  const startLeaveTimer = () => {
    if (!autoHide) return;
    clearTimer();
    timerRef.current = setTimeout(() => setCollapsed(true), idleTimeout);
  };

  useEffect(() => {
    if (!enabled || !code) return;
    setCollapsed(false);
    if (autoHide) timerRef.current = setTimeout(() => setCollapsed(true), idleTimeout);
    return clearTimer;
  }, [enabled, code, autoHide, idleTimeout]);

  if (!enabled || !code) return null;

  return (
    <div
      className={`music-embed ${position} ${collapsed ? 'collapsed' : 'expanded'}`}
      onMouseEnter={expand}
      onMouseLeave={startLeaveTimer}
    >
      {/* 保持挂载以保证折叠后音乐继续播放（display 由 .music-embed.collapsed 规则控制） */}
      <div className="music-embed-player" dangerouslySetInnerHTML={{ __html: code }} />
      <button type="button" className="music-embed-icon" onClick={expand} title="展开播放器" aria-label="展开播放器">
        <span className="material-icons">music_note</span>
      </button>
    </div>
  );
}
