"""
support_payment_module.py — Các trang Hỗ trợ, Hướng dẫn, Gói số và Phản hồi.
"""
import os
import re
from datetime import date

from PySide6.QtCore import Qt, QTimer, QUrl
from PySide6.QtGui import QDesktopServices, QFont, QPixmap
from PySide6.QtWidgets import (
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QFrame,
    QTabWidget,
    QGridLayout,
    QTextEdit,
    QPushButton,
    QMessageBox,
    QApplication,
    QScrollArea,
)

from gui.theme import COLORS
from gui.ui_helpers import show_toast
from core.licensing import get_machine_id, send_feedback_to_server
from core.utils import (
    CONTRACT_DOWNLOAD_URL,
    CONTRACT_GUIDE_FILENAME,
    get_contract_guide_path,
    get_resource_path,
)


_ASSETS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets")
_QR_IMAGE = os.path.join(_ASSETS, "payment_qr_vpbank.png")
_PRICE_FILE = get_resource_path("bang_gia.md")
_PRICING_WEB_URL = "https://phanmemhopdong.ini.vn/p/bang-gia.html"
_PROMO_START = date(2026, 5, 1)
_PROMO_END = date(2026, 12, 31)
_SUPPORT_PHONE_DISPLAY = "0988.341.387"
_PROMO_TEXT = (
    "Khuyến mãi 01/05/2026 - 31/12/2026: giảm 50% giá tháng. "
    "Starter còn 49.000đ/tháng, Pro còn 99.000đ/tháng, Office còn 199.000đ/tháng."
)


class PromoTicker(QFrame):
    """Dòng thông báo khuyến mãi chạy ngang trong tab bảng giá."""

    def __init__(self, text: str, parent=None):
        super().__init__(parent)
        self.setMinimumHeight(48)
        self.setStyleSheet(
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #1d4ed8, stop:1 #2563eb); "
            "border: 1px solid #1e40af; border-radius: 12px;"
        )

        self._label = QLabel(f"   {text}   ", self)
        self._label.setFont(QFont("Segoe UI", 10, QFont.Weight.Bold))
        self._label.setStyleSheet("color: white; background: transparent;")
        self._label.adjustSize()
        self._initialized = False

        self._timer = QTimer(self)
        self._timer.setInterval(20)
        self._timer.timeout.connect(self._tick)
        self._timer.start()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._label.adjustSize()
        y_pos = max(0, (self.height() - self._label.height()) // 2)
        if not self._initialized:
            self._label.move(self.width(), y_pos)
            self._initialized = True
        else:
            self._label.move(self._label.x(), y_pos)

    def _tick(self):
        if self.width() <= 0:
            return

        self._label.adjustSize()
        y_pos = max(0, (self.height() - self._label.height()) // 2)
        next_x = self._label.x() - 2
        if next_x + self._label.width() < 0:
            next_x = self.width()
        self._label.move(next_x, y_pos)


def _get_active_promo_text() -> str:
    today = date.today()
    if _PROMO_START <= today <= _PROMO_END:
        return _PROMO_TEXT
    return ""


def _make_key_label(text: str) -> QLabel:
    label = QLabel(text)
    label.setFont(QFont("Segoe UI", 10, QFont.Weight.Bold))
    label.setStyleSheet("background: transparent;")
    return label


def _make_value_label(text: str) -> QLabel:
    label = QLabel(text)
    label.setFont(QFont("Segoe UI", 10))
    label.setStyleSheet(f"color: {COLORS['text_primary']}; background: transparent;")
    return label


def _info_row(label_text: str, value_text: str):
    row = QHBoxLayout()
    row.setSpacing(8)

    key_lbl = _make_key_label(label_text)
    value_lbl = _make_value_label(value_text)
    value_lbl.setWordWrap(True)

    row.addWidget(key_lbl)
    row.addWidget(value_lbl, 1)
    return row


def _build_payment_panel() -> QWidget:
    scroll = QScrollArea()
    scroll.setWidgetResizable(True)
    scroll.setFrameShape(QFrame.Shape.NoFrame)

    wrapper = QWidget()
    wrapper.setMinimumWidth(920)
    outer = QGridLayout(wrapper)
    outer.setContentsMargins(0, 10, 0, 0)
    outer.setHorizontalSpacing(16)
    outer.setVerticalSpacing(16)
    outer.setColumnStretch(0, 3)
    outer.setColumnStretch(1, 2)

    payment_card = QFrame()
    payment_card.setObjectName("card")
    payment_layout = QGridLayout(payment_card)
    payment_layout.setContentsMargins(24, 22, 24, 22)
    payment_layout.setHorizontalSpacing(20)
    payment_layout.setVerticalSpacing(10)
    payment_layout.setColumnStretch(1, 1)

    heading = QLabel("Thông tin thanh toán")
    heading.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
    heading.setStyleSheet("background: transparent;")
    payment_layout.addWidget(heading, 0, 0, 1, 2)

    payment_layout.addWidget(_make_key_label("Ngân hàng:"), 1, 0)
    payment_layout.addWidget(_make_value_label("VPBank"), 1, 1)

    payment_layout.addWidget(_make_key_label("Số tài khoản:"), 2, 0)
    payment_layout.addWidget(_make_value_label("0972729060"), 2, 1)

    payment_layout.addWidget(_make_key_label("Tên tài khoản:"), 3, 0)
    payment_layout.addWidget(_make_value_label("NGUYEN XUAN THAO"), 3, 1)

    payment_layout.addWidget(_make_key_label("Chuẩn QR:"), 4, 0)
    payment_layout.addWidget(_make_value_label("VietQR / Napas 247"), 4, 1)

    note = QLabel("Quét mã QR bên dưới hoặc chuyển khoản theo đúng thông tin tài khoản hiển thị ở trên.")
    note.setWordWrap(True)
    note.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")
    payment_layout.addWidget(note, 5, 0, 1, 2)

    outer.addWidget(payment_card, 0, 0)

    qr_card = QFrame()
    qr_card.setObjectName("card")
    qr_layout = QVBoxLayout(qr_card)
    qr_layout.setContentsMargins(18, 18, 18, 18)
    qr_layout.setSpacing(10)

    qr_title = QLabel("Mã QR thanh toán")
    qr_title.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
    qr_title.setAlignment(Qt.AlignmentFlag.AlignCenter)
    qr_title.setStyleSheet("background: transparent;")

    qr_scroll = QScrollArea()
    qr_scroll.setWidgetResizable(True)
    qr_scroll.setFrameShape(QFrame.Shape.NoFrame)
    qr_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
    qr_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
    qr_scroll.setMinimumHeight(360)

    qr_holder = QWidget()
    qr_holder_layout = QVBoxLayout(qr_holder)
    qr_holder_layout.setContentsMargins(0, 0, 0, 0)

    qr_image = QLabel()
    qr_image.setAlignment(Qt.AlignmentFlag.AlignCenter)
    qr_image.setStyleSheet("background: transparent; border: none;")
    qr_image.setMinimumSize(300, 300)

    if os.path.exists(_QR_IMAGE):
        pixmap = QPixmap(_QR_IMAGE)
        qr_image.setPixmap(
            pixmap.scaled(
                300,
                300,
                Qt.AspectRatioMode.KeepAspectRatio,
                Qt.TransformationMode.SmoothTransformation,
            )
        )
    else:
        qr_image.setText("Không tìm thấy hình mã QR thanh toán.")
        qr_image.setStyleSheet(f"color: {COLORS['danger']}; background: transparent; border: none;")

    qr_holder_layout.addWidget(qr_image, alignment=Qt.AlignmentFlag.AlignCenter)
    qr_scroll.setWidget(qr_holder)

    qr_hint = QLabel("Ảnh QR đã được lưu kèm phần mềm để có thể mở ngay trong tab này.")
    qr_hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
    qr_hint.setWordWrap(True)
    qr_hint.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

    qr_layout.addWidget(qr_title)
    qr_layout.addWidget(qr_scroll, 1)
    qr_layout.addWidget(qr_hint)

    outer.addWidget(qr_card, 0, 1)
    outer.setRowStretch(1, 1)

    scroll.setWidget(wrapper)
    return scroll


class SupportPage(QWidget):
    """Trang hiển thị thông tin hỗ trợ kỹ thuật."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("content_area")

        root = QVBoxLayout(self)
        root.setContentsMargins(18, 18, 18, 18)
        root.setSpacing(16)

        hero = QFrame()
        hero.setObjectName("card")
        hero_layout = QVBoxLayout(hero)
        hero_layout.setContentsMargins(22, 20, 22, 20)
        hero_layout.setSpacing(6)

        title = QLabel("Hỗ trợ kỹ thuật")
        title.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel(
            "Liên hệ hỗ trợ nhanh qua điện thoại hoặc Zalo để được xử lý cài đặt, kích hoạt và lỗi vận hành."
        )
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        hero_layout.addWidget(title)
        hero_layout.addWidget(subtitle)
        root.addWidget(hero)

        support_card = QFrame()
        support_card.setObjectName("card")
        support_layout = QVBoxLayout(support_card)
        support_layout.setContentsMargins(24, 22, 24, 22)
        support_layout.setSpacing(10)

        heading = QLabel("Thông tin hỗ trợ")
        heading.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        heading.setStyleSheet("background: transparent;")

        support_layout.addWidget(heading)
        support_layout.addLayout(_info_row("Số điện thoại:", _SUPPORT_PHONE_DISPLAY))
        support_layout.addLayout(_info_row("Zalo:", _SUPPORT_PHONE_DISPLAY))
        support_layout.addLayout(_info_row("Nội dung hỗ trợ:", "Cài đặt phần mềm, kích hoạt bản quyền, xử lý lỗi và hỗ trợ sử dụng."))

        note = QLabel("Khi cần hỗ trợ, vui lòng nhắn Zalo hoặc gọi trực tiếp để được xử lý nhanh.")
        note.setWordWrap(True)
        note.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")
        support_layout.addWidget(note)

        root.addWidget(support_card)
        root.addStretch()


class GuidePage(QWidget):
    """Trang mở nhanh tài liệu hướng dẫn đi kèm phần mềm."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("content_area")
        self._guide_path = ""

        root = QVBoxLayout(self)
        root.setContentsMargins(18, 18, 18, 18)
        root.setSpacing(16)

        hero = QFrame()
        hero.setObjectName("card")
        hero_layout = QVBoxLayout(hero)
        hero_layout.setContentsMargins(22, 20, 22, 20)
        hero_layout.setSpacing(6)

        title = QLabel("Hướng dẫn sử dụng")
        title.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel(
            "Mở file hướng dẫn cục bộ đi kèm phần mềm hoặc mở trực tiếp link tải bộ cài mới nhất."
        )
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        hero_layout.addWidget(title)
        hero_layout.addWidget(subtitle)
        root.addWidget(hero)

        guide_card = QFrame()
        guide_card.setObjectName("card")
        guide_layout = QVBoxLayout(guide_card)
        guide_layout.setContentsMargins(22, 20, 22, 20)
        guide_layout.setSpacing(12)

        guide_steps = QLabel(
            f"<b>Link tải phần mềm:</b> <a href='{CONTRACT_DOWNLOAD_URL}'>{CONTRACT_DOWNLOAD_URL}</a><br/><br/>"
            "1. Tải file ZIP về máy và giải nén vào một thư mục riêng.<br/>"
            "2. Mở file <b>Hợp Đồng INI.exe</b> trong thư mục vừa giải nén.<br/>"
            "3. Nếu Windows hiển thị SmartScreen, chọn <b>More info</b> rồi <b>Run anyway</b>.<br/>"
            f"4. Giữ file <b>{CONTRACT_GUIDE_FILENAME}</b> cùng thư mục với EXE để có thể mở lại hướng dẫn bất cứ lúc nào.<br/>"
            "5. File hướng dẫn này đã bao gồm quy trình tạo hợp đồng, quản lý mẫu Word, sản phẩm và xử lý link Google."
        )
        guide_steps.setOpenExternalLinks(True)
        guide_steps.setWordWrap(True)
        guide_steps.setTextFormat(Qt.TextFormat.RichText)
        guide_steps.setStyleSheet(f"color: {COLORS['text_primary']}; background: transparent;")

        self.lbl_guide_path = QLabel()
        self.lbl_guide_path.setWordWrap(True)
        self.lbl_guide_path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        self.lbl_guide_path.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        btn_row = QHBoxLayout()
        btn_row.setSpacing(10)

        self.btn_open_guide = QPushButton(f"Mở {CONTRACT_GUIDE_FILENAME}")
        self.btn_open_guide.setStyleSheet(
            "background: #2563eb; color: white; font-weight: bold; border-radius: 8px; padding: 10px 16px;"
        )
        self.btn_open_guide.clicked.connect(self._open_local_guide)

        btn_open_download = QPushButton("Mở link tải phần mềm")
        btn_open_download.setStyleSheet(
            "background: white; color: #0f172a; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px 16px;"
        )
        btn_open_download.clicked.connect(self._open_download_link)

        btn_row.addWidget(self.btn_open_guide)
        btn_row.addWidget(btn_open_download)
        btn_row.addStretch()

        guide_layout.addWidget(guide_steps)
        guide_layout.addWidget(self.lbl_guide_path)
        guide_layout.addLayout(btn_row)

        root.addWidget(guide_card)
        root.addStretch()

        self._refresh_guide_status()

    def showEvent(self, event):
        self._refresh_guide_status()
        super().showEvent(event)

    def _refresh_guide_status(self):
        guide_path = get_contract_guide_path()
        self._guide_path = guide_path if os.path.exists(guide_path) else ""
        if self._guide_path:
            self.lbl_guide_path.setText(f"File hướng dẫn cục bộ: {self._guide_path}")
            self.lbl_guide_path.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")
            self.btn_open_guide.setEnabled(True)
            return

        self.lbl_guide_path.setText(
            f"Không tìm thấy file hướng dẫn cục bộ {CONTRACT_GUIDE_FILENAME}. Hãy build lại bộ cài hoặc mở link tải trực tiếp."
        )
        self.lbl_guide_path.setStyleSheet(f"color: {COLORS['danger']}; background: transparent;")
        self.btn_open_guide.setEnabled(False)

    def _open_local_guide(self):
        self._refresh_guide_status()
        if not self._guide_path:
            QMessageBox.warning(self, "Hướng dẫn", f"Không tìm thấy file {CONTRACT_GUIDE_FILENAME}.")
            return
        if not QDesktopServices.openUrl(QUrl.fromLocalFile(self._guide_path)):
            QMessageBox.warning(self, "Hướng dẫn", f"Không thể mở file {CONTRACT_GUIDE_FILENAME}.")

    def _open_download_link(self):
        if not QDesktopServices.openUrl(QUrl(CONTRACT_DOWNLOAD_URL)):
            QMessageBox.warning(self, "Hướng dẫn", "Không thể mở link tải phần mềm.")


class PackagesPage(QWidget):
    """Trang Gói số — dẫn người dùng đến bảng giá trên website."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("content_area")

        root = QVBoxLayout(self)
        root.setContentsMargins(18, 18, 18, 18)
        root.setSpacing(16)

        hero = QFrame()
        hero.setObjectName("card")
        hero_layout = QVBoxLayout(hero)
        hero_layout.setContentsMargins(22, 20, 22, 20)
        hero_layout.setSpacing(6)

        title = QLabel("Gói số")
        title.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel("Bảng giá và thanh toán đã được chuyển sang website để người dùng tham khảo trực tiếp trên web.")
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        hero_layout.addWidget(title)
        hero_layout.addWidget(subtitle)
        root.addWidget(hero)

        root.addWidget(self._build_pricing_link_card())
        root.addStretch()

    def _build_pricing_link_card(self) -> QWidget:
        card = QFrame()
        card.setObjectName("card")

        layout = QVBoxLayout(card)
        layout.setContentsMargins(22, 20, 22, 20)
        layout.setSpacing(12)

        heading = QLabel("Bảng giá được cập nhật trực tiếp trên website")
        heading.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        heading.setStyleSheet("background: transparent;")

        url_label = QLabel(f"<a href=\"{_PRICING_WEB_URL}\">{_PRICING_WEB_URL}</a>")
        url_label.setOpenExternalLinks(True)
        url_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        url_label.setStyleSheet(f"color: {COLORS['accent']}; background: transparent; font-weight: 600;")

        action_button = QPushButton("Mở bảng giá trên website")
        action_button.setFixedHeight(40)
        action_button.setObjectName("btn_success")
        action_button.clicked.connect(self._open_pricing_website)

        layout.addWidget(heading)
        layout.addWidget(url_label)
        layout.addWidget(action_button, alignment=Qt.AlignmentFlag.AlignLeft)
        return card

    def _open_pricing_website(self):
        QDesktopServices.openUrl(QUrl(_PRICING_WEB_URL))

    def _build_pricing_tab(self) -> QWidget:
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.Shape.NoFrame)

        page = QWidget()
        page.setMinimumWidth(1220)
        outer = QVBoxLayout(page)
        outer.setContentsMargins(0, 10, 0, 0)
        outer.setSpacing(16)

        if self.pricing_data.get("error"):
            error_card = QFrame()
            error_card.setObjectName("card")
            error_layout = QVBoxLayout(error_card)
            error_layout.setContentsMargins(18, 18, 18, 18)

            error_label = QLabel(self.pricing_data["error"])
            error_label.setWordWrap(True)
            error_label.setStyleSheet(f"color: {COLORS['danger']}; background: transparent;")
            error_layout.addWidget(error_label)

            outer.addWidget(error_card)
            outer.addStretch()
            scroll.setWidget(page)
            return scroll

        promo_text = _get_active_promo_text()
        if promo_text:
            outer.addWidget(PromoTicker(promo_text))

        outer.addWidget(self._build_comparison_card())
        outer.addWidget(self._build_package_columns_card())

        if self.pricing_data.get("addons"):
            outer.addWidget(self._build_addon_card())

        outer.addStretch()
        scroll.setWidget(page)
        return scroll

    def _load_pricing_data(self) -> dict:
        try:
            with open(_PRICE_FILE, "r", encoding="utf-8") as file_obj:
                return self._parse_pricing_markdown(file_obj.read())
        except Exception as exc:
            return {
                "packages": [],
                "comparison_rows": [],
                "addons": [],
                "error": f"Không thể tải bảng giá: {exc}",
            }

    def _parse_pricing_markdown(self, markdown_text: str) -> dict:
        packages = []
        addons = []
        lines = markdown_text.splitlines()
        index = 0

        while index < len(lines):
            stripped = lines[index].strip()

            if stripped.startswith("### "):
                package, index = self._parse_package_block(lines, index)
                if package:
                    packages.append(package)
                continue

            if stripped.startswith("## Add-on"):
                index += 1
                while index < len(lines) and not lines[index].strip().startswith("|"):
                    index += 1
                _, addon_rows, index = self._parse_markdown_table(lines, index)
                addons = addon_rows
                continue

            index += 1

        return {
            "packages": packages,
            "comparison_rows": self._build_comparison_rows(packages),
            "addons": addons,
            "error": "",
        }

    def _parse_package_block(self, lines, start_index):
        raw_title = self._clean_markdown_text(lines[start_index].strip()[4:])
        package_name, package_tagline = self._split_package_heading(raw_title)
        index = start_index + 1

        while index < len(lines) and not lines[index].strip():
            index += 1

        _, detail_rows, index = self._parse_markdown_table(lines, index)
        details = []
        detail_map = {}
        for row in detail_rows:
            if len(row) < 2:
                continue
            key = row[0]
            value = row[1]
            if key.lower() == "giá launch":
                continue
            details.append((key, value))
            detail_map[key] = value

        sections = []
        while index < len(lines):
            stripped = lines[index].strip()

            if not stripped:
                index += 1
                continue

            if stripped == "---":
                next_line = self._peek_next_non_empty(lines, index + 1)
                if next_line.startswith("### ") or next_line.startswith("## "):
                    index += 1
                    break
                index += 1
                continue

            if stripped.startswith("### ") or stripped.startswith("## "):
                break

            section_match = re.match(r"^\*\*(.+?)\*\*:?(.*)$", stripped)
            if not section_match:
                index += 1
                continue

            section_title = self._normalize_section_title(section_match.group(1))
            first_item = self._clean_markdown_text(section_match.group(2))
            items = [first_item] if first_item else []
            index += 1

            while index < len(lines):
                current = lines[index].strip()
                if not current:
                    index += 1
                    if items:
                        break
                    continue
                if current == "---":
                    break
                if current.startswith("### ") or current.startswith("## "):
                    break
                if re.match(r"^\*\*(.+?)\*\*:?(.*)$", current):
                    break
                if current.startswith("- "):
                    items.append(self._clean_markdown_text(current[2:]))
                else:
                    items.append(self._clean_markdown_text(current))
                index += 1

            if section_title and items:
                sections.append({"title": section_title, "items": items})

        return {
            "name": package_name,
            "tagline": package_tagline,
            "details": details,
            "detail_map": detail_map,
            "sections": sections,
        }, index

    def _parse_markdown_table(self, lines, start_index):
        table_lines = []
        index = start_index
        while index < len(lines) and lines[index].strip().startswith("|"):
            table_lines.append(lines[index].strip())
            index += 1

        if len(table_lines) < 2:
            return [], [], start_index

        headers = [self._clean_markdown_text(part) for part in table_lines[0].strip("|").split("|")]
        rows = []
        for raw_line in table_lines[2:]:
            row = [self._clean_markdown_text(part) for part in raw_line.strip("|").split("|")]
            if len(row) < len(headers):
                row.extend([""] * (len(headers) - len(row)))
            rows.append(row[: len(headers)])
        return headers, rows, index

    def _build_comparison_rows(self, packages):
        rows = []
        comparisons = [
            ("Giá", ("Giá", "Giá tháng")),
            ("Giá năm", ("Giá năm",)),
            ("Đối tượng", ("Đối tượng",)),
            ("Hợp đồng tối đa", ("Hợp đồng tối đa",)),
            ("MST / đơn vị", ("MST tối đa",)),
            ("Mẫu HĐ", ("Mẫu HĐ",)),
            ("Thiết bị", ("Thiết bị",)),
        ]

        for label, keys in comparisons:
            values = [self._pick_detail_value(package.get("detail_map", {}), keys) for package in packages]
            if any(value != "-" for value in values):
                rows.append((label, values))
        return rows

    def _build_comparison_card(self) -> QWidget:
        card = QFrame()
        card.setObjectName("card")
        layout = QVBoxLayout(card)
        layout.setContentsMargins(18, 18, 18, 18)
        layout.setSpacing(14)

        title = QLabel("So sánh nhanh")
        title.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel("Các chỉ tiêu quan trọng được đặt cùng hàng để người dùng dễ so sánh giữa các gói.")
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        grid = QGridLayout()
        grid.setHorizontalSpacing(10)
        grid.setVerticalSpacing(10)
        grid.setColumnStretch(0, 2)

        packages = self.pricing_data.get("packages", [])
        for column, package in enumerate(packages, start=1):
            grid.setColumnStretch(column, 2)
            grid.addWidget(
                self._make_matrix_cell(package.get("name", ""), header=True),
                0,
                column,
            )

        grid.addWidget(self._make_matrix_cell("Hạng mục", header=True, align=Qt.AlignmentFlag.AlignLeft), 0, 0)

        for row_index, (label, values) in enumerate(self.pricing_data.get("comparison_rows", []), start=1):
            grid.addWidget(self._make_matrix_cell(label, label_cell=True, align=Qt.AlignmentFlag.AlignLeft), row_index, 0)
            for column, value in enumerate(values, start=1):
                grid.addWidget(self._make_matrix_cell(value), row_index, column)

        layout.addWidget(title)
        layout.addWidget(subtitle)
        layout.addLayout(grid)
        return card

    def _build_package_columns_card(self) -> QWidget:
        card = QFrame()
        card.setObjectName("card")
        layout = QVBoxLayout(card)
        layout.setContentsMargins(18, 18, 18, 18)
        layout.setSpacing(14)

        title = QLabel("Chi tiết từng gói")
        title.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel("Mỗi gói được đặt thành một cột riêng để xem song song toàn bộ nội dung chi tiết.")
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        columns = QGridLayout()
        columns.setHorizontalSpacing(12)
        columns.setVerticalSpacing(12)

        for column, package in enumerate(self.pricing_data.get("packages", [])):
            columns.setColumnStretch(column, 1)
            columns.addWidget(self._build_package_card(package), 0, column)

        layout.addWidget(title)
        layout.addWidget(subtitle)
        layout.addLayout(columns)
        return card

    def _build_package_card(self, package: dict) -> QWidget:
        card = QFrame()
        card.setObjectName("card")
        card.setMinimumWidth(220)

        layout = QVBoxLayout(card)
        layout.setContentsMargins(16, 16, 16, 16)
        layout.setSpacing(10)

        name_label = QLabel(package.get("name", ""))
        name_label.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        name_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        name_label.setStyleSheet("background: transparent;")

        tagline = QLabel(package.get("tagline", ""))
        tagline.setWordWrap(True)
        tagline.setAlignment(Qt.AlignmentFlag.AlignCenter)
        tagline.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        primary_price = package.get("detail_map", {}).get("Giá") or package.get("detail_map", {}).get("Giá tháng") or ""
        price_label = QLabel(primary_price)
        price_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        price_label.setStyleSheet(
            f"background: #eef4ff; color: {COLORS['accent']}; border-radius: 8px; padding: 8px 10px; font-weight: 600;"
        )

        detail_grid = QGridLayout()
        detail_grid.setHorizontalSpacing(8)
        detail_grid.setVerticalSpacing(6)
        detail_grid.setColumnStretch(1, 1)

        detail_row = 0
        for label_text, value_text in package.get("details", []):
            key_label = QLabel(label_text)
            key_label.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))
            key_label.setStyleSheet("background: transparent;")

            value_label = QLabel(value_text)
            value_label.setWordWrap(True)
            value_label.setStyleSheet(f"color: {COLORS['text_primary']}; background: transparent;")

            detail_grid.addWidget(key_label, detail_row, 0, alignment=Qt.AlignmentFlag.AlignTop)
            detail_grid.addWidget(value_label, detail_row, 1)
            detail_row += 1

        layout.addWidget(name_label)
        layout.addWidget(tagline)
        layout.addWidget(price_label)
        layout.addLayout(detail_grid)

        for section in package.get("sections", []):
            section_title = QLabel(section.get("title", ""))
            section_title.setFont(QFont("Segoe UI", 10, QFont.Weight.Bold))
            section_title.setStyleSheet("background: transparent;")
            layout.addWidget(section_title)

            for item in section.get("items", []):
                item_label = QLabel(f"- {item}")
                item_label.setWordWrap(True)
                item_label.setStyleSheet(f"color: {COLORS['text_primary']}; background: transparent;")
                layout.addWidget(item_label)

        layout.addStretch()
        return card

    def _build_addon_card(self) -> QWidget:
        card = QFrame()
        card.setObjectName("card")
        layout = QVBoxLayout(card)
        layout.setContentsMargins(18, 18, 18, 18)
        layout.setSpacing(14)

        title = QLabel("Dịch vụ bổ sung")
        title.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        description = QLabel(
            "Nội dung dịch vụ bổ sung tại mục này đã được chuyển sang tư vấn trực tiếp để phù hợp hơn với từng nhu cầu sử dụng."
        )
        description.setWordWrap(True)
        description.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        contact_box = QLabel(
            f"Vui lòng mở mục Hỗ trợ và liên hệ số điện thoại {_SUPPORT_PHONE_DISPLAY} để được tư vấn chi tiết."
        )
        contact_box.setWordWrap(True)
        contact_box.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        contact_box.setStyleSheet(
            f"background: #eef4ff; color: {COLORS['accent']}; border: 1px solid #d7e3ff; border-radius: 10px; padding: 14px; font-weight: 600;"
        )

        note = QLabel("Tab Hỗ trợ cũng hiển thị thêm Zalo và nội dung hỗ trợ để tiện liên hệ khi cần.")
        note.setWordWrap(True)
        note.setStyleSheet(f"color: {COLORS['text_primary']}; background: transparent;")

        layout.addWidget(title)
        layout.addWidget(description)
        layout.addWidget(contact_box)
        layout.addWidget(note)
        return card

    def _make_matrix_cell(self, text: str, header: bool = False, label_cell: bool = False, align=Qt.AlignmentFlag.AlignCenter) -> QLabel:
        label = QLabel(text or "-")
        label.setWordWrap(True)
        label.setAlignment(align | Qt.AlignmentFlag.AlignVCenter)

        font_weight = QFont.Weight.Bold if (header or label_cell) else QFont.Weight.Normal
        label.setFont(QFont("Segoe UI", 9, font_weight))

        if header:
            label.setStyleSheet(
                f"background: #eef4ff; color: {COLORS['accent']}; border: 1px solid #d7e3ff; border-radius: 8px; padding: 10px;"
            )
        else:
            label.setStyleSheet(
                f"background: white; color: {COLORS['text_primary']}; border: 1px solid #e5e7eb; border-radius: 8px; padding: 10px;"
            )
        return label

    def _pick_detail_value(self, detail_map: dict, keys) -> str:
        for key in keys:
            if detail_map.get(key):
                return detail_map[key]
        return "-"

    def _peek_next_non_empty(self, lines, start_index) -> str:
        index = start_index
        while index < len(lines):
            candidate = lines[index].strip()
            if candidate:
                return candidate
            index += 1
        return ""

    def _split_package_heading(self, raw_title: str):
        cleaned_title = re.sub(r"^[^A-Za-z0-9À-ỹ]+", "", raw_title).strip()
        if cleaned_title.lower().startswith("gói "):
            cleaned_title = cleaned_title[4:].strip()
        if "—" in cleaned_title:
            name, subtitle = cleaned_title.split("—", 1)
            return name.strip(), subtitle.strip()
        return cleaned_title, ""

    def _normalize_section_title(self, raw_title: str):
        cleaned_title = self._clean_markdown_text(raw_title).rstrip(":")
        normalized = cleaned_title.casefold()
        if normalized == "mục tiêu":
            return ""
        if normalized.startswith("bao gồm"):
            return "Điểm nổi bật"
        if normalized == "lý do chọn":
            return "Phù hợp khi"
        return cleaned_title

    def _clean_markdown_text(self, text: str) -> str:
        cleaned = text.strip()
        cleaned = cleaned.replace("**", "").replace("`", "")
        return cleaned.strip()


class FeedbackPage(QWidget):
    """Trang gửi phản hồi từ ứng dụng lên server."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("content_area")

        root = QVBoxLayout(self)
        root.setContentsMargins(18, 18, 18, 18)
        root.setSpacing(16)

        hero = QFrame()
        hero.setObjectName("card")
        hero_layout = QVBoxLayout(hero)
        hero_layout.setContentsMargins(22, 20, 22, 20)
        hero_layout.setSpacing(6)

        title = QLabel("Phản hồi")
        title.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        title.setStyleSheet("background: transparent;")

        subtitle = QLabel("Gửi góp ý, yêu cầu tính năng hoặc lỗi vận hành trực tiếp lên server hỗ trợ.")
        subtitle.setWordWrap(True)
        subtitle.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent;")

        hero_layout.addWidget(title)
        hero_layout.addWidget(subtitle)
        root.addWidget(hero)

        form_card = QFrame()
        form_card.setObjectName("card")
        form_layout = QVBoxLayout(form_card)
        form_layout.setContentsMargins(22, 20, 22, 20)
        form_layout.setSpacing(12)

        lbl = QLabel("Nội dung phản hồi")
        lbl.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        lbl.setStyleSheet("background: transparent;")

        self.txt_feedback = QTextEdit()
        self.txt_feedback.setPlaceholderText("Nhập nội dung phản hồi, lỗi gặp phải hoặc đề xuất tính năng...")
        self.txt_feedback.setMinimumHeight(220)

        self.btn_send = QPushButton("Gửi phản hồi")
        self.btn_send.setFixedHeight(40)
        self.btn_send.setObjectName("btn_success")
        self.btn_send.clicked.connect(self._on_send_feedback)

        form_layout.addWidget(lbl)
        form_layout.addWidget(self.txt_feedback)
        form_layout.addWidget(self.btn_send, alignment=Qt.AlignmentFlag.AlignRight)

        root.addWidget(form_card)
        root.addStretch()

    def _on_send_feedback(self):
        content = self.txt_feedback.toPlainText().strip()
        if not content:
            QMessageBox.warning(self, "Phản hồi", "Vui lòng nhập nội dung phản hồi trước khi gửi.")
            return

        main = self.window()
        company_info = getattr(main, "company_info", {}) if hasattr(main, "company_info") else {}
        tax_id = (company_info.get("tax_id") or "").strip() if isinstance(company_info, dict) else ""
        license_key = getattr(main, "license_key", "") if hasattr(main, "license_key") else ""
        app_version = QApplication.instance().applicationVersion() if QApplication.instance() else ""

        self.btn_send.setEnabled(False)
        try:
            result = send_feedback_to_server(
                content=content,
                tax_id=tax_id,
                machine_id=get_machine_id(),
                company_info=company_info,
                app_version=app_version,
                license_key=license_key,
            )
        finally:
            self.btn_send.setEnabled(True)

        if result.get("success"):
            self.txt_feedback.clear()
            show_toast(self.window(), result.get("message") or "Đã gửi phản hồi thành công.")
            QMessageBox.information(self, "Phản hồi", result.get("message") or "Đã gửi phản hồi lên server thành công.")
            return

        QMessageBox.warning(self, "Phản hồi", result.get("message") or "Không thể gửi phản hồi lên server.")
