//
//  AboutViewController.swift
//  VenusKitto
//
//  Created by Neoa on 2025/8/27.
//

import UIKit
import WebKit

final class AboutViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    // 可按需替换为你们的线上链接
    private let PRIVACY_URL = URL(string: "https://ytwljs.github.io/gl-policy.html")!
    private let TERMS_URL   = URL(string: "https://ytwljs.github.io/gl-user.html")!

    private let titleLabel: UILabel = {
        let l = UILabel()
        l.text = "关于我们"
        l.font = .systemFont(ofSize: 28, weight: .semibold)
        l.textColor = UIColor(hex: "#2B2B2B")
        return l
    }()

    private let logoImageView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "Home372"))
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 20
        return iv
    }()

    private let versionLabel: UILabel = {
        let l = UILabel()
        l.font = .systemFont(ofSize: 14)
        l.textColor = UIColor(hex: "#888888")
        l.textAlignment = .center
        return l
    }()

    private let tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .insetGrouped)
        tv.backgroundColor = .clear
        tv.showsVerticalScrollIndicator = false
        tv.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: "#FFFEFC")
        
        if let backImage = UIImage(named: "AddPet385") {
            let backButton = UIBarButtonItem(image: backImage.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(tapCancel))
            navigationItem.leftBarButtonItem = backButton
        }

        buildUI()
        fillInfo()
        tableView.dataSource = self
        tableView.delegate = self
    }

    private func buildUI() {
        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 12),
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24)
        ])

        // 中心内容
        let centerWrap = UIView()
        view.addSubview(centerWrap)
        centerWrap.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            centerWrap.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 24),
            centerWrap.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
            centerWrap.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24)
        ])

        centerWrap.addSubview(logoImageView)
        centerWrap.addSubview(versionLabel)
        logoImageView.translatesAutoresizingMaskIntoConstraints = false
        versionLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            logoImageView.topAnchor.constraint(equalTo: centerWrap.topAnchor, constant: 24),
            logoImageView.centerXAnchor.constraint(equalTo: centerWrap.centerXAnchor),
            logoImageView.widthAnchor.constraint(equalToConstant: 80),
            logoImageView.heightAnchor.constraint(equalToConstant: 80),

            versionLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 8),
            versionLabel.centerXAnchor.constraint(equalTo: centerWrap.centerXAnchor),
            versionLabel.bottomAnchor.constraint(equalTo: centerWrap.bottomAnchor)
        ])

        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: centerWrap.bottomAnchor, constant: 24),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
    
    @objc private func tapCancel() { navigationController?.popViewController(animated: true)
    }


    private func fillInfo() {
        let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "-"
        versionLabel.text = "版本 v\(version)"
    }

    // MARK: - UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int { 1 }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 2 }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "PolicyCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ??
                   UITableViewCell(style: .default, reuseIdentifier: identifier)
        cell.accessoryType = .disclosureIndicator
        cell.selectionStyle = .default
        cell.textLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        cell.textLabel?.textColor = UIColor(hex: "#2B2B2B")
        cell.backgroundColor = .white
        cell.contentView.backgroundColor = .white

        cell.textLabel?.text = (indexPath.row == 0) ? "隐私协议" : "用户协议"
        return cell
    }

    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 52 }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let isPrivacy = (indexPath.row == 0)
        let url = isPrivacy ? PRIVACY_URL : TERMS_URL
        let title = isPrivacy ? "隐私协议" : "用户协议"
        let vc = PolicyWebController(url: url, titleText: title)
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
    }
}

// 简易内置 Web 容器
final class PolicyWebController: UIViewController, WKNavigationDelegate {
    private let url: URL
    private let titleText: String
    private var webView: WKWebView!

    init(url: URL, titleText: String) {
        self.url = url
        self.titleText = titleText
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { fatalError() }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: "#FFFEFC")

        if let backImage = UIImage(named: "AddPet385") {
            let backButton = UIBarButtonItem(image: backImage.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(tapCancel))
            navigationItem.leftBarButtonItem = backButton
        }

        
        let titleLabel = UILabel()
        titleLabel.text = titleText
        titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
        titleLabel.textColor = UIColor(hex: "#2B2B2B")

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])

        webView = WKWebView(frame: .zero)
        webView.navigationDelegate = self
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            webView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
            webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

        webView.load(URLRequest(url: url))
    }
    
    @objc private func tapCancel() { navigationController?.popViewController(animated: true)
    }

}
