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

from __future__ import annotations

import logging
import sys

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

# Import from lscopt module
try:
    from .cli import LSCCurve
except ImportError:
    try:
        from pytola_sim.lscopt.cli import LSCCurve
    except ImportError as e:
        msg = "LSCCurve could not be imported"
        raise ImportError(msg) from e

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

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


class LSCOptimizerConfig(ConfigMixin):
    """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


conf = LSCOptimizerConfig()


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,
    ) -> 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) -> 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) -> 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) -> None:
        """Initialize GUI components and setup application state.

        Creates configuration manager, loads settings, initializes UI,
        and sets up signal connections.
        """
        super().__init__()
        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) -> None:
        """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) -> None:
        """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) -> None:
        """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) -> None:
        """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) -> None:
        """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) -> None:
        """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) -> None:
        """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) -> None:
        """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"], conf.m, -5.0, 0, 0.05),
            ("m1", param_labels["m1"], conf.m1, -10.0, 0.0, 0.2),
            ("s", param_labels["s"], conf.s, 0.0, 10.0, 0.1),
            ("s1", param_labels["s1"], conf.s1, 0.0, 20.0, 0.1),
            ("H", param_labels["H"], conf.H, 0.0, 5.0, 0.1),
            ("m2", param_labels["m2"], conf.m2, -2.0, 2.0, 0.1),
            ("H1", param_labels["H1"], conf.H1, 0.0, 2.0, 0.1),
            ("H2", param_labels["H2"], conf.H2, 0.0, 2.0, 0.1),
            ("J", param_labels["J"], conf.J, 0.0, 180.0, 1.0),
            ("J1", param_labels["J1"], conf.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) -> None:
        """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) -> None:
        """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) -> None:
        """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)

        except (OSError, RuntimeError, ValueError) as e:
            logger.exception("Calculation error")
            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) -> None:
        """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(conf, 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) -> None:
        """Load window geometry and parameter values from configuration.

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

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

    def keyPressEvent(self, event: QKeyEvent) -> None:
        """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() -> None:
    """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()
    apply_theme(window, "monokai")
    window.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
