"""PySide2 GUI version of LSC optimizer application."""

from __future__ import annotations

import json
import logging
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar

import numpy as np
import PySide2
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (
    QApplication,
    QDoubleSpinBox,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QMainWindow,
    QPushButton,
    QScrollArea,
    QSizePolicy,
    QVBoxLayout,
    QWidget,
)

# Import from lscopt module
try:
    from .lscopt import LSCCurve
except ImportError:
    try:
        from pytola.simulation.lscopt.lscopt import LSCCurve
    except ImportError as e:
        raise ImportError("LSCCurve could not be imported") from e

# Import translation system
try:
    from .translation import translator
except ImportError:
    try:
        from pytola.simulation.lscopt.translation import translator
    except ImportError as e:
        raise ImportError("Translator could not be imported") from e

logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)

# 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


@dataclass
class LSCOptimizerConfig:
    """Configuration class for LSC Optimizer GUI with persistent storage.

    Manages GUI settings including window geometry and default parameter values.
    Configuration is automatically saved to ~/.pytola/lscopt.json
    """

    # Window geometry settings
    window_width: int = 1200
    window_height: int = 800
    window_x: int = 100
    window_y: int = 100

    # Default LSC curve parameter values
    m: float = -1.3
    m1: float = -2.4
    s: float = 1.2183
    s1: float = 8.1
    H: float = 0.5
    m2: float = 0.5
    H1: float = 0.2
    H2: float = 0.65
    J: float = 80.0
    J1: float = 40.0

    def __post_init__(self) -> None:
        """Post-initialization hook for configuration setup."""


class ConfigManager:
    """Manager class for GUI configuration persistence.

    Handles loading, saving, and updating of GUI configuration settings.
    Uses dataclass pattern for type safety and automatic serialization.
    """

    CONFIG_FILE: ClassVar[Path] = Path.home() / ".pytola" / "lscopt.json"
    DEFAULT_CONFIG: ClassVar[LSCOptimizerConfig] = LSCOptimizerConfig()

    def __init__(self, config_file: Path | None = None):
        """Initialize configuration manager with optional custom config file.

        Args:
            config_file: Optional custom path for configuration file.
                      If None, uses default location ~/.pytola/lscopt.json
        """
        if config_file is not None:
            self.config_file = config_file
        else:
            self.config_file = self.CONFIG_FILE
            self.config_file.parent.mkdir(parents=True, exist_ok=True)

        self.config = self.load_config()

    def load_config(self) -> LSCOptimizerConfig:
        """Load configuration from file or return default configuration.

        Returns
        -------
            LSCOptimizerConfig: Loaded configuration or defaults if file doesn't exist
                              or loading fails
        """
        if not self.config_file.exists():
            return self.DEFAULT_CONFIG

        try:
            with open(self.config_file, "r", encoding="utf-8") as f:
                data = json.load(f)

            # Create config with loaded values, falling back to defaults
            config_dict = {}
            for field_name in self.DEFAULT_CONFIG.__dataclass_fields__:
                config_dict[field_name] = data.get(field_name, getattr(self.DEFAULT_CONFIG, field_name))

            return LSCOptimizerConfig(**config_dict)
        except (json.JSONDecodeError, KeyError, TypeError) as e:
            logger.warning(f"Could not load config from {self.config_file}: {e}")
            return self.DEFAULT_CONFIG

    def save_config(self) -> None:
        """Save current configuration to JSON file.

        Persists all current configuration values to the configuration file.
        Creates directory structure if needed.
        """
        try:
            config_dict = {
                field_name: getattr(self.config, field_name) for field_name in self.config.__dataclass_fields__
            }
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(config_dict, f, indent=4)
        except Exception as e:
            logger.error(f"Failed to save config: {e}")

    def get_config(self) -> LSCOptimizerConfig:
        """Get current active configuration.

        Returns
        -------
            LSCOptimizerConfig: Current configuration instance
        """
        return self.config

    def update_config(self, **kwargs) -> None:
        """Update configuration with new parameter values.

        Args:
            **kwargs: Configuration field names and their new values
        """
        for key, value in kwargs.items():
            if hasattr(self.config, key):
                setattr(self.config, key, value)


class ParameterWidget(QWidget):
    """Widget for numerical parameter input using double spinbox.

    Provides labeled input control for floating-point parameters with
    configurable ranges and step sizes.
    """

    def __init__(
        self,
        name: str,
        label: str,
        default_value: float,
        min_val: float,
        max_val: float,
        step: float,
        parent: QWidget | None = None,
    ):
        """Initialize parameter input widget.

        Args:
            name: Internal parameter name
            label: Display label for the parameter
            default_value: Initial/default value
            min_val: Minimum allowed value
            max_val: Maximum allowed value
            step: Step size for increment/decrement
            parent: Parent widget
        """
        super().__init__(parent)
        self.name = name
        self.label = label
        self.default_value = default_value

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        # Label with improved styling - 增大标签尺寸
        self.label_widget = QLabel(label)
        self.label_widget.setMinimumWidth(160)  # 增大最小宽度
        self.label_widget.setMaximumWidth(220)  # 增大最大宽度
        self.label_widget.setStyleSheet("font-size: 18px;")  # 设置字体大小
        layout.addWidget(self.label_widget)

        # Spinbox with enhanced styling and spacing - 增大输入框尺寸
        self.spinbox = QDoubleSpinBox()
        self.spinbox.setRange(min_val, max_val)
        self.spinbox.setValue(default_value)
        self.spinbox.setSingleStep(step)
        self.spinbox.setDecimals(4 if abs(step) < 1 else 2)
        self.spinbox.setMinimumWidth(150)  # 增大最小宽度
        self.spinbox.setMinimumHeight(36)  # 设置最小高度
        self.spinbox.setButtonSymbols(QDoubleSpinBox.UpDownArrows)  # 显式启用上下箭头
        layout.addWidget(self.spinbox)

        # Spacer for better alignment
        spacer = QWidget()
        spacer.setMinimumWidth(25)  # 增加间距
        spacer.setMaximumWidth(50)
        layout.addWidget(spacer)

    def get_value(self) -> float:
        """Get current value from the spinbox.

        Returns
        -------
            float: Current parameter value
        """
        return self.spinbox.value()

    def set_value(self, value: float) -> None:
        """Set parameter value in the spinbox.

        Args:
            value: New value to set
        """
        self.spinbox.setValue(value)


class PlotWidget(QWidget):
    """Widget wrapper for matplotlib plotting.

    Integrates matplotlib figure canvas for LSC curve visualization.
    """

    def __init__(self, parent: QWidget | None = None):
        """Initialize matplotlib plot widget.

        Args:
            parent: Parent widget
        """
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(5)

        # Set minimum size for the plot widget
        self.setMinimumSize(480, 480)

        # Create matplotlib figure with default style
        self.figure = Figure(figsize=(10, 7), tight_layout=True)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        layout.addWidget(self.canvas)

        # Store axes reference
        self.ax = self.figure.add_subplot(111)

    def clear_plot(self) -> None:
        """Clear current plot."""
        self.ax.clear()
        self.canvas.draw()

    def update_plot(self, lscc: LSCCurve) -> None:
        """Update plot with new LSC curve data.

        Args:
            lscc: LSCCurve instance containing curve data to plot
        """
        self.ax.clear()

        # Calculate curve data
        i = np.linspace(lscc.m, 0, 100)
        j = np.linspace(lscc.m1, 0, 100)

        # Calculate internal segment curves
        y1 = lscc.x[0] + lscc.x[1] * i + lscc.x[2] * i**2 + lscc.x[3] * i**3  # Inner upper
        y2 = lscc.x[4] + lscc.x[5] * i + lscc.x[6] * i**2 + lscc.x[7] * i**3  # Inner lower

        # Calculate external segment curves
        g1 = lscc.x[8] + lscc.x[9] * j + lscc.x[10] * j**2 + lscc.x[11] * j**3  # Outer upper
        g2 = lscc.x[12] + lscc.x[13] * j + lscc.x[14] * j**2 + lscc.x[15] * j**3  # Outer lower

        # Plot curves with default matplotlib style
        self.ax.plot(i, y1, label="Inner Top")
        self.ax.plot(i, y2, label="Inner Bottom")
        self.ax.plot(j, g1, label="Outer Top")
        self.ax.plot(j, g2, label="Outer Bottom")

        # Calculate and plot key points
        y3_point = lscc.x[0] + lscc.x[1] * lscc.m + lscc.x[2] * lscc.ms + lscc.x[3] * lscc.mc
        g3_point = lscc.x[8] + lscc.x[9] * lscc.m1 + lscc.x[10] * lscc.m1s + lscc.x[11] * lscc.m1c

        self.ax.plot(lscc.m, y3_point, marker="o", markersize=8, label=f"Inner ({lscc.m:.1f}, {y3_point:.2f})")
        self.ax.plot(lscc.m1, g3_point, marker="s", markersize=8, label=f"Outer ({lscc.m1:.1f}, {g3_point:.2f})")

        # Standard plot settings
        self.ax.set_xlabel("X")
        self.ax.set_ylabel("Y")
        self.ax.set_title("LSC Curve Optimization Results")
        self.ax.legend(loc="best")
        self.ax.grid(True)
        self.ax.axis("equal")

        self.canvas.draw()


class ResultDisplayWidget(QWidget):
    """Enhanced widget for displaying LSC optimization calculation results.

    Shows optimization results with modern styling including solution vector norm
    and residual cost in a visually appealing formatted display area.
    """

    def __init__(self, parent: QWidget | None = None):
        """Initialize enhanced result display widget with modern styling.

        Sets up layout with modern visual hierarchy, consistent spacing,
        and responsive design elements.

        Args:
            parent: Parent widget
        """
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setSpacing(8)
        layout.setContentsMargins(8, 8, 8, 8)

        # Modern container styling - 深度美化结果容器
        self.setStyleSheet("""
            QWidget {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                stop:0 #ffffff, stop:1 #f1f5f9);
                border: 2px solid #cbd5e1;
                border-radius: 18px;
            }
        """)

        # Enhanced title with modern styling - 深度美化标题
        title_label = QLabel(translator.tr("results_panel"))
        title_label.setObjectName("resultTitle")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 24px;
                font-weight: 800;
                color: #1e293b;
                padding: 12px 0px 15px 0px;
                border-bottom: 3px solid #4a6fa5;
                font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
                text-transform: uppercase;
                letter-spacing: 1px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 transparent, stop:0.5 #4a6fa5, stop:1 transparent);
            }
        """)
        layout.addWidget(title_label)

        # Enhanced results display with modern card styling - 深度美化内容区域
        self.result_text = QLabel(translator.tr("ready_text"))
        self.result_text.setWordWrap(True)
        self.result_text.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.result_text.setObjectName("resultContent")
        self.result_text.setStyleSheet("""
            QLabel {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                stop:0 #f8fafc, stop:1 #e2e8f0);
                border: 2px solid #cbd5e1;
                border-radius: 14px;
                padding: 20px 24px;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
                font-size: 19px;
                color: #0f5132;
                font-weight: 500;
            }
        """)
        layout.addWidget(self.result_text)

    def update_results(self, norm: float, cost: float) -> None:
        """Update display with new calculation results using enhanced formatting.

        Args:
            norm: Solution vector norm value
            cost: Optimization residual cost
        """
        formatted_text = (
            f"{translator.tr('calculation_success')}\n\n"
            f"{translator.tr('solution_norm')}: {norm:.4f}\n"
            f"{translator.tr('optimization_residual')}: {cost:.6f}"
        )
        self.result_text.setText(formatted_text)

    def show_error(self, message: str) -> None:
        """Display error message with appropriate styling.

        Args:
            message: Error message to display
        """
        self.result_text.setText(f"{translator.tr('error_prefix')}{message}")
        self.result_text.setStyleSheet("background-color: #ffebee; color: #c62828; padding: 10px;")


class LSCOptimizerGUI(QMainWindow):
    """Main GUI window for LSC optimizer application.

    Provides complete graphical interface for LSC curve optimization
    including parameter input, real-time plotting, and result display.
    Features persistent configuration and keyboard shortcuts.
    """

    def __init__(self):
        """Initialize GUI components and setup application state.

        Creates configuration manager, loads settings, initializes UI,
        and sets up signal connections.
        """
        super().__init__()
        self.config_manager = ConfigManager()
        self.config = self.config_manager.get_config()
        self.lscc: LSCCurve | None = None
        self.auto_calc_timer = None  # Timer for debouncing auto-calculations
        self.init_ui()
        self.load_settings()
        self.setup_connections()

    def init_ui(self):
        """Initialize and setup the complete user interface with modern styling.

        Creates main window layout with parameter input panel on left
        and results/plotting panel on right. Applies unified modern
        color scheme, typography, and visual hierarchy.
        """
        self.setWindowTitle(translator.tr("window_title"))
        self.setMinimumSize(1200, 700)  # 增加最小宽度以适应绘图区

        # Apply modern window styling
        self.setStyleSheet(self._get_modern_stylesheet())

        # Create application menu bar
        self.create_menu_bar()

        # Create status bar for calculation results
        self.create_status_bar()

        # Create main central widget with modern styling
        central_widget = QWidget()
        central_widget.setObjectName("centralWidget")
        self.setCentralWidget(central_widget)
        main_layout = QHBoxLayout(central_widget)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # Left panel for parameter input with modern styling
        left_panel = QGroupBox(translator.tr("parameters_panel"))
        left_panel.setObjectName("parameterPanel")
        left_layout = QVBoxLayout(left_panel)
        left_layout.setSpacing(12)  # 减小垂直间距
        left_layout.setContentsMargins(16, 16, 16, 16)  # 减小面板边距

        # Enhanced scrollable area for parameter controls with improved styling
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setObjectName("parameterScrollArea")
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: transparent;
            }
            QScrollArea > QWidget > QWidget {
                background-color: transparent;
            }
        """)

        scroll_widget = QWidget()
        scroll_widget.setObjectName("scrollWidget")
        self.params_layout = QFormLayout(scroll_widget)
        self.params_layout.setSpacing(12)  # 减小行间距
        self.params_layout.setContentsMargins(12, 12, 12, 12)  # 减小滚动区边距
        self.params_layout.setLabelAlignment(Qt.AlignLeft)  # type: ignore[arg-type]
        self.params_layout.setRowWrapPolicy(QFormLayout.DontWrapRows)  # Prevent label wrapping

        scroll_area.setWidget(scroll_widget)
        left_layout.addWidget(scroll_area)

        # Add visual separator before parameter widgets - 美化分隔线
        separator = QWidget()
        separator.setFixedHeight(2)
        separator.setStyleSheet("""
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                      stop:0 transparent, stop:0.5 #4a6fa5, stop:1 transparent);
            margin: 8px 0px;
            border-radius: 1px;
        """)
        left_layout.addWidget(separator)

        # Initialize all parameter input widgets
        self.create_parameter_widgets()

        # Add visual separator after parameter widgets - 美化分隔线
        separator2 = QWidget()
        separator2.setFixedHeight(2)
        separator2.setStyleSheet("""
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                      stop:0 transparent, stop:0.5 #4a6fa5, stop:1 transparent);
            margin: 8px 0px;
            border-radius: 1px;
        """)
        left_layout.addWidget(separator2)

        # Main calculation trigger button with modern styling - 增大按钮字体
        self.calculate_button = QPushButton(translator.tr("calculate_button"))
        self.calculate_button.setCursor(Qt.PointingHandCursor)
        self.calculate_button.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #22c55e, stop:1 #16a34a);
                color: white;
                border: none;
                border-radius: 12px;
                padding: 16px 32px;
                font-size: 18px;
                font-weight: 700;
                font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
                min-height: 32px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #16a34a, stop:1 #15803d);
                border: 2px solid #22c55e;
                margin: -2px;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #15803d, stop:1 #166534);
                border: 1px solid #22c55e;
                margin: 0px;
            }
            QPushButton:disabled {
                background: #d1d5db;
                color: #6b7280;
            }
        """)
        left_layout.addWidget(self.calculate_button)

        # Reset to default values button with modern styling - 增大按钮字体
        self.reset_button = QPushButton(translator.tr("reset_button"))
        self.reset_button.setCursor(Qt.PointingHandCursor)
        self.reset_button.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #ef4444, stop:1 #dc2626);
                color: white;
                border: none;
                border-radius: 10px;
                padding: 14px 28px;
                font-size: 16px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
                min-height: 28px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #dc2626, stop:1 #b91c1c);
                border: 2px solid #ef4444;
                margin: -1px;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #b91c1c, stop:1 #991b1b);
                border: 1px solid #ef4444;
                margin: 0px;
            }
        """)
        left_layout.addWidget(self.reset_button)

        # Right panel for visualization only - 移除结果区域, 全部空间给绘图区
        right_panel = QWidget()
        right_panel.setObjectName("plotPanel")
        right_layout = QVBoxLayout(right_panel)
        right_layout.setSpacing(0)  # 移除间距
        right_layout.setContentsMargins(0, 0, 0, 0)

        # Matplotlib plotting widget - 占据全部空间
        self.plot_widget = PlotWidget()
        right_layout.addWidget(self.plot_widget, 1)  # stretch=1 让绘图区完全扩展

        # Arrange panels in main horizontal layout with proper proportions
        main_layout.addWidget(left_panel, 1)
        main_layout.addWidget(right_panel, 2)

        # Apply final styling adjustments
        self._apply_component_styling()

    def create_menu_bar(self):
        """Create application menu bar with standard File and Help menus.

        Sets up menu structure with keyboard shortcuts for common operations.
        """
        menubar = self.menuBar()

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

        # Reset parameters menu action
        reset_action = file_menu.addAction(translator.tr("menu_reset"))
        reset_action.triggered.connect(self.reset_parameters)
        reset_action.setShortcut("Ctrl+R")

        file_menu.addSeparator()

        # Application exit menu action
        exit_action = file_menu.addAction(translator.tr("menu_exit"))
        exit_action.triggered.connect(self.close)
        exit_action.setShortcut("Ctrl+Q")

        # Help and information menu
        help_menu = menubar.addMenu(translator.tr("menu_help"))

        # About dialog menu action
        about_action = help_menu.addAction(translator.tr("menu_about"))
        about_action.triggered.connect(self.show_about)

    def create_status_bar(self):
        """Create status bar for displaying calculation results and application status.

        Sets up status bar with permanent widget for real-time calculation feedback.
        """
        from PySide2.QtWidgets import QLabel

        # Create status bar
        self.status_bar = self.statusBar()

        # Create permanent widget for calculation results
        self.calc_status_label = QLabel(translator.tr("ready_text"))
        self._set_ready_style()

        # Add to status bar
        self.status_bar.addPermanentWidget(self.calc_status_label)

        # Set initial status message
        self.status_bar.showMessage(translator.tr("ready_status"))

    def _set_ready_style(self):
        """Set status label style for ready state."""
        self.calc_status_label.setStyleSheet("""
            QLabel {
                color: #334155;
                font-size: 16px;
                font-weight: 600;
                padding: 8px 16px;
                background-color: rgba(255, 255, 255, 0.95);
                border: 1px solid #cbd5e1;
                border-radius: 8px;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
            }
        """)

    def _set_success_style(self):
        """Set status label style for successful calculation state."""
        self.calc_status_label.setStyleSheet("""
            QLabel {
                color: #166534;
                font-size: 16px;
                font-weight: 600;
                padding: 8px 16px;
                background-color: rgba(240, 253, 244, 0.95);
                border: 1px solid #86efac;
                border-radius: 8px;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
            }
        """)

    def _set_error_style(self):
        """Set status label style for error state."""
        self.calc_status_label.setStyleSheet("""
            QLabel {
                color: #b91c1c;
                font-size: 16px;
                font-weight: 600;
                padding: 8px 16px;
                background-color: rgba(254, 242, 242, 0.95);
                border: 1px solid #fecaca;
                border-radius: 8px;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
            }
        """)

    def _get_modern_stylesheet(self) -> str:
        """Generate comprehensive modern stylesheet for the application.

        Returns
        -------
            str: Complete CSS stylesheet string for modern UI theming
        """
        return """
        /* Main window styling - 增大基础字体 */
        QMainWindow {
            background-color: #f5f7fa;
            font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
            font-size: 18px;
        }

        /* 全局字体设置 */
        QWidget {
            font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
            font-size: 18px;
        }

        /* Central widget */
        #centralWidget {
            background-color: transparent;
        }

        /* Parameter panel styling - 深度美化参数面板 */
        #parameterPanel {
            background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                            stop:0 #ffffff, stop:1 #f8fafc);
            border: 2px solid #e2e8f0;
            border-radius: 20px;
            font-weight: 500;
            color: #1a1a2e;
            margin: 0px;
            padding-top: 35px;
        }

        #parameterPanel::title {
            subcontrol-origin: margin;
            subcontrol-position: top center;
            padding: 14px 22px;
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                      stop:0 #3b82f6, stop:1 #1d4ed8);
            color: white;
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;
            border-bottom: 2px solid #1e40af;
            font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
            font-size: 18px;
            font-weight: 600;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }

        /* Scroll area styling */
        #parameterScrollArea {
            border: none;
            background-color: transparent;
        }

        #scrollWidget {
            background-color: transparent;
        }

        /* Results panel styling */
        #resultsPanel {
            background-color: transparent;
        }

        /* Form layout labels - 增大标签字体 */
        QFormLayout QLabel {
            color: #1a1a2e;
            font-weight: 500;
            font-size: 18px;
            font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
            padding: 6px 12px 6px 0px;
        }

        /* Menu bar styling - Unified blue theme */
        QMenuBar {
            background-color: #0f172a;
            color: white;
            border-bottom: 2px solid #3b82f6;
            padding: 4px;
            font-size: 15px;
            font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
        }

        QMenuBar::item {
            background: transparent;
            padding: 10px 16px;
            border-radius: 6px;
        }

        QMenuBar::item:selected {
            background-color: #3b82f6;
        }

        QMenuBar::item:pressed {
            background-color: #2563eb;
        }

        QMenu {
            background-color: white;
            color: #0f172a;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 8px 0px;
        }

        QMenu::item {
            padding: 12px 30px;
            font-size: 16px;
            font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
        }

        QMenu::item:selected {
            background-color: #dbeafe;
            color: #1d4ed8;
        }

        /* Scrollbar styling - 现代滚动条 */
        QScrollBar:vertical {
            border: none;
            background-color: #f0f2f5;
            width: 14px;
            border-radius: 7px;
            margin: 2px;
        }

        QScrollBar::handle:vertical {
            background-color: #c5cad3;
            border-radius: 7px;
            min-height: 30px;
        }

        QScrollBar::handle:vertical:hover {
            background-color: #a0a8b5;
        }

        QScrollBar::handle:vertical:pressed {
            background-color: #8890a0;
        }

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

        /* QDoubleSpinBox 全局样式 - 增大字体和尺寸 */
        QDoubleSpinBox {
            font-size: 18px;
            font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
            padding: 10px 14px;
            min-height: 24px;
        }
        """

    def _apply_component_styling(self) -> None:
        """Apply additional component-specific styling adjustments."""
        # Style parameter labels - 增大字体尺寸
        for widget in self.param_widgets.values():
            widget.label_widget.setStyleSheet("""
                color: #1a1a2e;
                font-weight: 600;
                font-size: 18px;
                font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
                padding: 8px 16px 8px 6px;
                text-align: right;
            """)

    def show_about(self):
        """Show application about dialog with version and usage information.

        Displays application version, description, and keyboard shortcuts.
        """
        from PySide2.QtWidgets import QMessageBox

        QMessageBox.about(
            self,
            translator.tr("about_title"),
            translator.tr("about_content"),
        )

    def create_parameter_widgets(self):
        """Create and initialize all parameter input widgets.

        Sets up parameter controls for all LSC curve parameters with
        appropriate ranges, labels, and default values.
        """
        # Get translated parameter labels
        param_labels = translator.tr_params()  # Get all parameter labels

        # Define all LSC parameters with their configuration using translated labels
        params = [
            ("m", param_labels["m"], self.config.m, -5.0, 0, 0.05),
            ("m1", param_labels["m1"], self.config.m1, -10.0, 0.0, 0.2),
            ("s", param_labels["s"], self.config.s, 0.0, 10.0, 0.1),
            ("s1", param_labels["s1"], self.config.s1, 0.0, 20.0, 0.1),
            ("H", param_labels["H"], self.config.H, 0.0, 5.0, 0.1),
            ("m2", param_labels["m2"], self.config.m2, -2.0, 2.0, 0.1),
            ("H1", param_labels["H1"], self.config.H1, 0.0, 2.0, 0.1),
            ("H2", param_labels["H2"], self.config.H2, 0.0, 2.0, 0.1),
            ("J", param_labels["J"], self.config.J, 0.0, 180.0, 1.0),
            ("J1", param_labels["J1"], self.config.J1, 0.0, 180.0, 1.0),
        ]

        # Create widget instances and store references
        self.param_widgets = {}
        for name, label, default, min_val, max_val, step in params:
            widget = ParameterWidget(name, label, default, min_val, max_val, step)
            self.param_widgets[name] = widget
            self.params_layout.addRow(widget.label_widget, widget)

            # Connect parameter changes to auto-calculation
            widget.spinbox.valueChanged.connect(self.auto_calculate_lsc)

    def setup_connections(self):
        """Set up Qt signal-slot connections for UI interactions.

        Connects button clicks, menu actions, and other UI events
        to their respective handler methods.
        """
        from PySide2.QtCore import QTimer

        # Initialize auto-calculation timer with 500ms debounce
        self.auto_calc_timer = QTimer()
        self.auto_calc_timer.setSingleShot(True)
        self.auto_calc_timer.timeout.connect(self.calculate_lsc)

        self.calculate_button.clicked.connect(self.calculate_lsc)
        self.reset_button.clicked.connect(self.reset_parameters)

    def auto_calculate_lsc(self):
        """Trigger auto-calculation with debouncing.

        Uses a timer to debounce rapid parameter changes and
        prevent excessive calculations during interactive adjustment.
        """
        if self.auto_calc_timer:
            # Restart timer - this cancels previous timeout and schedules new one
            self.auto_calc_timer.start(500)  # 500ms delay before calculation

    def calculate_lsc(self):
        """Perform LSC curve optimization calculation.

        Collects current parameter values, runs optimization,
        updates results display, and refreshes plot visualization.
        Handles errors gracefully with user feedback.
        """
        try:
            # Collect all parameter values from input widgets
            params = {name: widget.get_value() for name, widget in self.param_widgets.items()}

            # Initialize LSC curve with current parameters
            self.lscc = LSCCurve(**params)

            # Update status bar with calculation metrics
            norm = float(np.linalg.norm(self.lscc.x))
            cost = self.lscc.R.cost
            status_text = (
                f"{translator.tr('calculation_success')} | "
                f"{translator.tr('solution_norm')}: {norm:.4f} | {translator.tr('optimization_residual')}: {cost:.6f}"
            )
            self.calc_status_label.setText(status_text)
            self._set_success_style()
            self.status_bar.showMessage(translator.tr("calculation_complete_status"), 5000)  # 显示5秒

            # Refresh plot with new curve data
            self.plot_widget.update_plot(self.lscc)

            # Persist current parameter values to configuration
            self.config_manager.update_config(**params)

        except Exception as e:
            logger.error(f"Calculation error: {e}")
            error_text = f"{translator.tr('error_prefix')}{e!s}"
            self.calc_status_label.setText(error_text)
            self._set_error_style()
            self.status_bar.showMessage(translator.tr("calculation_error_status"), 5000)

    def reset_parameters(self):
        """Reset all parameter inputs to their default configuration values.

        Clears plot display and resets results panel to initial state.
        """
        for name, widget in self.param_widgets.items():
            default_value = getattr(self.config_manager.DEFAULT_CONFIG, name)
            widget.set_value(default_value)

        # Clear visualization and reset status
        self.plot_widget.clear_plot()
        self.calc_status_label.setText(translator.tr("ready_text"))
        self._set_ready_style()
        self.status_bar.showMessage(translator.tr("ready_status"))

    def load_settings(self):
        """Load window geometry and parameter values from configuration.

        Restores window position/size and sets parameter widgets to
        previously saved values.
        """
        self.resize(self.config.window_width, self.config.window_height)
        self.move(self.config.window_x, self.config.window_y)

        # Apply saved parameter values to input widgets
        for name, widget in self.param_widgets.items():
            value = getattr(self.config, name)
            widget.set_value(value)

    def closeEvent(self, event):
        """Handle window closing - save configuration."""
        # Save window geometry
        self.config_manager.update_config(
            window_width=self.width(), window_height=self.height(), window_x=self.x(), window_y=self.y()
        )

        # Save current parameter values
        params = {name: widget.get_value() for name, widget in self.param_widgets.items()}
        self.config_manager.update_config(**params)

        # Save to file
        self.config_manager.save_config()

        super().closeEvent(event)

    def keyPressEvent(self, event):
        """Handle global keyboard shortcut events.

        Processes Enter/Return for calculation and Escape for reset.
        Delegates other keys to parent class.

        Args:
            event: Qt key press event
        """
        if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            # Return/Enter key initiates calculation
            self.calculate_lsc()
        elif event.key() == Qt.Key_Escape:
            # Escape key triggers parameter reset
            self.reset_parameters()
        else:
            super().keyPressEvent(event)


def main():
    """Run main entry point for LSC Optimizer GUI application.

    Initializes Qt application, creates main window, and starts
    the event loop. Handles application lifecycle and cleanup.
    """
    app = QApplication(sys.argv)

    # Configure application metadata
    app.setApplicationName("LSC Optimizer")
    app.setApplicationVersion("0.1.0")

    window = LSCOptimizerGUI()
    window.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
