"""Cross-platform purchase panel for MuraveyChina.

Opens the /buy page in an embedded web view or falls back to the system browser.

- macOS: WKWebView inside NSPanel
- Windows: QWebEngineView inside QDialog
- Fallback: webbrowser.open()
"""

from __future__ import annotations

import logging
import sys
import webbrowser

PURCHASE_PAGE_URL = "https://whop.com/checkout/plan_YFqvqKJproMsR"
_THANK_YOU_PATH = "/thank-you"

logger = logging.getLogger(__name__)


class PurchasePanel:
    """Cross-platform payment panel.

    Usage:
        panel = PurchasePanel()
        paid = panel.show_and_wait()  # blocks until paid or dismissed
    """

    def show_and_wait(self) -> bool:
        """Show payment panel; block until paid or dismissed.

        Returns True if payment was completed (/thank-you detected).
        Returns False if the user closed the panel without paying.
        """
        try:
            if sys.platform == "darwin":
                return self._show_macos()
            elif sys.platform == "win32":
                return self._show_windows()
        except Exception:
            logger.exception("Embedded payment panel failed — falling back to browser")

        webbrowser.open(PURCHASE_PAGE_URL)
        return False

    def _show_macos(self) -> bool:
        import AppKit
        from Foundation import NSURL, NSURLRequest
        from WebKit import WKWebView, WKWebViewConfiguration

        result = [False]

        class _NavigationDelegate(AppKit.NSObject):
            def webView_didFinishNavigation_(self, webview, navigation):
                url = str(webview.URL().absoluteString())
                if _THANK_YOU_PATH in url:
                    logger.info("Payment completed — /thank-you detected")
                    result[0] = True
                    AppKit.NSApp.stopModal()

        class _WindowDelegate(AppKit.NSObject):
            def windowWillClose_(self, notification):
                AppKit.NSApp.stopModal()

        nav_delegate = _NavigationDelegate.alloc().init()
        win_delegate = _WindowDelegate.alloc().init()

        WIDTH, HEIGHT = 620, 740
        screen_frame = AppKit.NSScreen.mainScreen().frame()
        x = (screen_frame.size.width - WIDTH) / 2
        y = (screen_frame.size.height - HEIGHT) / 2
        frame = AppKit.NSMakeRect(x, y, WIDTH, HEIGHT)

        style = (1 << 0) | (1 << 1) | (1 << 7)  # Titled | Closable | NonActivating
        panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(
            frame, style, AppKit.NSBackingStoreBuffered, False
        )
        panel.setTitle_("MuraveyChina — 购买")
        panel.setLevel_(AppKit.NSFloatingWindowLevel)
        panel.setHidesOnDeactivate_(False)
        panel.setReleasedWhenClosed_(False)
        panel.setDelegate_(win_delegate)

        content_frame = AppKit.NSMakeRect(0, 0, WIDTH, HEIGHT)
        config = WKWebViewConfiguration.alloc().init()
        webview = WKWebView.alloc().initWithFrame_configuration_(content_frame, config)
        webview.setNavigationDelegate_(nav_delegate)

        url = NSURL.URLWithString_(PURCHASE_PAGE_URL)
        request = NSURLRequest.requestWithURL_(url)
        webview.loadRequest_(request)

        panel.setContentView_(webview)
        panel.center()

        AppKit.NSApp.activateIgnoringOtherApps_(True)
        panel.makeKeyAndOrderFront_(None)
        AppKit.NSApp.runModalForWindow_(panel)
        panel.orderOut_(None)

        return result[0]

    def _show_windows(self) -> bool:
        from PyQt6.QtCore import QUrl
        from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile
        from PyQt6.QtWebEngineWidgets import QWebEngineView
        from PyQt6.QtWidgets import QApplication, QDialog, QVBoxLayout

        app = QApplication.instance() or QApplication(sys.argv)

        class _PaymentPage(QWebEnginePage):
            def __init__(self, dialog, profile):
                super().__init__(profile, dialog)
                self._dialog = dialog

            def acceptNavigationRequest(self, url, nav_type, is_main_frame):
                if is_main_frame and _THANK_YOU_PATH in url.path():
                    logger.info("Payment completed — closing panel")
                    self._dialog._completed = True
                    self._dialog.accept()
                return True

        dialog = QDialog()
        dialog.setWindowTitle("MuraveyChina — 购买")
        dialog.resize(620, 740)
        dialog._completed = False

        if screen := app.primaryScreen():
            geo = screen.availableGeometry()
            dialog.move(
                geo.center().x() - dialog.width() // 2,
                geo.center().y() - dialog.height() // 2,
            )

        layout = QVBoxLayout(dialog)
        layout.setContentsMargins(0, 0, 0, 0)

        profile = QWebEngineProfile("muraveychina_payment", dialog)
        view = QWebEngineView(dialog)
        page = _PaymentPage(dialog, profile)
        view.setPage(page)
        view.load(QUrl(PURCHASE_PAGE_URL))
        layout.addWidget(view)

        dialog.exec()
        return bool(dialog._completed)
