"""GUI interface for music player application.

This module provides the complete graphical user interface for the music player,
built with PySide2 and featuring modern Material Design aesthetics.
"""

from __future__ import annotations

import logging
import os
import sys
from enum import Enum
from pathlib import Path
from typing import ClassVar, Dict

import PySide2
from PySide2.QtCore import Qt, QTimer, Signal
from PySide2.QtWidgets import (
    QAction,
    QApplication,
    QFileDialog,
    QHBoxLayout,
    QLabel,
    QListWidget,
    QMainWindow,
    QMessageBox,
    QPushButton,
    QSlider,
    QStatusBar,
    QVBoxLayout,
    QWidget,
)


# 自定义进度条类,确保拖动功能正常
class DraggableProgressSlider(QSlider):
    """Custom slider with guaranteed draggable functionality."""

    def __init__(self, orientation, parent=None) -> None:
        super().__init__(orientation, parent)
        self.setMouseTracking(True)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setAttribute(Qt.WA_AcceptTouchEvents, True)

    def mousePressEvent(self, event) -> None:
        """Override mouse press event."""
        logger.debug(f"Mouse press event: {event.pos()}")
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event) -> None:
        """Override mouse move event."""
        logger.debug(f"Mouse move event: {event.pos()}")
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event) -> None:
        """Override mouse release event."""
        logger.debug(f"Mouse release event: {event.pos()}")
        super().mouseReleaseEvent(event)


# Import Vista styles
try:
    from .vista_styles import VistaStyleManager
except ImportError:
    # Fallback if vista_styles module doesn't exist
    VistaStyleManager = None

try:
    from .musicplayer import MusicPlayerCore
except ImportError:
    # Fallback for direct script execution
    import sys
    from pathlib import Path

    sys.path.insert(0, str(Path(__file__).parent.parent))
    from pytola.multimedia.musicplayer.musicplayer import MusicPlayerCore


class PlaybackState:
    """Enum class for playback states."""

    STOPPED = "stopped"
    PLAYING = "playing"
    PAUSED = "paused"


logger = logging.getLogger(__name__)


# Performance monitoring and memory management
_performance_stats = {
    "ui_updates": 0,
    "last_update_time": 0.0,
    "avg_update_interval": 0.0,
    "cpu_usage": 0.0,
    "memory_usage": 0.0,
    "garbage_collections": 0,
}

# Memory optimization settings
_MEMORY_CONFIG = {
    "max_playlist_cache_size": 100,  # Maximum playlist cache size
    "cleanup_interval": 30,  # Cleanup interval (seconds)
    "min_free_memory_mb": 100,  # Minimum free memory (MB)
    "auto_gc_threshold": 50,  # Automatic GC threshold
}

# UI Constants for compact design - Inspired by checksum module
_UI_CONSTANTS = {
    # Dimensions
    "BUTTON_HEIGHT": 22,
    "INPUT_HEIGHT": 22,
    "COMPACT_SPACING": 4,
    "TIGHT_SPACING": 2,
    "MIN_MARGIN": 2,
    "SMALL_MARGIN": 8,
    "MEDIUM_MARGIN": 12,
    "LARGE_MARGIN": 16,
    # Widths
    "BUTTON_WIDTH_LARGE": 120,
    "BUTTON_WIDTH_MEDIUM": 100,
    "BUTTON_WIDTH_SMALL": 80,
    # UI Constants for hierarchical icon sizing
    "ICON_SIZE_PRIMARY": 64,  # Primary functionality: play/pause
    "ICON_SIZE_SECONDARY": 48,  # Secondary functionality: stop, playback mode
    "ICON_SIZE_TERTIARY": 40,  # Tertiary functionality: previous/next
    "ICON_SIZE_QUATERNARY": 32,  # Quaternary functionality: other controls
    "ICON_SIZE_MINIMAL": 24,  # Minimal functionality: browse, clear
    # Fonts
    "FONT_SIZE_LARGE": 16,
    "FONT_SIZE_MEDIUM": 15,
    "FONT_SIZE_SMALL": 12,
    "FONT_FAMILY": "'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif",
    "MONO_FONT": "'Consolas', 'Microsoft YaHei UI', monospace",
    # Colors (aligned with checksum style)
    "PRIMARY_BLUE": "#3b82f6",
    "PRIMARY_DARK": "#1d4ed8",
    "BORDER_COLOR": "#cbd5e1",
    "BACKGROUND_LIGHT": "#ffffff",
    "BACKGROUND_CARD": "#f8fafc",
    "TEXT_PRIMARY": "#0f172a",
    "TEXT_SECONDARY": "#64748b",
}


class LayoutFactory:
    """Factory class for creating compact UI layouts with consistent spacing and margins."""

    @staticmethod
    def create_compact_layout(
        spacing: int = _UI_CONSTANTS["COMPACT_SPACING"],
        margins: tuple = (_UI_CONSTANTS["MIN_MARGIN"],) * 4,
    ) -> QHBoxLayout:
        """Create horizontally compact layout."""
        layout = QHBoxLayout()
        layout.setSpacing(spacing)
        layout.setContentsMargins(*margins)
        return layout

    @staticmethod
    def create_vertical_compact_layout(
        spacing: int = _UI_CONSTANTS["COMPACT_SPACING"],
        margins: tuple = (_UI_CONSTANTS["MIN_MARGIN"],) * 4,
    ) -> QVBoxLayout:
        """Create vertically compact layout."""
        layout = QVBoxLayout()
        layout.setSpacing(spacing)
        layout.setContentsMargins(*margins)
        return layout

    @staticmethod
    def configure_compact_widget(
        widget: QWidget,
        spacing: int = _UI_CONSTANTS["TIGHT_SPACING"],
        margins: tuple = (
            0,
            _UI_CONSTANTS["MIN_MARGIN"],
            0,
            _UI_CONSTANTS["MIN_MARGIN"],
        ),
    ) -> None:
        """Configure widget with compact layout settings."""
        if hasattr(widget, "layout") and widget.layout():
            layout = widget.layout()
            layout.setSpacing(spacing)
            layout.setContentsMargins(*margins)


logger = logging.getLogger(__name__)


class StyleManager:
    """Manager class for handling application styling and themes."""

    # Vista Glass Style Color Schemes
    VISTA_LIGHT: ClassVar[Dict[str, str]] = {
        "primary": "#3b82f6",  # 主要蓝色调
        "secondary": "#2563eb",  # 次要蓝色调
        "glass_primary": "rgba(59, 130, 246, 0.7)",  # 半透明主要蓝
        "glass_secondary": "rgba(37, 99, 235, 0.7)",  # 半透明次要蓝
        "glass_accent": "rgba(245, 158, 11, 0.7)",  # 半透明强调色
        "background": "rgba(255, 255, 255, 0.85)",  # 半透明白色背景
        "surface": "rgba(248, 250, 252, 0.9)",  # 半透明表面
        "text": "#0f172a",
        "text_secondary": "#64748b",
        "accent": "#f59e0b",
        "success": "#10b981",
        "warning": "#f59e0b",
        "error": "#ef4444",
        "border": "rgba(203, 213, 225, 0.6)",  # 半透明边框
        "hover": "rgba(241, 245, 249, 0.7)",  # 半透明悬停
        "glass_effect": "rgba(255, 255, 255, 0.3)",  # 玻璃反射效果
    }

    VISTA_DARK: ClassVar[Dict[str, str]] = {
        "primary": "#60a5fa",
        "secondary": "#3b82f6",
        "glass_primary": "rgba(96, 165, 250, 0.7)",
        "glass_secondary": "rgba(59, 130, 246, 0.7)",
        "glass_accent": "rgba(251, 191, 36, 0.7)",
        "background": "rgba(15, 23, 42, 0.85)",
        "surface": "rgba(30, 41, 59, 0.9)",
        "text": "#f1f5f9",
        "text_secondary": "#94a3b8",
        "accent": "#fbbf24",
        "success": "#34d399",
        "warning": "#fbbf24",
        "error": "#f87171",
        "border": "rgba(51, 65, 85, 0.6)",
        "hover": "rgba(51, 65, 85, 0.7)",
        "glass_effect": "rgba(255, 255, 255, 0.1)",
    }

    # Traditional Light/Dark Themes
    LIGHT_THEME = VISTA_LIGHT
    DARK_THEME = VISTA_DARK

    @classmethod
    def get_light_theme(cls) -> str:
        """Get complete light theme stylesheet."""
        colors = cls.LIGHT_THEME
        return cls._generate_stylesheet(colors)

    @classmethod
    def get_dark_theme(cls) -> str:
        """Get complete dark theme stylesheet."""
        colors = cls.DARK_THEME
        return cls._generate_stylesheet(colors)

    @classmethod
    def get_vista_light_theme(cls) -> str:
        """Get Vista glass light theme stylesheet."""
        colors = cls.VISTA_LIGHT
        return cls._generate_vista_stylesheet(colors)

    @classmethod
    def get_vista_dark_theme(cls) -> str:
        """Get Vista glass dark theme stylesheet."""
        colors = cls.VISTA_DARK
        return cls._generate_vista_stylesheet(colors)

    @classmethod
    def _generate_stylesheet(cls, colors: dict[str, str]) -> str:
        """Generate traditional stylesheet.

        Args:
            colors: Dictionary of color definitions

        Returns
        -------
            Complete QSS stylesheet string
        """
        return f"""
/* Traditional Style */
QMainWindow {{
    background-color: {colors["background"]};
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
    font-size: 15px;
}}

QWidget {{
    color: {colors["text"]};
    background-color: {colors["background"]};
}}

QPushButton {{
    background-color: {colors["primary"]};
    color: white;
    border: none;
    border-radius: 6px;
    padding: 8px 16px;
    font-weight: 500;
}}

QPushButton:hover {{
    background-color: {colors["secondary"]};
}}

QPushButton:pressed {{
    background-color: {colors["accent"]};
}}

QSlider::groove:horizontal {{
    border: 1px solid {colors["border"]};
    height: 6px;
    background: {colors["surface"]};
    border-radius: 3px;
}}

QSlider::handle:horizontal {{
    background: {colors["primary"]};
    border: 2px solid {colors["background"]};
    width: 16px;
    margin: -6px 0;
    border-radius: 8px;
}}

QSlider::handle:horizontal:hover {{
    background: {colors["secondary"]};
    border-color: {colors["primary"]};
}}

QSlider::sub-page:horizontal {{
    background: {colors["primary"]};
    border-radius: 3px;
}}

QLabel {{
    color: {colors["text"]};
}}

QLabel#currentTimeLabel {{
    color: {colors["primary"]};
    font-weight: 500;
}}

QListWidget {{
    background-color: {colors["surface"]};
    border: 1px solid {colors["border"]};
    border-radius: 4px;
    color: {colors["text"]};
}}

QListWidget::item:selected {{
    background-color: {colors["primary"]};
    color: white;
}}

QListWidget::item:hover {{
    background-color: {colors["hover"]};
}}
"""

    @classmethod
    def _generate_vista_stylesheet(cls, colors: dict[str, str]) -> str:
        """Generate Vista glass style stylesheet with transparency effects.

        Args:
            colors: Dictionary of Vista glass color definitions

        Returns
        -------
            Complete QSS stylesheet string with glass effects
        """
        return f"""
/* Vista Glass Style Main Window */
QMainWindow {{
    background-color: {colors["background"]};
    font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
    font-size: 15px;
    /* Vista玻璃效果 */
    border: 1px solid {colors["border"]};
}}

QWidget {{
    font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
    font-size: 15px;
    background-color: transparent;
}}

/* Vista玻璃中央部件 */
QWidget#centralWidget {{
    background-color: {colors["background"]};
    border-radius: 12px;
    /* 玻璃反射效果 */
    border: 1px solid {colors["border"]};
}}

/* Vista标题栏 - 玻璃效果 */
QLabel#titleLabel {{
    font-size: 18px;
    font-weight: 600;
    color: {colors["text"]};
    padding: 12px 16px;
    border-bottom: 2px solid {colors["primary"]};
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    background-color: {colors["surface"]};
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
}}

/* Vista玻璃按钮基础样式 */
QPushButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["glass_primary"]},
                              stop:0.5 {colors["glass_secondary"]},
                              stop:1 rgba(29, 78, 216, 0.7));
    color: white;
    border: 1px solid {colors["primary"]};
    border-radius: 8px;
    padding: 8px 16px;
    font-size: 14px;
    font-weight: 500;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
    min-height: 32px;
    min-width: 80px;
    /* Vista玻璃效果 */
    background-clip: padding-box;
}}

QPushButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["glass_secondary"]},
                              stop:0.5 rgba(29, 78, 216, 0.8),
                              stop:1 rgba(30, 64, 175, 0.8));
    border: 1px solid {colors["secondary"]};
}}

QPushButton:pressed {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 rgba(29, 78, 216, 0.9),
                              stop:0.5 rgba(30, 64, 175, 0.9),
                              stop:1 rgba(23, 37, 84, 0.9));
}}

QPushButton:disabled {{
    background: rgba(148, 163, 184, 0.5);
    color: rgba(203, 213, 225, 0.7);
    border: 1px solid rgba(203, 213, 225, 0.3);
}}

/* Vista播放控制按钮 - 突出主要蓝色调 */
QPushButton#playButton {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.8,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_primary"]},
                               stop:0.7 {colors["glass_secondary"]},
                               stop:1 rgba(29, 78, 216, 0.8));
    border: 2px solid {colors["primary"]};
    border-radius: 36px;
    min-width: 72px;
    min-height: 72px;
    font-size: 40px;
    font-weight: 600;
    color: white;
    padding: 16px;
    /* Vista玻璃高光效果 - 使用 Qt 支持的属性 */
}}

QPushButton#playButton:hover {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.8,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_secondary"]},
                               stop:0.7 rgba(29, 78, 216, 0.9),
                               stop:1 rgba(30, 64, 175, 0.9));
    border-color: {colors["secondary"]};
}}

QPushButton#pauseButton {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.8,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_primary"]},
                               stop:0.7 {colors["glass_secondary"]},
                               stop:1 rgba(29, 78, 216, 0.8));
    border: 2px solid {colors["primary"]};
    border-radius: 36px;
    min-width: 72px;
    min-height: 72px;
    font-size: 40px;
    font-weight: 600;
    color: white;
    padding: 16px;

}}

QPushButton#pauseButton:hover {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.8,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_secondary"]},
                               stop:0.7 rgba(29, 78, 216, 0.9),
                               stop:1 rgba(30, 64, 175, 0.9));
    border-color: {colors["secondary"]};
}}

/* Vista次要控制按钮 - 使用次要色调 */
QPushButton#stopButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["glass_accent"]},
                              stop:1 rgba(192, 132, 9, 0.7));
    border: 2px solid {colors["accent"]};
    border-radius: 28px;
    min-width: 56px;
    min-height: 56px;
    font-size: 28px;
    font-weight: 600;
    color: white;
    padding: 12px;
}}

QPushButton#stopButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 rgba(245, 158, 11, 0.9),
                              stop:1 rgba(192, 132, 9, 0.9));
    border-color: #d97706;
}}

QPushButton#modeButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["glass_accent"]},
                              stop:1 rgba(192, 132, 9, 0.7));
    border: 2px solid {colors["accent"]};
    border-radius: 28px;
    min-width: 56px;
    min-height: 56px;
    font-size: 28px;
    font-weight: 600;
    color: white;
    padding: 12px;
}}

QPushButton#modeButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 rgba(245, 158, 11, 0.9),
                              stop:1 rgba(192, 132, 9, 0.9));
    border-color: #d97706;
}}

/* Vista导航按钮 - 辅助色调 */
QPushButton#prevButton, QPushButton#nextButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 rgba(100, 116, 139, 0.7),
                              stop:1 rgba(71, 85, 105, 0.7));
    border: 2px solid rgba(100, 116, 139, 0.8);
    border-radius: 24px;
    min-width: 48px;
    min-height: 48px;
    font-size: 20px;
    color: white;
    padding: 8px;

}}

QPushButton#prevButton:hover, QPushButton#nextButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 rgba(100, 116, 139, 0.9),
                              stop:1 rgba(71, 85, 105, 0.9));
    border-color: rgba(71, 85, 105, 0.9);

}}

/* Vista进度控制区域 */
QWidget#progressSection {{
    background-color: {colors["surface"]};
    padding: 12px 16px;
    border-radius: 8px;
    margin: 8px;
}}

QWidget#mainControls {{
    background-color: {colors["surface"]};
    border-radius: 16px;
    padding: 16px;
    margin: 8px;
    border: 1px solid {colors["border"]};
}}

QWidget#bottomSection {{
    background-color: {colors["surface"]};
    padding: 12px 16px;
    border-radius: 8px;
    margin: 8px;
    border: 1px solid {colors["border"]};
}}

/* Vista时间标签 */
QLabel#currentTimeLabel, QLabel#totalTimeLabel {{
    font-size: 14px;
    font-family: 'Consolas', monospace;
    color: {colors["text_secondary"]};
    padding: 4px 8px;
    background-color: {colors["glass_effect"]};
    border-radius: 4px;
}}

QLabel#currentTimeLabel {{
    color: {colors["primary"]};
    font-weight: 600;
    border: 1px solid {colors["primary"]};
}}

/* Vista进度滑块 */
QSlider#progressSlider::groove:horizontal {{
    border: 1px solid {colors["border"]};
    height: 8px;
    background: {colors["surface"]};
    border-radius: 4px;
}}

QSlider#progressSlider::handle:horizontal {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.6,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_primary"]},
                               stop:1 {colors["primary"]});
    border: 2px solid {colors["background"]};
    width: 20px;
    margin: -6px 0;
    border-radius: 10px;

}}

QSlider#progressSlider::handle:horizontal:hover {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.6,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_secondary"]},
                               stop:1 {colors["secondary"]});
    border-color: {colors["primary"]};
}}

QSlider#progressSlider::sub-page:horizontal {{
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 {colors["primary"]},
                              stop:1 {colors["secondary"]});
    border-radius: 4px;
}}

/* Vista音量控制 */
QSlider#volumeSlider::groove:horizontal {{
    border: 1px solid {colors["border"]};
    height: 6px;
    background: {colors["surface"]};
    border-radius: 3px;
}}

QSlider#volumeSlider::handle:horizontal {{
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.6,
                               fx:0.5, fy:0.3,
                               stop:0 {colors["glass_accent"]},
                               stop:1 {colors["accent"]});
    border: 1px solid {colors["background"]};
    width: 16px;
    margin: -5px 0;
    border-radius: 8px;
}}

QSlider#volumeSlider::sub-page:horizontal {{
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 {colors["accent"]},
                              stop:1 #d97706);
    border-radius: 3px;
}}

QLabel#volumeLabel {{
    color: {colors["text_secondary"]};
    font-size: 13px;
    padding: 0 6px;
    background-color: {colors["glass_effect"]};
    border-radius: 3px;
}}

/* Vista控制面板 */
QWidget#controlPanel {{
    background-color: {colors["surface"]};
    border: 1px solid {colors["border"]};
    border-radius: 12px;
    padding: 12px;
}}

/* Vista进度条 */
QProgressBar {{
    border: 1px solid {colors["border"]};
    border-radius: 6px;
    text-align: center;
    background-color: {colors["surface"]};
    color: {colors["text"]};
}}

QProgressBar::chunk {{
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 {colors["primary"]},
                              stop:1 {colors["secondary"]});
    border-radius: 5px;
}}

/* Vista列表视图 */
QListWidget {{
    background-color: {colors["surface"]};
    border: 1px solid {colors["border"]};
    border-radius: 8px;
    alternate-background-color: {colors["hover"]};
}}

QListWidget::item:selected {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]},
                              stop:1 {colors["secondary"]});
    color: white;
}}

QListWidget::item:hover {{
    background-color: {colors["hover"]};
}}
/* Professional Playback Controls with Unified Styling */
/* Primary Level - Playback Control (Most Prominent) */
QPushButton#playButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]}, stop:1 {colors["secondary"]});
    border: 2px solid {colors["primary"]};
    border-radius: 32px;
    min-width: 64px;
    min-height: 64px;
    font-size: 36px;
    font-weight: 600;
    color: white;
    padding: 12px;
}}

QPushButton#playButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["secondary"]}, stop:1 #1d4ed8);
    border-color: {colors["secondary"]};
}}

QPushButton#pauseButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]}, stop:1 {colors["secondary"]});
    border: 2px solid {colors["primary"]};
    border-radius: 32px;
    min-width: 64px;
    min-height: 64px;
    font-size: 36px;
    font-weight: 600;
    color: white;
    padding: 12px;
}}

QPushButton#pauseButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["secondary"]}, stop:1 #1d4ed8);
    border-color: {colors["secondary"]};
}}

/* Secondary Level - Stop and Mode Controls */
QPushButton#stopButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]}, stop:1 {colors["secondary"]});
    border: 2px solid {colors["primary"]};
    border-radius: 24px;
    min-width: 48px;
    min-height: 48px;
    font-size: 24px;
    font-weight: 600;
    color: white;
    padding: 8px;
}}

QPushButton#stopButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["secondary"]}, stop:1 #1d4ed8);
    border-color: {colors["secondary"]};
}}

QPushButton#modeButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]}, stop:1 {colors["secondary"]});
    border: 2px solid {colors["primary"]};
    border-radius: 24px;
    min-width: 48px;
    min-height: 48px;
    font-size: 24px;
    font-weight: 600;
    color: white;
    padding: 8px;
}}

QPushButton#modeButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["secondary"]}, stop:1 #1d4ed8);
    border-color: {colors["secondary"]};
}}

/* Tertiary Level - Navigation Controls */
QPushButton#prevButton, QPushButton#nextButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["primary"]}, stop:1 {colors["secondary"]});
    border: 2px solid {colors["primary"]};
    border-radius: 20px;
    min-width: 40px;
    min-height: 40px;
    font-size: 18px;
    color: white;
    padding: 6px;
}}

QPushButton#prevButton:hover, QPushButton#nextButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 {colors["secondary"]}, stop:1 #1d4ed8);
    border-color: {colors["secondary"]};
}}



/* Professional Progress Controls */
QWidget#progressSection {{
    background-color: transparent;
    padding: 8px 0;
}}

QWidget#mainControls {{
    background-color: {colors["surface"]};
    border-radius: 12px;
    padding: 12px;
}}

QWidget#bottomSection {{
    background-color: transparent;
}}

/* Time Labels */
QLabel#currentTimeLabel, QLabel#totalTimeLabel {{
    font-size: 13px;
    font-family: 'Consolas', monospace;
    color: {colors["text_secondary"]};
    padding: 2px 4px;
}}

QLabel#currentTimeLabel {{
    color: {colors["primary"]};
    font-weight: 500;
}}

/* Progress Slider - Enhanced */
QSlider#progressSlider::groove:horizontal {{
    border: 1px solid {colors["border"]};
    height: 6px;
    background: {colors["surface"]};
    border-radius: 3px;
}}

QSlider#progressSlider::handle:horizontal {{
    background: {colors["primary"]};
    border: 2px solid {colors["background"]};
    width: 16px;
    margin: -6px 0;
    border-radius: 8px;
}}

QSlider#progressSlider::handle:horizontal:hover {{
    background: {colors["secondary"]};
    border-color: {colors["primary"]};
}}

QSlider#progressSlider::sub-page:horizontal {{
    background: {colors["primary"]};
    border-radius: 3px;
}}

/* Volume Controls */
QSlider#volumeSlider::groove:horizontal {{
    border: 1px solid {colors["border"]};
    height: 4px;
    background: {colors["surface"]};
    border-radius: 2px;
}}

QSlider#volumeSlider::handle:horizontal {{
    background: {colors["primary"]};
    border: 1px solid {colors["background"]};
    width: 12px;
    margin: -4px 0;
    border-radius: 6px;
}}

QSlider#volumeSlider::sub-page:horizontal {{
    background: {colors["primary"]};
    border-radius: 2px;
}}

QLabel#volumeLabel {{
    color: {colors["text_secondary"]};
    font-size: 12px;
    padding: 0 4px;
}}

/* Control Panel */
QWidget#controlPanel {{
    background-color: {colors["background"]};
    border: 1px solid {colors["border"]};
    border-radius: 8px;
}}

/* Progress Bar */
QProgressBar {{
    border: 1px solid {colors["border"]};
    border-radius: 3px;
    text-align: center;
    color: {colors["text"]};
    background-color: {colors["surface"]};
    height: 16px;
}}

QProgressBar::chunk {{
    background-color: {colors["primary"]};
    border-radius: 2px;
}}

/* Playlist View - Ultra compact items */
QListWidget {{
    background-color: {colors["surface"]};
    alternate-background-color: {colors["background"]};
    border: 1px solid {colors["border"]};
    border-radius: 4px;
    color: {colors["text"]};
    font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
    font-size: 13px;
}}

QListWidget::item {{
    padding: 4px 8px;
    border-bottom: 1px solid {colors["border"]};
}}

QListWidget::item:selected {{
    background-color: {colors["primary"]};
    color: white;
}}

QListWidget::item:hover {{
    background-color: {colors["hover"]};
}}

/* Table Widget */
QTableWidget {{
    background-color: {colors["surface"]};
    alternate-background-color: {colors["background"]};
    border: 1px solid {colors["border"]};
    border-radius: 6px;
    color: {colors["text"]};
    gridline-color: {colors["border"]};
}}

QHeaderView::section {{
    background-color: {colors["primary"]};
    color: white;
    padding: 6px;
    font-weight: 600;
    border: 1px solid {colors["border"]};
}}

/* Input Controls - Ultra compact design */
QLineEdit, QComboBox {{
    background-color: {colors["surface"]};
    border: 1px solid {colors["border"]};
    border-radius: 4px;
    padding: 4px 8px;
    color: {colors["text"]};
    font-size: 13px;
    min-height: 22px;
}}

QLineEdit:focus, QComboBox:focus {{
    border: 1px solid {colors["primary"]};
    outline: none;
}}

QLineEdit:disabled, QComboBox:disabled {{
    background-color: {colors["border"]};
    color: {colors["text_secondary"]};
}}

/* Scroll Bars - Ultra compact */
QScrollBar:vertical {{
    border: none;
    background-color: {colors["surface"]};
    width: 10px;
    border-radius: 5px;
}}

QScrollBar::handle:vertical {{
    background-color: {colors["primary"]};
    border-radius: 5px;
    min-height: 12px;
}}

QScrollBar::handle:vertical:hover {{
    background-color: {colors["secondary"]};
}}

QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
    height: 0px;
}}

/* Status bar - Minimal padding */
QStatusBar {{
    background-color: {colors["surface"]};
    border-top: 1px solid {colors["border"]};
    font-size: 12px;
    color: {colors["text_secondary"]};
    padding: 1px 6px;
}}

/* Menu bar - Compact */
QMenuBar {{
    background-color: {colors["background"]};
    color: {colors["text"]};
    border-bottom: 1px solid {colors["border"]};
    padding: 1px;
    font-size: 13px;
}}

QMenuBar::item {{
    padding: 4px 8px;
    border-radius: 3px;
}}

QMenuBar::item:selected {{
    background-color: {colors["hover"]};
}}

QMenu {{
    background-color: {colors["surface"]};
    color: {colors["text"]};
    border: 1px solid {colors["border"]};
    border-radius: 4px;
    padding: 2px 0px;
}}

QMenu::item {{
    padding: 4px 16px;
    font-size: 13px;
}}

QMenu::item:selected {{
    background-color: {colors["hover"]};
}}

/* Group Boxes */
QGroupBox {{
    border: 1px solid {colors["border"]};
    border-radius: 8px;
    margin-top: 12px;
    font-weight: 500;
    color: {colors["text"]};
}}

QGroupBox::title {{
    subcontrol-origin: margin;
    left: 12px;
    padding: 0 8px;
    background-color: {colors["background"]};
}}

/* Labels */
QLabel {{
    color: {colors["text"]};
    font-family: 'Segoe UI', sans-serif;
    font-size: 13px;
}}

QLabel#statusLabel {{
    font-weight: 500;
    color: {colors["primary"]};
}}

/* Control Groups Styling - Optimized Layout */
QWidget#navigationGroup {{
    background-color: transparent;
    padding-right: 8px;  /* Space before core controls */
}}

QWidget#corePlaybackGroup {{
    background-color: transparent;
    padding: 0 12px;  /* Extra space around core buttons */
}}

QWidget#extraControlsGroup {{
    background-color: transparent;
    padding-left: 8px;  /* Space after core controls */
}}

QWidget#quickVolumeGroup {{
    background-color: transparent;
}}

/* Quick Volume Buttons */
QPushButton#volumeUpButton, QPushButton#volumeDownButton {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #94a3b8, stop:1 #64748b);
    border: 1px solid #94a3b8;
    border-radius: 12px;
    min-width: 32px;
    min-height: 24px;
    font-size: 12px;
    color: white;
    padding: 2px;
}}

QPushButton#volumeUpButton:hover, QPushButton#volumeDownButton:hover {{
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #64748b, stop:1 #475569);
    border-color: #64748b;
}}


/* Tool Tips */
QToolTip {{
    background-color: {colors["surface"]};
    color: {colors["text"]};
    border: 1px solid {colors["primary"]};
    border-radius: 4px;
    padding: 3px;
    font-size: 11px;
}}
"""

    @classmethod
    def get_theme(cls, theme_name: str) -> str:
        """Get stylesheet for specified theme.

        Args:
            theme_name: Theme name ('light', 'dark', 'vista-light', 'vista-dark')

        Returns
        -------
            QSS stylesheet string
        """
        theme_lower = theme_name.lower()
        if theme_lower == "dark":
            return cls.get_dark_theme()
        if theme_lower == "vista-light":
            return cls.get_vista_light_theme()
        if theme_lower == "vista-dark":
            return cls.get_vista_dark_theme()
        return cls.get_light_theme()

    @classmethod
    def save_theme_to_file(cls, theme_name: str, file_path: Path) -> bool:
        """Save theme stylesheet to file.

        Args:
            theme_name: Theme name to save
            file_path: Target file path

        Returns
        -------
            True if saved successfully, False otherwise
        """
        try:
            stylesheet = cls.get_theme(theme_name)
            file_path.parent.mkdir(parents=True, exist_ok=True)

            Path(file_path).write_text(stylesheet, encoding="utf-8")

            logger.info(f"Theme '{theme_name}' saved to {file_path}")
            return True

        except Exception as e:
            logger.exception(f"Failed to save theme to {file_path}: {e}")
            return False


# Configure Qt platform plugins for Windows compatibility
qt_dir = Path(PySide2.__file__).parent
plugin_path = str(qt_dir / "plugins" / "platforms")
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = plugin_path

# Also set QT_DEBUG_PLUGINS for debugging if needed
# os.environ["QT_DEBUG_PLUGINS"] = "1"


# Multi-language support
class Language(Enum):
    """Supported languages."""

    CHINESE = "zh"
    ENGLISH = "en"


class TranslationManager:
    """Manage UI translations for music player."""

    def __init__(self) -> None:
        """Initialize translation manager with default Chinese."""
        self.current_language = Language.CHINESE
        self.translations = self._load_translations()

    def _load_translations(self) -> dict[str, dict[str, str]]:
        """Load translation dictionaries."""
        return {
            Language.CHINESE.value: {
                # Window and titles
                "window_title": "🎵 音乐播放器",
                "app_title": "🎵 MUSIC PLAYER",
                # Menu items
                "menu_file": "文件(&F)",
                "menu_help": "帮助(&H)",
                "action_open_folder": "打开文件夹(&O)...",
                "action_exit": "退出(&X)",
                "action_about": "关于(&A)",
                # Control buttons
                "button_play": "播放",
                "button_pause": "暂停",
                "button_stop": "停止",
                "button_browse": "添加文件夹",
                "button_clear": "清空",
                # Playback modes
                "mode_sequential": "顺序播放",
                "mode_shuffle": "随机播放",
                "mode_single_loop": "单曲循环",
                "mode_infinite_loop": "列表循环",
                # Labels
                "label_volume": "音量:",
                "label_playlist": "播放列表:",
                "label_time_initial": "00:00 / 00:00",
                # Status messages
                "status_ready": "就绪",
                "status_loaded_tracks": "已加载 {} 首歌曲来自 {}",
                "status_no_audio_files": "所选文件夹中未找到音频文件",
                "status_playlist_cleared": "播放列表已清空",
                "status_no_tracks": "播放列表为空",
                "status_playing": "正在播放: {}",
                "status_paused": "播放已暂停",
                "status_resumed": "播放已恢复",
                "status_stopped": "播放已停止",
                "status_load_failed": "无法加载歌曲",
                "status_play_failed": "无法开始播放",
                # Dialog messages
                "dialog_select_folder": "选择音乐文件夹",
                "dialog_about_title": "关于音乐播放器",
                "dialog_about_text": "🎵 音乐播放器 v0.1.0\n\n"
                "基于PySide2的现代化音乐播放器,支持文件夹播放列表。\n\n"
                "功能特性:\n"
                "• 现代化Material Design界面\n"
                "• 基于文件夹的播放列表管理\n"
                "• 支持MP3、WAV、FLAC等多种格式\n"
                "• 持久化配置保存\n"
                "• 明亮/暗黑主题\n\n"
                "使用PySide2、playsound和mutagen构建。",
                # File types
                "file_type_music": "音频文件 (*.mp3 *.wav *.flac *.ogg *.m4a)",
                "file_type_all": "所有文件 (*.*)",
            },
            Language.ENGLISH.value: {
                # Window and titles
                "window_title": "🎵 Music Player",
                "app_title": "🎵 MUSIC PLAYER",
                # Menu items
                "menu_file": "&File",
                "menu_help": "&Help",
                "action_open_folder": "&Open Folder...",
                "action_exit": "E&xit",
                "action_about": "&About",
                # Control buttons - Tooltip texts only
                "button_play": "Play",
                "button_pause": "Pause",
                "button_stop": "Stop",
                "button_browse": "Add Folder",
                "button_clear": "Clear",
                # Playback modes
                "mode_sequential": "Sequential",
                "mode_shuffle": "Shuffle",
                "mode_single_loop": "Single Loop",
                "mode_infinite_loop": "Infinite Loop",
                # Labels
                "label_volume": "Volume:",
                "label_playlist": "Playlist:",
                "label_time_initial": "00:00 / 00:00",
                # Status messages
                "status_ready": "Ready",
                "status_loaded_tracks": "Loaded {} tracks from {}",
                "status_no_audio_files": "No audio files found in selected folder",
                "status_playlist_cleared": "Playlist cleared",
                "status_no_tracks": "No tracks in playlist",
                "status_playing": "Playing: {}",
                "status_paused": "Playback paused",
                "status_resumed": "Playback resumed",
                "status_stopped": "Playback stopped",
                "status_load_failed": "Failed to load track",
                "status_play_failed": "Failed to start playback",
                # Dialog messages
                "dialog_select_folder": "Select Music Folder",
                "dialog_about_title": "About Music Player",
                "dialog_about_text": "🎵 Music Player v0.1.0\n\n"
                "A modern PySide2 music player with folder-based playlist support.\n\n"
                "Features:\n"
                "• Modern Material Design interface\n"
                "• Folder-based playlist management\n"
                "• Support for MP3, WAV, FLAC, and more\n"
                "• Persistent configuration\n"
                "• Light/Dark themes\n\n"
                "Built with PySide2, playsound, and mutagen.",
                # File types
                "file_type_music": "Audio files (*.mp3 *.wav *.flac *.ogg *.m4a)",
                "file_type_all": "All files (*.*)",
            },
        }

    def set_language(self, language: Language) -> None:
        """Set current language."""
        self.current_language = language

    def tr(self, key: str) -> str:
        """Translate key to current language."""
        return self.translations[self.current_language.value].get(key, key)

    def get_available_languages(self) -> list[tuple[str, str]]:
        """Get available languages for UI display."""
        return [
            (Language.CHINESE.value, "中文"),
            (Language.ENGLISH.value, "English"),
        ]


# Global translation manager
_translation_manager = TranslationManager()


class MusicPlayerGUI(QMainWindow):
    """Main GUI window for music player application.

    Provides complete graphical interface for music playback including
    playlist management, playback controls, and modern styling.
    Features persistent configuration and keyboard shortcuts.
    """

    # Custom signals
    track_changed = Signal(int)
    playback_state_changed = Signal(object)  # Using object instead of PlaybackState

    def __init__(self) -> None:
        """Initialize GUI components and setup application state with memory optimization."""
        super().__init__()
        self.music_player = MusicPlayerCore()

        # 内存管理定时器
        self._memory_cleanup_timer = QTimer()
        self._memory_cleanup_timer.timeout.connect(self._perform_memory_cleanup)
        self._memory_cleanup_timer.start(_MEMORY_CONFIG["cleanup_interval"] * 1000)

        # 性能监控定时器
        self._perf_monitor_timer = QTimer()
        self._perf_monitor_timer.timeout.connect(self._monitor_system_performance)
        self._perf_monitor_timer.start(5000)  # 每5秒监控一次

        # UI components
        self.playlist_widget: QListWidget | None = None
        self.progress_slider: QSlider | None = None
        self.volume_slider: QSlider | None = None
        self.time_label: QLabel | None = None
        self.status_label: QLabel | None = None
        self.play_button: QPushButton | None = None
        self.pause_button: QPushButton | None = None
        self.stop_button: QPushButton | None = None
        self.mode_button: QPushButton | None = None  # 播放模式按钮
        self.mode_label: QLabel | None = None  # 播放模式标签

        # Timers
        self.progress_timer: QTimer | None = None

        # 进度滑块拖动状态
        self._is_slider_dragging = False

        self._setup_ui()
        self._load_config()
        self._setup_signals()
        self._setup_timers()
        self._apply_styling()

    def _setup_ui(self) -> None:
        """Set up user interface components."""
        self.setWindowTitle(_translation_manager.tr("window_title"))
        self._restore_window_geometry()

        # Create central widget
        central_widget = QWidget()
        central_widget.setObjectName("centralWidget")
        self.setCentralWidget(central_widget)

        # Main layout - Extreme compact design inspired by checksum
        main_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(_UI_CONSTANTS["SMALL_MARGIN"],) * 4,
        )

        # Create components
        self._create_title_bar(main_layout)
        self._create_control_panel(main_layout)
        self._create_playlist_view(main_layout)
        self._create_status_bar()
        self._create_menu_bar()

        # 设置中央部件布局
        central_widget.setLayout(main_layout)

        # UI初始化完成后启动定时器,使用更低频率以提高性能
        if self.progress_timer:
            self.progress_timer.start(300)  # 从200ms改为300ms,进一步降低CPU使用率

    def _create_title_bar(self, layout: QVBoxLayout) -> None:
        """Create application title bar."""
        title_label = QLabel(_translation_manager.tr("app_title"))
        title_label.setObjectName("titleLabel")
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)

    def _create_control_panel(self, layout: QVBoxLayout) -> None:
        """Create professional playback control panel with improved layout."""
        # Control panel container with professional spacing
        control_group = QWidget()
        control_group.setObjectName("controlPanel")
        control_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(
                _UI_CONSTANTS["SMALL_MARGIN"],
                _UI_CONSTANTS["MIN_MARGIN"],
                _UI_CONSTANTS["SMALL_MARGIN"],
                _UI_CONSTANTS["MIN_MARGIN"],
            ),
        )
        control_group.setLayout(control_layout)

        # === PROFESSIONAL PLAYER LAYOUT ===
        # 1. Progress section (top) - Classic player design
        progress_section = QWidget()
        progress_section.setObjectName("progressSection")
        progress_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, 0, 0, _UI_CONSTANTS["COMPACT_SPACING"]),
        )
        progress_section.setLayout(progress_layout)

        # Time labels row
        time_row = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(0, 0, 0, 0),
        )

        # Current time
        self.current_time_label = QLabel("00:00")
        self.current_time_label.setObjectName("currentTimeLabel")
        self.current_time_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.current_time_label.setMinimumWidth(40)
        time_row.addWidget(self.current_time_label)

        # Progress slider (使用自定义可拖动滑块)
        self.progress_slider = DraggableProgressSlider(Qt.Horizontal)
        self.progress_slider.setMinimum(0)
        self.progress_slider.setMaximum(1000)
        self.progress_slider.setValue(0)
        self.progress_slider.setObjectName("progressSlider")
        self.progress_slider.setStyleSheet("height: 20px; padding: 4px;")
        time_row.addWidget(self.progress_slider, 1)  # Take available space

        # Total time
        self.total_time_label = QLabel("00:00")
        self.total_time_label.setObjectName("totalTimeLabel")
        self.total_time_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.total_time_label.setMinimumWidth(40)
        time_row.addWidget(self.total_time_label)

        progress_layout.addLayout(time_row)
        control_layout.addWidget(progress_section)

        # 2. Main control buttons (center) - Optimized professional arrangement
        main_controls = QWidget()
        main_controls.setObjectName("mainControls")
        main_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(
                0,
                _UI_CONSTANTS["COMPACT_SPACING"],
                0,
                _UI_CONSTANTS["COMPACT_SPACING"],
            ),
        )
        main_controls.setLayout(main_layout)

        # === LEFT GROUP: Navigation Controls (Previous/Next Track) ===
        nav_group = QWidget()
        nav_group.setObjectName("navigationGroup")
        nav_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, 0, 0, 0),
        )
        nav_group.setLayout(nav_layout)

        # Previous track button (Tertiary level)
        self.prev_button = QPushButton("⏮")
        self.prev_button.setObjectName("prevButton")
        self.prev_button.setToolTip("上一曲")
        self.prev_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_TERTIARY"])
        self.prev_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_TERTIARY"])
        self.prev_button.setStyleSheet(
            f"padding: 6px; font-size: 18px; border-radius: {_UI_CONSTANTS['ICON_SIZE_TERTIARY'] // 2}px;",
        )
        nav_layout.addWidget(self.prev_button)

        # Next track button (Tertiary level)
        self.next_button = QPushButton("⏭")
        self.next_button.setObjectName("nextButton")
        self.next_button.setToolTip("下一曲")
        self.next_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_TERTIARY"])
        self.next_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_TERTIARY"])
        self.next_button.setStyleSheet(
            f"padding: 6px; font-size: 18px; border-radius: {_UI_CONSTANTS['ICON_SIZE_TERTIARY'] // 2}px;",
        )
        nav_layout.addWidget(self.next_button)

        main_layout.addWidget(nav_group)

        # === CENTER GROUP: Core Playback Controls (Play/Pause/Stop) ===
        core_group = QWidget()
        core_group.setObjectName("corePlaybackGroup")
        core_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],  # Small spacing between core buttons
            margins=(0, 0, 0, 0),
        )
        core_group.setLayout(core_layout)

        # Stop button (Secondary level - positioned left of play)
        self.stop_button = QPushButton("⏹")
        self.stop_button.setObjectName("stopButton")
        self.stop_button.setToolTip(_translation_manager.tr("button_stop"))
        self.stop_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_SECONDARY"])
        self.stop_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_SECONDARY"])
        self.stop_button.setStyleSheet(
            f"padding: 8px; font-size: 24px; border-radius: {_UI_CONSTANTS['ICON_SIZE_SECONDARY'] // 2}px;",
        )
        core_layout.addWidget(self.stop_button)

        # Play/Pause button (Primary level - center and most prominent)
        self.play_button = QPushButton("▶")
        self.play_button.setObjectName("playButton")
        self.play_button.setToolTip(_translation_manager.tr("button_play"))
        self.play_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_PRIMARY"])
        self.play_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_PRIMARY"])
        self.play_button.setStyleSheet(
            f"padding: 12px; font-size: 36px; border-radius: {_UI_CONSTANTS['ICON_SIZE_PRIMARY'] // 2}px;",
        )
        core_layout.addWidget(self.play_button)

        # Pause button (hidden initially, same position as play)
        self.pause_button = QPushButton("⏸")
        self.pause_button.setObjectName("pauseButton")
        self.pause_button.setToolTip(_translation_manager.tr("button_pause"))
        self.pause_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_PRIMARY"])
        self.pause_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_PRIMARY"])
        self.pause_button.setStyleSheet(
            f"padding: 12px; font-size: 36px; border-radius: {_UI_CONSTANTS['ICON_SIZE_PRIMARY'] // 2}px;",
        )
        self.pause_button.setVisible(False)
        core_layout.addWidget(self.pause_button)

        main_layout.addWidget(core_group)

        # === RIGHT GROUP: Additional Controls (Mode/Quick Volume) ===
        extra_group = QWidget()
        extra_group.setObjectName("extraControlsGroup")
        extra_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, 0, 0, 0),
        )
        extra_group.setLayout(extra_layout)

        # Playback mode button (Secondary level)
        self.mode_button = QPushButton(self.music_player.playback_mode.get_symbol())
        self.mode_button.setObjectName("modeButton")
        self.mode_button.setToolTip(
            f"播放模式: {self.music_player.playback_mode.get_display_name()}",
        )
        self.mode_button.clicked.connect(self._cycle_playback_mode)
        self.mode_button.setMinimumWidth(_UI_CONSTANTS["ICON_SIZE_SECONDARY"])
        self.mode_button.setMinimumHeight(_UI_CONSTANTS["ICON_SIZE_SECONDARY"])
        self.mode_button.setStyleSheet(
            f"padding: 8px; font-size: 24px; border-radius: {_UI_CONSTANTS['ICON_SIZE_SECONDARY'] // 2}px;",
        )
        extra_layout.addWidget(self.mode_button)

        # Quick volume buttons for convenience
        volume_controls = QWidget()
        volume_controls.setObjectName("quickVolumeGroup")
        volume_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=2,
            margins=(0, 0, 0, 0),
        )
        volume_controls.setLayout(volume_layout)

        # Volume up button
        self.volume_up_button = QPushButton("🔊")
        self.volume_up_button.setObjectName("volumeUpButton")
        self.volume_up_button.setToolTip("音量+")
        self.volume_up_button.setMinimumWidth(32)
        self.volume_up_button.setMinimumHeight(24)
        # 移除本地样式设置,使用全局样式表
        volume_layout.addWidget(self.volume_up_button)

        # Volume down button
        self.volume_down_button = QPushButton("🔉")
        self.volume_down_button.setObjectName("volumeDownButton")
        self.volume_down_button.setToolTip("音量-")
        self.volume_down_button.setMinimumWidth(32)
        self.volume_down_button.setMinimumHeight(24)
        # 移除本地样式设置,使用全局样式表
        volume_layout.addWidget(self.volume_down_button)

        extra_layout.addWidget(volume_controls)

        main_layout.addWidget(extra_group)

        control_layout.addWidget(main_controls)

        # 3. Volume and additional controls (bottom)
        bottom_section = QWidget()
        bottom_section.setObjectName("bottomSection")
        bottom_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(0, _UI_CONSTANTS["COMPACT_SPACING"], 0, 0),
        )
        bottom_section.setLayout(bottom_layout)

        # Volume control
        volume_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, 0, 0, 0),
        )

        volume_icon = QLabel("🔊")
        volume_icon.setStyleSheet("font-size: 16px; padding: 0 4px;")
        volume_layout.addWidget(volume_icon)

        self.volume_slider = QSlider(Qt.Horizontal)
        self.volume_slider.setMinimum(0)
        self.volume_slider.setMaximum(100)
        self.volume_slider.setValue(70)
        self.volume_slider.setObjectName("volumeSlider")
        self.volume_slider.setMinimumWidth(120)
        volume_layout.addWidget(self.volume_slider)

        self.volume_label = QLabel("70%")
        self.volume_label.setObjectName("volumeLabel")
        self.volume_label.setStyleSheet(
            "font-size: 12px; padding: 0 4px; min-width: 32px;",
        )
        self.volume_label.setAlignment(Qt.AlignCenter)
        volume_layout.addWidget(self.volume_label)

        bottom_layout.addLayout(volume_layout)
        bottom_layout.addStretch()

        control_layout.addWidget(bottom_section)
        layout.addWidget(control_group)

    def _create_playlist_view(self, layout: QVBoxLayout) -> None:
        """Create playlist display area with extreme compact design."""
        # Playlist group - Ultra compact
        playlist_group = QWidget()
        playlist_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, _UI_CONSTANTS["MIN_MARGIN"], 0, _UI_CONSTANTS["MIN_MARGIN"]),
        )
        playlist_group.setLayout(playlist_layout)

        # Playlist header - Ultra compact
        header_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(0, 0, 0, 0),
        )
        playlist_label = QLabel(_translation_manager.tr("label_playlist"))
        playlist_label.setStyleSheet(
            f"font-size: {_UI_CONSTANTS['FONT_SIZE_MEDIUM']}px; font-weight: 500;",
        )
        header_layout.addWidget(playlist_label)

        # Folder browse button with symbol and tooltip
        browse_button = QPushButton("📁")
        browse_button.setToolTip(_translation_manager.tr("button_browse"))
        browse_button.clicked.connect(self._browse_folder)
        browse_button.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        browse_button.setStyleSheet("padding: 2px 8px; font-size: 14px;")
        header_layout.addWidget(browse_button)

        # Clear button with symbol and tooltip
        clear_button = QPushButton("🗑")
        clear_button.setToolTip(_translation_manager.tr("button_clear"))
        clear_button.clicked.connect(self._clear_playlist)
        clear_button.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        clear_button.setStyleSheet("padding: 2px 8px; font-size: 14px;")
        header_layout.addWidget(clear_button)

        header_layout.addStretch()
        playlist_layout.addLayout(header_layout)

        # Playlist widget
        self.playlist_widget = QListWidget()
        self.playlist_widget.itemDoubleClicked.connect(self._on_track_double_clicked)
        self.playlist_widget.setStyleSheet(
            f"QListWidget::item {{ padding: {_UI_CONSTANTS['TIGHT_SPACING']}px"
            f" {_UI_CONSTANTS['COMPACT_SPACING']}px; }}",
        )
        playlist_layout.addWidget(self.playlist_widget)

        layout.addWidget(playlist_group, 1)

    def _create_status_bar(self) -> None:
        """Create status bar with enhanced network status display."""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        self.status_label = QLabel(_translation_manager.tr("status_ready"))
        self.status_label.setObjectName("statusLabel")
        self.status_bar.addWidget(self.status_label)

        # 添加加载状态标签
        self.loading_status_label = QLabel("")
        self.loading_status_label.setStyleSheet("color: #666666; font-size: 11px;")
        self.status_bar.addPermanentWidget(self.loading_status_label)

        # 添加错误信息标签
        self.error_label = QLabel("")
        self.error_label.setStyleSheet("color: #ff4444; font-weight: bold;")
        self.status_bar.addPermanentWidget(self.error_label)

        # 启动状态更新定时器
        self.status_update_timer = QTimer()
        self.status_update_timer.timeout.connect(self._update_network_status)
        self.status_update_timer.start(500)  # 每500ms更新一次

    def _create_menu_bar(self) -> None:
        """Create menu bar with file and help menus."""
        menubar = self.menuBar()

        # File menu
        file_menu = menubar.addMenu(_translation_manager.tr("menu_file"))

        open_action = QAction(_translation_manager.tr("action_open_folder"), self)
        open_action.setShortcut("Ctrl+O")
        open_action.triggered.connect(self._browse_folder)
        file_menu.addAction(open_action)

        file_menu.addSeparator()

        exit_action = QAction(_translation_manager.tr("action_exit"), self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # Help menu
        help_menu = menubar.addMenu(_translation_manager.tr("menu_help"))

        about_action = QAction(_translation_manager.tr("action_about"), self)
        about_action.triggered.connect(self._show_about)
        help_menu.addAction(about_action)

    def _setup_signals(self) -> None:
        """Set up signal-slot connections."""
        # Button connections
        if self.play_button:
            self.play_button.clicked.connect(self._play_current_track)
        if self.pause_button:
            self.pause_button.clicked.connect(self._pause_playback)
        if self.stop_button:
            self.stop_button.clicked.connect(self._stop_playback)

        # Playback mode connection
        if self.mode_button:
            self.mode_button.clicked.connect(self._cycle_playback_mode)

        # Slider connections
        if self.progress_slider:
            # 使用 sliderMoved 检测拖动,valueChanged 更新显示
            self.progress_slider.sliderMoved.connect(self._on_progress_slider_moved)
            self.progress_slider.sliderReleased.connect(
                self._on_progress_slider_released,
            )
            self.progress_slider.valueChanged.connect(self._on_progress_slider_changed)

        # Additional button connections
        if self.prev_button:
            self.prev_button.clicked.connect(self._previous_track)
        if self.next_button:
            self.next_button.clicked.connect(self._next_track)

        # Quick volume button connections
        if self.volume_up_button:
            self.volume_up_button.clicked.connect(self._volume_up)
        if self.volume_down_button:
            self.volume_down_button.clicked.connect(self._volume_down)

        # Volume slider connection
        if self.volume_slider:
            self.volume_slider.valueChanged.connect(self._on_volume_slider_changed)

        if self.volume_slider:
            self.volume_slider.valueChanged.connect(self._on_volume_changed)

    def _setup_timers(self) -> None:
        """Set up periodic timers with optimized intervals."""
        self.progress_timer = QTimer()
        self.progress_timer.timeout.connect(self._update_progress)
        # 降低更新频率以减少UI压力
        self.progress_timer.setTimerType(Qt.PreciseTimer)

        # 初始化进度滑块范围
        if self.progress_slider:
            self.progress_slider.setMinimum(0)
            self.progress_slider.setMaximum(1000)  # 使用1000作为精度单位
            self.progress_slider.setValue(0)

    def _apply_styling(self) -> None:
        """Apply application styling with Vista glass theme if available."""
        config = self.music_player.config_manager.get_config()

        # 尝试使用Vista玻璃主题
        if VistaStyleManager is not None:
            try:
                theme = VistaStyleManager.get_vista_light_theme()
                self.setStyleSheet(theme)
                logger.info("Applied Vista glass theme successfully")
                return
            except Exception as e:
                logger.warning(f"Failed to apply Vista theme: {e}")

        # 降级到传统主题
        theme = StyleManager.get_theme(config.theme)
        self.setStyleSheet(theme)
        logger.info("Applied traditional theme")

    def _load_config(self) -> None:
        """Load configuration and restore state."""
        config = self.music_player.config_manager.get_config()

        # Restore volume
        if self.volume_slider:
            self.volume_slider.setValue(int(config.volume * 100))

        # Restore recent folders
        recent_folders = self.music_player.config_manager.get_recent_folders()
        if recent_folders:
            # Auto-load first recent folder
            first_folder = Path(recent_folders[0])
            if first_folder.exists():
                self._load_folder_to_playlist(first_folder)

    def _restore_window_geometry(self) -> None:
        """Restore window position and size from configuration."""
        config = self.music_player.config_manager.get_config()
        self.setGeometry(
            config.window_x,
            config.window_y,
            config.window_width,
            config.window_height,
        )

    def _browse_folder(self) -> None:
        """Open folder browser dialog."""
        folder_path = QFileDialog.getExistingDirectory(
            self,
            _translation_manager.tr("dialog_select_folder"),
            "",
            QFileDialog.ShowDirsOnly,
        )

        if folder_path:
            folder = Path(folder_path)
            self._load_folder_to_playlist(folder)

    def _load_folder_to_playlist(self, folder_path: Path) -> None:
        """Load folder contents to playlist."""
        track_count = self.music_player.load_folder_to_playlist(folder_path)

        if track_count > 0:
            # Update UI
            self._refresh_playlist_view()
            self._update_status(
                _translation_manager.tr("status_loaded_tracks").format(
                    track_count,
                    folder_path.name,
                ),
            )
        else:
            self._update_status(_translation_manager.tr("status_no_audio_files"))

    def _refresh_playlist_view(self) -> None:
        """Refresh playlist display with detailed file information."""
        if not self.playlist_widget:
            return

        self.playlist_widget.clear()

        tracks = self.music_player.get_current_playlist_tracks()
        for i, track in enumerate(tracks):
            size_str = self._format_file_size(track.file_size)
            duration_str = self._format_time(track.duration)
            filename = track.file_path.name
            display_text = (
                f"{i + 1:2d}. {track.title} - {track.artist}\n     📁 {filename} | ⏱️ {duration_str} | 💾 {size_str}"
            )

            self.playlist_widget.addItem(display_text)

    def _clear_playlist(self) -> None:
        """Clear current playlist."""
        self.music_player.clear_playlist()

        if self.playlist_widget:
            self.playlist_widget.clear()

        self._update_status(_translation_manager.tr("status_playlist_cleared"))

    def _play_current_track(self) -> None:
        """Play currently selected track."""
        if not self.playlist_widget or self.playlist_widget.count() == 0:
            self._update_status(_translation_manager.tr("status_no_tracks"))
            return

        # Get selected track or play first track
        selected_items = self.playlist_widget.selectedItems()
        if selected_items:
            track_index = self.playlist_widget.row(selected_items[0])
        else:
            track_index = 0
            self.playlist_widget.setCurrentRow(0)

        self._play_track_at_index(track_index)

    def _play_track_at_index(self, index: int) -> None:
        """Play track at specified index."""
        # Reset progress display (before playing new song)
        self._reset_progress_display()

        if self.music_player.play_track_at_index(index):
            track = self.music_player.get_track_info(index)
            if track:
                self.track_changed.emit(index)
                self._update_status(
                    _translation_manager.tr("status_playing").format(track.title),
                )
                self._update_playback_buttons(True)
        else:
            self._update_status(_translation_manager.tr("status_play_failed"))

    def _reset_progress_display(self) -> None:
        """Reset progress display to initial state with professional time labels."""
        # Reset progress slider
        if self.progress_slider:
            self.progress_slider.blockSignals(True)
            self.progress_slider.setValue(0)
            self.progress_slider.blockSignals(False)

        # Reset time labels
        if self.current_time_label:
            self.current_time_label.setText("00:00")
        if self.total_time_label:
            self.total_time_label.setText("00:00")

        # Stop and restart progress timer
        if self.progress_timer:
            self.progress_timer.stop()
            self.progress_timer.start(300)  # 降低到300ms以减少CPU负载

    def _pause_playback(self) -> None:
        """Pause/resume playback."""
        from .audio_player import PlaybackState

        if self.music_player.audio_player.state == PlaybackState.PLAYING:
            self.music_player.pause_playback()
            self._update_status(_translation_manager.tr("status_paused"))
            self._update_playback_buttons(False)
        elif self.music_player.audio_player.state == PlaybackState.PAUSED:
            if self.music_player.resume_playback():
                self._update_status(_translation_manager.tr("status_resumed"))
                self._update_playback_buttons(True)

    def _stop_playback(self) -> None:
        """Stop playback."""
        self.music_player.stop_playback()
        self._update_status(_translation_manager.tr("status_stopped"))
        self._update_playback_buttons(False)

        # Reset progress display
        self._reset_progress_display()

    def _cycle_playback_mode(self) -> None:
        """Cycle to the next playback mode."""
        new_mode = self.music_player.cycle_playback_mode()

        # Update UI display
        if self.mode_button:
            self.mode_button.setText(new_mode.get_symbol())
            self.mode_button.setToolTip(f"播放模式: {new_mode.get_display_name()}")

        if self.mode_label:
            self.mode_label.setText(new_mode.get_display_name())

        # Update status bar
        self._update_status(f"播放模式已切换为: {new_mode.get_display_name()}")

        logger.info(f"Playback mode cycled to: {new_mode.get_display_name()}")

    def _on_track_double_clicked(self, item) -> None:
        """Handle double-click on playlist item."""
        row = self.playlist_widget.row(item)
        self._play_track_at_index(row)

    def _on_progress_slider_moved(self, value: int) -> None:
        """Handle progress slider being dragged."""
        logger.debug(f"Progress slider moved to {value}")

        # 设置拖动标志
        self._is_slider_dragging = True

        # 立即停止定时器
        if self.progress_timer and self.progress_timer.isActive():
            self.progress_timer.stop()
            logger.debug("Progress timer stopped")

    def _on_progress_slider_released(self) -> None:
        """Handle progress slider release - 使用标志位而非信号阻塞."""
        logger.debug("Progress slider released")

        # 清除拖动标志
        self._is_slider_dragging = False
        logger.debug("Slider dragging flag cleared")

        # 执行跳转
        self._seek_to_slider_position()

        # 立即恢复定时器
        if self.progress_timer:
            QTimer.singleShot(50, self._restart_progress_timer)
            logger.debug("Progress timer restart scheduled")

    def _restart_progress_timer(self) -> None:
        """Restart progress timer after a short delay."""
        if self.progress_timer and not self.progress_timer.isActive():
            self.progress_timer.start(300)
            logger.debug("Progress timer restarted")

    def _on_progress_slider_changed(self, value: int) -> None:
        """Handle progress slider value change with real-time time display."""
        # During dragging, only update time display, do not update actual playback position
        if not self.progress_slider:
            return

        # If dragging, only update time display
        if self._is_slider_dragging:
            tracks = self.music_player.get_current_playlist_tracks()
            if tracks and self.music_player.current_track_index >= 0:
                track = tracks[self.music_player.current_track_index]
                if track.duration > 0:
                    # Calculate corresponding time position
                    position = (value / 1000.0) * track.duration
                    # Real-time update time display (during drag)
                    if self.current_time_label:
                        time_str = self._format_time(position)
                        self.current_time_label.setText(time_str)
                        logger.debug(f"Time updated during drag: {time_str}")
            return

        # Non-dragging state, ignore valueChanged event (updated by timer)
        logger.debug(f"Slider value changed (not dragging), value: {value}")

    def _on_volume_slider_changed(self, value: int) -> None:
        """Handle volume slider change with percentage display."""
        volume = value / 100.0
        self.music_player.set_volume(volume)
        if self.volume_label:
            self.volume_label.setText(f"{value}%")

    def _on_volume_changed(self, value: int) -> None:
        """Handle volume slider change (deprecated, kept for compatibility)."""
        volume = value / 100.0
        self.music_player.set_volume(volume)

    def _previous_track(self) -> None:
        """Play previous track in playlist."""
        if not self.playlist_widget or self.playlist_widget.count() == 0:
            return

        current_index = self.music_player.current_track_index
        if current_index > 0:
            self._play_track_at_index(current_index - 1)
            self.playlist_widget.setCurrentRow(current_index - 1)

    def _next_track(self) -> None:
        """Play next track in playlist."""
        if not self.playlist_widget or self.playlist_widget.count() == 0:
            return

        current_index = self.music_player.current_track_index
        if current_index < self.playlist_widget.count() - 1:
            self._play_track_at_index(current_index + 1)
            self.playlist_widget.setCurrentRow(current_index + 1)

    def _volume_up(self) -> None:
        """Increase volume by 5%."""
        if self.volume_slider:
            current_value = self.volume_slider.value()
            new_value = min(100, current_value + 5)
            self.volume_slider.setValue(new_value)
            self._on_volume_slider_changed(new_value)

    def _volume_down(self) -> None:
        """Decrease volume by 5%."""
        if self.volume_slider:
            current_value = self.volume_slider.value()
            new_value = max(0, current_value - 5)
            self.volume_slider.setValue(new_value)
            self._on_volume_slider_changed(new_value)

    def _update_progress(self) -> None:
        """Update progress display with performance optimization and monitoring."""
        import time

        # 性能统计
        current_time = time.time()
        _performance_stats["ui_updates"] += 1

        if _performance_stats["last_update_time"] > 0:
            interval = current_time - _performance_stats["last_update_time"]
            _performance_stats["avg_update_interval"] = _performance_stats["avg_update_interval"] * 0.9 + interval * 0.1
        _performance_stats["last_update_time"] = current_time

        tracks = self.music_player.get_current_playlist_tracks()
        if not tracks or self.music_player.current_track_index < 0:
            return

        track = tracks[self.music_player.current_track_index]
        current_position = self.music_player.audio_player.position

        # 批量更新UI组件,减少重绘次数
        ui_updates = []

        # Collect time labels that need updating (do not update during drag)
        if self.current_time_label and not self._is_slider_dragging:
            current_text = self._format_time(current_position)
            if self.current_time_label.text() != current_text:
                ui_updates.append((self.current_time_label, "setText", current_text))

        if self.total_time_label:
            total_text = self._format_time(track.duration)
            if self.total_time_label.text() != total_text:
                ui_updates.append((self.total_time_label, "setText", total_text))

        # Update progress slider (only update in non-dragging state)
        if self.progress_slider and track.duration > 0 and not self._is_slider_dragging:
            progress_percentage = (current_position / track.duration) * 1000
            current_value = self.progress_slider.value()
            new_value = int(progress_percentage)

            # 只有当变化超过阈值时才更新
            if abs(new_value - current_value) >= 5:  # 0.5%的变化阈值
                ui_updates.append((self.progress_slider, "setValue", new_value))

        # 批量执行UI更新
        if ui_updates:
            # 阻塞信号以防止递归调用
            blocked_widgets = []
            for widget, _, _ in ui_updates:
                if hasattr(widget, "blockSignals"):
                    widget.blockSignals(True)
                    blocked_widgets.append(widget)

            try:
                # 执行所有更新
                for widget, method_name, value in ui_updates:
                    method = getattr(widget, method_name)
                    method(value)
            finally:
                # 恢复信号
                for widget in blocked_widgets:
                    widget.blockSignals(False)

        # Regularly output performance statistics (every 30 seconds)
        if _performance_stats["ui_updates"] % 100 == 0:
            avg_interval_ms = _performance_stats["avg_update_interval"] * 1000
            logger.debug(
                f"Performance: Avg UI update interval: {avg_interval_ms:.1f}ms",
            )

    def _seek_to_slider_position(self) -> None:
        """Seek to position indicated by progress slider."""
        logger.info("_seek_to_slider_position called")

        if not self.progress_slider:
            logger.warning("Progress slider is None")
            return

        tracks = self.music_player.get_current_playlist_tracks()
        if not tracks or self.music_player.current_track_index < 0:
            logger.warning(
                f"No tracks or invalid index: tracks={len(tracks) if tracks else 0}, "
                f"index={self.music_player.current_track_index}",
            )
            return

        track = tracks[self.music_player.current_track_index]
        logger.info(f"Current track: {track.title}, duration={track.duration}s")

        if track.duration <= 0:
            logger.warning(f"Invalid track duration: {track.duration}")
            return

        # 获取滑块位置对应的秒数
        slider_value = self.progress_slider.value()
        target_position = (slider_value / 1000.0) * track.duration

        logger.info(
            f"Seeking: slider_value={slider_value}, target_position={target_position:.2f}s",
        )

        # 执行跳转
        result = self.music_player.seek_position(target_position)
        logger.info(f"Seek result: {result}")

        if result:
            self._update_status(f"跳转到 {self._format_time(target_position)}")
        else:
            self._update_status("跳转失败")

    def _update_playback_buttons(self, is_playing: bool) -> None:
        """Update playback button states with professional toggle behavior."""
        if self.play_button and self.pause_button:
            if is_playing:
                self.play_button.setVisible(False)
                self.pause_button.setVisible(True)
            else:
                self.play_button.setVisible(True)
                self.pause_button.setVisible(False)

    def _update_status(self, message: str) -> None:
        """Update status bar message."""
        if self.status_label:
            self.status_label.setText(message)

    def _update_network_status(self) -> None:
        """Update network loading status display."""
        if hasattr(self.music_player, "audio_player"):
            # 更新加载状态
            loading_status = getattr(
                self.music_player.audio_player,
                "loading_status",
                "",
            )
            if self.loading_status_label and loading_status:
                self.loading_status_label.setText(f"[{loading_status}]")

            # 更新错误信息
            last_error = getattr(self.music_player.audio_player, "last_error", None)
            if self.error_label:
                if last_error:
                    self.error_label.setText(f"⚠️ {last_error}")
                else:
                    self.error_label.setText("")

    def _format_time(self, seconds: float) -> str:
        """Format time in MM:SS format."""
        minutes = int(seconds // 60)
        secs = int(seconds % 60)
        return f"{minutes:02d}:{secs:02d}"

    def _format_file_size(self, size_bytes: int) -> str:
        """Format file size in human readable format."""
        if size_bytes < 1024:
            return f"{size_bytes} B"
        if size_bytes < 1024 * 1024:
            return f"{size_bytes / 1024:.1f} KB"
        if size_bytes < 1024 * 1024 * 1024:
            return f"{size_bytes / (1024 * 1024):.1f} MB"
        return f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"

    def _show_about(self) -> None:
        """Show about dialog."""
        QMessageBox.about(
            self,
            _translation_manager.tr("dialog_about_title"),
            _translation_manager.tr("dialog_about_text"),
        )

    def closeEvent(self, event) -> None:
        """Handle window close event with comprehensive cleanup."""
        # 保存配置
        self.music_player.config_manager.get_config()
        geom = self.geometry()
        self.music_player.config_manager.update_config(
            window_x=geom.x(),
            window_y=geom.y(),
            window_width=geom.width(),
            window_height=geom.height(),
            last_playlist=self.music_player.current_playlist_name,
            last_track_index=self.music_player.current_track_index,
        )

        # 清理所有定时器
        if self._memory_cleanup_timer:
            self._memory_cleanup_timer.stop()
        if self._perf_monitor_timer:
            self._perf_monitor_timer.stop()
        if self.progress_timer:
            self.progress_timer.stop()

        # 清理资源
        self.music_player.cleanup()

        # 强制垃圾回收
        import gc

        gc.collect()

        event.accept()

    def _perform_memory_cleanup(self) -> None:
        """执行内存清理操作."""
        import gc

        import psutil

        try:
            # 获取当前内存使用情况
            process = psutil.Process()
            memory_mb = process.memory_info().rss / 1024 / 1024
            _performance_stats["memory_usage"] = memory_mb

            # 如果内存使用过高, 执行清理
            if memory_mb > _MEMORY_CONFIG["min_free_memory_mb"]:
                # 清理播放器缓存
                if hasattr(self.music_player, "_preload_cache"):
                    cache_size = len(self.music_player._preload_cache)
                    if cache_size > _MEMORY_CONFIG["max_playlist_cache_size"]:
                        # 保留最近使用的缓存项
                        sorted_cache = sorted(
                            self.music_player._preload_cache.items(),
                            key=lambda x: x[1].get("last_access", 0),
                            reverse=True,
                        )
                        self.music_player._preload_cache = dict(
                            sorted_cache[: _MEMORY_CONFIG["max_playlist_cache_size"]],
                        )

                # 执行垃圾回收
                collected = gc.collect()
                _performance_stats["garbage_collections"] += 1
                logger.debug(
                    f"Memory cleanup: {collected} objects collected, {memory_mb:.1f}MB used",
                )

        except Exception as e:
            logger.warning(f"Memory cleanup error: {e}")

    def _monitor_system_performance(self) -> None:
        """监控系统性能指标."""
        import psutil

        try:
            process = psutil.Process()
            cpu_percent = process.cpu_percent()
            memory_mb = process.memory_info().rss / 1024 / 1024

            _performance_stats["cpu_usage"] = cpu_percent
            _performance_stats["memory_usage"] = memory_mb

            # 性能警告
            if cpu_percent > 80:
                logger.warning(f"High CPU usage: {cpu_percent}%")
            if memory_mb > 500:
                logger.warning(f"High memory usage: {memory_mb:.1f}MB")

        except Exception as e:
            logger.warning(f"Performance monitoring error: {e}")


def main() -> None:
    """Run main entry point for music player GUI application."""
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(levelname)s - %(message)s",
    )

    app = QApplication(sys.argv)
    app.setApplicationName("Music Player")
    app.setApplicationVersion("0.1.0")

    try:
        window = MusicPlayerGUI()
        window.show()
        sys.exit(app.exec_())
    except Exception as e:
        logger.exception(f"Failed to start music player: {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
