# -*- coding: utf-8 -*-
"""
LVT About Dialog — with Terms of Use tab.

Author: Loc Vu Trung (LVT) / Slow Forest
License: GPL-3.0
"""

import os
import configparser

from qgis.PyQt.QtCore import Qt
from ..shared.qt_compat import QtCompat
from qgis.PyQt.QtGui import QFont
from qgis.PyQt.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel,
    QComboBox, QPushButton, QGroupBox, QFormLayout,
    QTabWidget, QWidget, QTextEdit,
)

from ..shared.i18n import tr, current_language, set_language


def _build_terms_html(version=''):
    v = version or '?'
    return (
        "<style>"
        "body{font-family:Arial,sans-serif;font-size:12.5px;color:#212121}"
        "h2{color:#1B5E20;font-size:15px;margin:6px 0 4px 0}"
        "h3{color:#0D47A1;font-size:13px;margin:14px 0 4px 0;"
        "border-bottom:1px solid #BBDEFB;padding-bottom:3px}"
        ".vi{border-left:4px solid #1B5E20;padding:4px 8px;margin:4px 0;"
        "background:#F1F8E9;border-radius:0 4px 4px 0}"
        ".en{border-left:4px solid #0D47A1;padding:4px 8px;margin:4px 0;"
        "background:#E3F2FD;border-radius:0 4px 4px 0}"
        ".warn{background:#FFF3E0;border:1px solid #FF6F00;"
        "padding:8px;border-radius:4px;margin:10px 0}"
        ".stop{background:#FFEBEE;border:1px solid #C62828;"
        "padding:8px;border-radius:4px;margin:10px 0}"
        ".ok{background:#E8F5E9;border:1px solid #2E7D32;"
        "padding:8px;border-radius:4px;margin:10px 0}"
        "table{border-collapse:collapse;width:100%;font-size:11.5px;margin:6px 0}"
        "th{background:#1B5E20;color:white;padding:5px 8px;text-align:left}"
        "td{border:1px solid #C8E6C9;padding:4px 8px;vertical-align:top}"
        "tr:nth-child(even) td{background:#F9FBE7}"
        "ul{margin:3px 0;padding-left:18px}"
        "li{margin:2px 0}"
        "</style>"
        f"<h2>&#127807; LVT4U v{v} &mdash; &#272;i&#7873;u kho&#7843;n / Terms of Use</h2>"

        "<h3>1. &#128218; M&#7909;c &#273;&#237;ch phi th&#432;&#417;ng m&#7841;i / Non-Commercial Purpose Only</h3>"
        "<div class='stop'>&#128683; <b>QUAN TR&#7885;NG / IMPORTANT</b><br>"
        "<b>VI:</b> Plugin d&agrave;nh cho <b style='color:#C62828'>H&#7885;C T&#7852;P, TRAO &#272;&#7892;I KINH NGHI&#7878;M PHI TH&#431;&#416;NG M&#7840;I</b>.<br>"
        "<b>EN:</b> Plugin is for <b style='color:#C62828'>EDUCATIONAL, NON-COMMERCIAL</b> use only.</div>"
        "<div class='vi'><b>Ti&#7871;ng Vi&#7879;t:</b><ul>"
        "<li>Plugin <b>KH&Ocirc;NG</b> &#273;&#432;&#7907;c thi&#7871;t k&#7871; cho m&#7909;c &#273;&#237;ch th&#432;&#417;ng m&#7841;i.</li>"
        "<li>Kh&ocirc;ng d&ugrave;ng cho d&#7921; &aacute;n <b>thu ph&#237;, h&#7907;p &#273;&#7891;ng kinh t&#7871;, h&#7891; s&#417; ph&aacute;p l&yacute; &#273;&#7845;t &#273;ai</b>.</li>"
        "<li>T&aacute;c gi&#7843; <b>t&#7915; ch&#7889;i m&#7885;i tr&aacute;ch nhi&#7879;m</b> n&#7871;u d&ugrave;ng sai m&#7909;c &#273;&#237;ch.</li>"
        "</ul></div>"
        "<div class='en'><b>English:</b><ul>"
        "<li>Plugin is <b>NOT</b> designed for commercial purposes.</li>"
        "<li>Do not use in <b>paid projects, legal land dossiers, commercial contracts</b>.</li>"
        "<li>Author <b>disclaims all liability</b> for out-of-scope use.</li>"
        "</ul></div>"

        "<h3>2. &#128302; &#272;&#7897; ch&#237;nh x&aacute;c theo module / Per-Module Accuracy</h3>"
        "<div class='warn'>&#9888;&#65039; M&#7895;i module c&oacute; gi&#7899;i h&#7841;n ri&ecirc;ng. / Each module has its own accuracy limits.</div>"
        "<table><tr><th>Module</th><th>VI &mdash; Gi&#7899;i h&#7841;n</th><th>EN &mdash; Limits</th></tr>"
        "<tr><td><b>KML/KMZ Export</b></td><td>Ch&ecirc;nh l&#7879;ch &plusmn;0.1&ndash;3m t&ugrave;y datum NTv2</td><td>Offset &plusmn;0.1&ndash;3m depending on NTv2 datum</td></tr>"
        "<tr><td><b>KML &rarr; SHP</b></td><td>Sai l&#7879;ch &plusmn;1&ndash;5m n&#7871;u thi&#7871;u datum grid</td><td>Up to &plusmn;1&ndash;5m without datum grid</td></tr>"
        "<tr><td><b>T&#237;nh di&#7879;n t&#237;ch</b></td><td>Tham kh&#7843;o; d&ugrave;ng CRS &#273;&uacute;ng (VN-2000/UTM)</td><td>Reference; use correct CRS (VN-2000/UTM)</td></tr>"
        "<tr><td><b>Thematic Map / TT16</b></td><td>H&#7885;c t&#7853;p, tr&igrave;nh b&agrave;y. Kh&ocirc;ng thay th&#7871; b&#7843;n &#273;&#7891; ph&aacute;p l&yacute;</td><td>Educational only. Not a legal map replacement</td></tr>"
        "<tr><td><b>MBTiles / Basemap</b></td><td>B&#7843;n quy&#7873;n &#7843;nh thu&#7897;c nh&agrave; cung c&#7845;p (Google, OSM)</td><td>Imagery copyright belongs to providers (Google, OSM)</td></tr>"
        "<tr><td><b>Satellite Download</b></td><td>Tu&acirc;n theo &#273;i&#7873;u kho&#7843;n GEE/Sentinel. Ch&#7881; nghi&ecirc;n c&#7913;u</td><td>Subject to GEE/Sentinel terms. Research only</td></tr>"
        "<tr><td><b>CAD Converter / DWG</b></td><td>C&oacute; th&#7875; m&#7845;t topology, nh&atilde;n, block</td><td>May lose topology, labels, blocks</td></tr>"
        "<tr><td><b>CRS / Coord Convert</b></td><td>&plusmn;0.5&ndash;2m t&ugrave;y datum v&agrave; Helmert</td><td>&plusmn;0.5&ndash;2m depending on datum &amp; Helmert</td></tr>"
        "<tr><td><b>EUDR / FSC Export</b></td><td>Kh&ocirc;ng thay th&#7871; h&#7879; th&#7889;ng EU ch&#237;nh th&#7913;c</td><td>Not a replacement for official EU EUDR system</td></tr>"
        "<tr><td><b>Excel / GIS</b></td><td>Ph&#7909; thu&#7897;c &#273;&#7883;nh d&#7841;ng file, m&atilde; h&oacute;a k&yacute; t&#7921;</td><td>Depends on file format &amp; character encoding</td></tr>"
        "</table>"

        "<h3>3. &#127951; Cam k&#7871;t ti&ecirc;u chu&#7849;n Vi&#7879;t Nam / Commitment to Vietnamese Standards</h3>"
        "<div class='ok'>&#10003; T&aacute;c gi&#7843; lu&ocirc;n n&#7895; l&#7921;c b&aacute;m theo / Author strives to follow:</div>"
        "<div class='vi'><ul>"
        "<li><b>BTNMT</b> &mdash; Quy chu&#7849;n k&#7929; thu&#7853;t &#273;o &#273;&#7841;c, b&#7843;n &#273;&#7891; &#273;&#7883;a ch&#237;nh</li>"
        "<li><b>TT 25/2014/TT-BTNMT</b> &mdash; B&#7843;n &#273;&#7891; &#273;&#7883;a ch&#237;nh</li>"
        "<li><b>TT 16/2021/TT-BTNMT</b> &mdash; K&yacute; hi&#7879;u b&#7843;n &#273;&#7891; &#273;&#7883;a h&igrave;nh t&#7881; l&#7879; l&#7899;n</li>"
        "<li><b>TCVN</b> v&#7873; GIS, tr&#7855;c &#273;&#7883;a, VN-2000, HN-72</li>"
        "<li>H&#7879; t&#7885;a &#273;&#7897; <b>VN-2000</b> (Q&#272; 83/2000/Q&#272;-TTg)</li>"
        "</ul><i>&#272;&acirc;y l&agrave; n&#7895; l&#7921;c phi th&#432;&#417;ng m&#7841;i. K&#7871;t qu&#7843; c&#7847;n c&#417; quan nh&agrave; n&#432;&#7899;c x&aacute;c nh&#7853;n m&#7899;i c&oacute; gi&aacute; tr&#7883; ph&aacute;p l&yacute;.</i></div>"
        "<div class='en'><ul>"
        "<li><b>MONRE</b> &mdash; National standards for surveying &amp; cadastral mapping</li>"
        "<li><b>Circular 25/2014/TT-BTNMT</b> &mdash; Cadastral maps</li>"
        "<li><b>Circular 16/2021/TT-BTNMT</b> &mdash; Large-scale topographic map symbols</li>"
        "<li><b>TCVN</b> for GIS, geodesy, VN-2000 &amp; HN-72</li>"
        "<li><b>VN-2000</b> coordinate system (Decision 83/2000/QD-TTg)</li>"
        "</ul><i>This is a non-commercial effort. Legal validity requires confirmation by a competent state authority.</i></div>"

        "<h3>4. &#128220; B&#7843;n quy&#7873;n / Copyright &amp; License</h3>"
        "<div class='vi'>Ph&aacute;t h&agrave;nh <b>mi&#7877;n ph&#237;</b> theo <b>GPL-3.0</b>. B&#7843;n quy&#7873;n &copy; <b>L&#7897;c V&#361; Trung (LVTCenter)</b>. S&#7917; d&#7909;ng th&#432;&#417;ng m&#7841;i <b>b&#7883; nghi&ecirc;m c&#7845;m</b>.</div>"
        "<div class='en'>Released <b>free</b> under <b>GPL-3.0</b>. Copyright &copy; <b>L&#7897;c V&#361; Trung (LVTCenter)</b>. Commercial use is <b>strictly prohibited</b>.</div>"

        "<h3>5. &#9878;&#65039; Mi&#7877;n tr&#7915; tr&aacute;ch nhi&#7879;m / Disclaimer of Liability</h3>"
        "<div class='vi'><b>T&aacute;c gi&#7843; KH&Ocirc;NG ch&#7883;u tr&aacute;ch nhi&#7879;m:</b><ul>"
        "<li>Sai l&#7879;ch t&#7885;a &#273;&#7897;, di&#7879;n t&#237;ch do gi&#7899;i h&#7841;n thu&#7853;t to&aacute;n ho&#7863;c d&#7919; li&#7879;u &#273;&#7847;u v&agrave;o</li>"
        "<li>Thi&#7879;t h&#7841;i t&#7915; vi&#7879;c d&ugrave;ng k&#7871;t qu&#7843; plugin cho m&#7909;c &#273;&#237;ch th&#432;&#417;ng m&#7841;i, ph&aacute;p l&yacute;</li>"
        "<li>M&#7845;t d&#7919; li&#7879;u, h&#7887;ng file, xung &#273;&#7897;t ph&#7847;n m&#7873;m</li>"
        "</ul></div>"
        "<div class='en'><b>The author is NOT liable for:</b><ul>"
        "<li>Coordinate or area errors due to algorithm/data limitations</li>"
        "<li>Damages from commercial or legal use of plugin outputs</li>"
        "<li>Data loss, file corruption, or software conflicts</li>"
        "</ul></div>"
        "<div class='warn'>&#9888;&#65039; Ch&ecirc;nh l&#7879;ch t&#7885;a &#273;&#7897; gi&#7919;a c&aacute;c ph&eacute;p chi&#7871;u (VN-2000, WGS-84...) l&agrave; b&igrave;nh th&#432;&#7901;ng. Ph&#7909; thu&#7897;c datum NTv2 trong QGIS.<br>"
        "Coordinate differences between projections are normal. Depends on NTv2 datum grid in your QGIS.</div>"
    )


class AboutDialog(QDialog):
    """About dialog with two tabs: About info and Terms of Use."""

    def __init__(self, iface, plugin_dir, parent=None):
        super().__init__(parent or iface.mainWindow())
        self.iface = iface
        self.plugin_dir = plugin_dir
        self.setWindowTitle(f"LVT — {tr('About')}")
        self.setMinimumWidth(520)
        self.setMinimumHeight(560)
        _NCHB = getattr(Qt, 'WindowContextHelpButtonHint',
                        getattr(getattr(Qt, 'WindowType', Qt),
                                'WindowContextHelpButtonHint', 0))
        self.setWindowFlags(self.windowFlags() & ~_NCHB)
        self._read_metadata()
        self._build_ui()

    def _read_metadata(self):
        meta_path = os.path.join(self.plugin_dir, "metadata.txt")
        config = configparser.ConfigParser()
        # utf-8-sig automatically strips the BOM (\ufeff) if present
        try:
            config.read(meta_path, encoding="utf-8-sig")
        except Exception:
            try:
                config.read(meta_path, encoding="utf-8")
            except Exception:
                pass  # nosec B110
        self._version     = config.get("general", "version",     fallback="—")
        self._description = config.get("general", "description", fallback="")
        self._author      = config.get("general", "author",      fallback="—")

    def _build_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(10)

        tabs = QTabWidget()
        main_layout.addWidget(tabs)

        # Tab 1: About
        about_tab = QWidget()
        self._build_about_tab(about_tab)
        tabs.addTab(about_tab, f"  {tr('About')}")

        # Tab 2: Terms
        terms_tab = QWidget()
        self._build_terms_tab(terms_tab)
        tabs.addTab(terms_tab, "  Điều khoản / Terms of Use")

        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        close_btn = QPushButton(tr("Close"))
        close_btn.clicked.connect(self.close)
        btn_layout.addWidget(close_btn)
        main_layout.addLayout(btn_layout)

    def _build_about_tab(self, tab):
        layout = QVBoxLayout(tab)
        layout.setSpacing(12)

        header = QLabel("LVT Plugin Suite")
        header_font = QFont()
        header_font.setPointSize(16)
        header_font.setBold(True)
        header.setFont(header_font)
        header.setAlignment(QtCompat.AlignCenter)
        layout.addWidget(header)

        desc = QLabel(self._description)
        desc.setWordWrap(True)
        desc.setAlignment(QtCompat.AlignCenter)
        layout.addWidget(desc)

        author_html = f"""
        <div style='font-family:Arial;text-align:center;color:#333'>
        <div style='background:#f4f4f4;padding:20px;border-radius:10px'>
        <h1 style='color:#1B5E20;margin-bottom:5px;'>L&#7897;c V&#361; Trung</h1>
        <p style='font-size:14px;font-weight:bold;color:#444;margin-top:0;'>
        {tr('FSC, Silviculture & Digital Transformation Expert')}</p>
        <hr style='border:0;height:1px;background:#ddd;width:80%'>
        <div style='text-align:left;display:inline-block;width:80%;
        font-size:13px;line-height:1.8;margin-top:10px'>
        <b>&#128242; Zalo:</b> 0913 191 178<br>
        <b>&#127760; Website:</b> <a href='http://locvutrung.lvtcenter.it.com'
        style='color:#1565C0'>locvutrung.lvtcenter.it.com</a><br>
        <b>&#127916; YouTube:</b> <a href='https://www.youtube.com/@locvutrung'
        style='color:#c62828'>youtube.com/@locvutrung</a><br>
        </div>
        <div style='margin-top:15px;background:#fff;padding:12px;
        border-radius:5px;border-left:5px solid #1B5E20;text-align:left;
        font-size:13px;line-height:1.8;box-shadow:0 2px 4px rgba(0,0,0,0.1)'>
        <b>{tr('Expertise')}:</b><br>
        &#8226; {tr('FSC/CoC Forest Certification')}<br>
        &#8226; {tr('EU Deforestation Regulation (EUDR)')}<br>
        &#8226; {tr('Webapp / Appsheet Applications')}<br>
        &#8226; {tr('QGIS GIS / Data Management')}<br>
        &#8226; {tr('Silviculture')}
        </div></div></div>
        """
        author_label = QLabel(author_html)
        author_label.setWordWrap(True)
        author_label.setTextFormat(QtCompat.RichText)
        author_label.setOpenExternalLinks(True)
        layout.addWidget(author_label)

        info_group = QGroupBox()
        info_layout = QFormLayout(info_group)
        info_layout.addRow(
            QLabel(f"<b>{tr('Version')}:</b>"),
            QLabel(self._version),
        )
        info_layout.addRow(
            QLabel(f"<b>{tr('License')}:</b>"),
            QLabel("GPL-3.0 — Non-commercial use only"),
        )
        layout.addWidget(info_group)

        lang_group = QGroupBox(tr("Language"))
        lang_layout = QHBoxLayout(lang_group)
        self._lang_combo = QComboBox()
        self._lang_combo.addItem("English", "en")
        self._lang_combo.addItem("Tiếng Việt", "vi")
        current = current_language()
        idx = self._lang_combo.findData(current)
        if idx >= 0:
            self._lang_combo.setCurrentIndex(idx)
        lang_layout.addWidget(QLabel(f"{tr('Language')}:"))
        lang_layout.addWidget(self._lang_combo)
        save_btn = QPushButton(tr("Apply"))
        save_btn.clicked.connect(self._on_apply)
        lang_layout.addWidget(save_btn)
        layout.addWidget(lang_group)
        layout.addStretch()

    def _build_terms_tab(self, tab):
        layout = QVBoxLayout(tab)
        lbl = QLabel(
            "<b>Điều khoản sử dụng đầy đủ / Full Terms of Use</b><br>"
            "<i>Hiệu lực từ lần cài đặt / In effect from installation</i>"
        )
        lbl.setWordWrap(True)
        layout.addWidget(lbl)
        txt = QTextEdit()
        txt.setReadOnly(True)
        txt.setHtml(_build_terms_html(self._version))
        layout.addWidget(txt)

    def _on_apply(self):
        chosen = self._lang_combo.currentData()
        # set_language() now emits language_signals.language_changed
        # which triggers _rebuild_ui in lvt_plugin.py — no restart needed
        set_language(chosen)
        lang_name = "Tiếng Việt" if chosen == "vi" else "English"
        self.iface.messageBar().pushSuccess(
            "LVT",
            tr("Language") + f": {lang_name} — ✅ Applied!",
        )
