"""Splash/loading window — shown during startup so user knows the app is loading."""

from __future__ import annotations

import sys


class SplashWindow:
    """Centered frameless window: shows 'Loading...' then 'Ready!', then fades out."""

    def __init__(self) -> None:
        from PyQt6.QtCore import QPropertyAnimation, QTimer, Qt, pyqtSignal, QObject, QEasingCurve
        from PyQt6.QtGui import QFont
        from PyQt6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QGraphicsOpacityEffect

        class _Signals(QObject):
            ready = pyqtSignal()
            close = pyqtSignal()

        self._signals = _Signals()
        self.ready_signal = self._signals.ready
        self.close_signal = self._signals.close

        # Main window
        self._win = QWidget()
        self._win.setWindowFlags(
            Qt.WindowType.FramelessWindowHint
            | Qt.WindowType.WindowStaysOnTopHint
            | Qt.WindowType.Tool
        )
        self._win.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self._win.setFixedSize(320, 150)

        # Background panel
        self._bg = QWidget(self._win)
        self._bg.setGeometry(0, 0, 320, 150)
        self._bg.setStyleSheet(
            "background: qlineargradient(x1:0,y1:0,x2:1,y2:1,"
            "stop:0 #0d0d1a, stop:1 #141428);"
            "border: 1px solid rgba(58,139,255,0.15);"
            "border-radius: 16px;"
        )

        # Layout
        layout = QVBoxLayout(self._bg)
        layout.setContentsMargins(24, 20, 24, 20)
        layout.setSpacing(6)

        # Logo/title
        self._title = QLabel("🐜 Muravey")
        self._title.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        self._title.setStyleSheet("color: rgba(255,255,255,0.4); background: transparent; border: none;")
        self._title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self._title)

        # Status label
        self._label = QLabel("Loading...")
        self._label.setFont(QFont("Segoe UI", 16, QFont.Weight.Bold))
        self._label.setStyleSheet("color: rgba(58,139,255,0.8); background: transparent; border: none;")
        self._label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self._label)

        # Trial info label
        self._trial_label = QLabel("")
        self._trial_label.setFont(QFont("Segoe UI", 9))
        self._trial_label.setStyleSheet("color: rgba(255,255,255,0.2); background: transparent; border: none;")
        self._trial_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self._trial_label)

        # Opacity effect for fade-out
        self._opacity = QGraphicsOpacityEffect(self._win)
        self._opacity.setOpacity(1.0)
        self._win.setGraphicsEffect(self._opacity)

        # Connect signals
        self._signals.ready.connect(self._on_ready)
        self._signals.close.connect(self._do_close)

        self._QPropertyAnimation = QPropertyAnimation
        self._QEasingCurve = QEasingCurve
        self._QTimer = QTimer

        # Center on screen
        screen = QApplication.primaryScreen()
        if screen:
            geo = screen.availableGeometry()
            x = geo.x() + (geo.width() - 320) // 2
            y = geo.y() + (geo.height() - 150) // 2
            self._win.move(x, y)

        self._win.show()

    def set_ready(self) -> None:
        """Call from any thread — changes text to ready and schedules fade-out."""
        self.ready_signal.emit()

    def _on_ready(self) -> None:
        self._label.setText("Your assistant is ready!")
        self._label.setStyleSheet("color: rgba(100,255,160,0.8); background: transparent; border: none;")
        # Show trial expiry date with warning if close
        try:
            from datetime import datetime, timezone
            _cutoff = datetime(2026, 4, 21, 23, 59, 59, tzinfo=timezone.utc)
            now = datetime.now(timezone.utc)
            if now < _cutoff:
                days = (_cutoff - now).days
                if days <= 3:
                    self._trial_label.setText(f"Trial ends in {days} day{'s' if days != 1 else ''}! Buy at whop.com/muravey-ai")
                    self._trial_label.setStyleSheet("color: rgba(255,100,80,0.6); background: transparent; border: none;")
                else:
                    self._trial_label.setText(f"Free until April 21, 2026  ·  {days} days left")
                    self._trial_label.setStyleSheet("color: rgba(255,255,255,0.25); background: transparent; border: none;")
        except Exception:
            pass
        # Fade out after 3 seconds (5 if warning)
        try:
            delay = 5000 if days <= 3 else 3000
        except Exception:
            delay = 3000
        self._QTimer.singleShot(delay, self._fade_out)

    def _fade_out(self) -> None:
        self._anim = self._QPropertyAnimation(self._opacity, b"opacity")
        self._anim.setDuration(600)
        self._anim.setStartValue(1.0)
        self._anim.setEndValue(0.0)
        self._anim.setEasingCurve(self._QEasingCurve.Type.InOutQuad)
        self._anim.finished.connect(self._do_close)
        self._anim.start()

    def _do_close(self) -> None:
        try:
            self._win.close()
            self._win.deleteLater()
        except Exception:
            pass

    def close(self) -> None:
        """Force close from any thread."""
        self.close_signal.emit()
