//
//  HomeScenicHeaderView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 首页顶部景区选择条。
final class HomeScenicHeaderView: UIView {

    /// 点击景区名称时触发。
    var onTap: (() -> Void)?

    /// 点击消息入口时触发。
    var onMessageTap: (() -> Void)?

    private let titleLabel = UILabel()
    private let arrowView = UIImageView(image: UIImage(systemName: "chevron.down"))
    private let messageButton = UIButton(type: .system)
    private let unreadDotView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = AppColor.cardBackground
        titleLabel.font = .app(.subtitle)
        titleLabel.textColor = AppColor.textPrimary
        titleLabel.lineBreakMode = .byTruncatingTail
        titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        arrowView.tintColor = AppColor.textSecondary
        arrowView.contentMode = .scaleAspectFit
        arrowView.setContentCompressionResistancePriority(.required, for: .horizontal)

        var messageConfiguration = UIButton.Configuration.plain()
        messageConfiguration.image = UIImage(systemName: "bell")
        messageConfiguration.baseForegroundColor = AppColor.textPrimary
        messageConfiguration.contentInsets = .zero
        messageButton.configuration = messageConfiguration
        messageButton.accessibilityIdentifier = "home_message_button"
        messageButton.addTarget(self, action: #selector(handleMessageTap), for: .touchUpInside)

        unreadDotView.backgroundColor = AppColor.danger
        unreadDotView.layer.cornerRadius = 4
        unreadDotView.isUserInteractionEnabled = false
        unreadDotView.isHidden = true
        unreadDotView.accessibilityIdentifier = "home_message_unread_dot"

        addSubview(titleLabel)
        addSubview(arrowView)
        addSubview(messageButton)
        messageButton.addSubview(unreadDotView)

        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(safeAreaLayoutGuide).offset(AppSpacing.screenHorizontalInset)
            make.centerY.equalTo(safeAreaLayoutGuide)
        }
        arrowView.snp.makeConstraints { make in
            make.leading.equalTo(titleLabel.snp.trailing).offset(AppSpacing.xs)
            make.trailing.lessThanOrEqualTo(messageButton.snp.leading).offset(-AppSpacing.xs)
            make.centerY.equalTo(safeAreaLayoutGuide)
            make.width.height.equalTo(16)
        }
        messageButton.snp.makeConstraints { make in
            make.trailing.equalTo(safeAreaLayoutGuide).offset(-AppSpacing.screenHorizontalInset)
            make.centerY.equalTo(safeAreaLayoutGuide)
            make.width.height.equalTo(44)
        }
        unreadDotView.snp.makeConstraints { make in
            make.centerX.equalTo(messageButton.snp.centerX).offset(9)
            make.centerY.equalTo(messageButton.snp.centerY).offset(-9)
            make.width.height.equalTo(8)
        }

        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 更新景区名称与未读消息状态。
    func apply(scenicName: String, hasUnreadMessages: Bool) {
        let trimmed = scenicName.trimmingCharacters(in: .whitespacesAndNewlines)
        titleLabel.text = trimmed.isEmpty ? "请选择景区" : trimmed
        unreadDotView.isHidden = !hasUnreadMessages
        messageButton.accessibilityLabel = hasUnreadMessages ? "消息中心，有未读消息" : "消息中心"
    }

    @objc private func handleTap() {
        onTap?()
    }

    @objc private func handleMessageTap() {
        onMessageTap?()
    }
}

extension HomeScenicHeaderView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        guard let touchedView = touch.view else { return true }
        return touchedView !== messageButton && !touchedView.isDescendant(of: messageButton)
    }
}
