//
//  SessionPhoneExpandView.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/20.
//

import Foundation

class SessionPhoneExpandView: UIView {
    
    lazy var expandView: SessionCoverView = {
        let view = SessionCoverView()
//        view.backgroundColor = UIColor.init(white: 0, alpha: 0.4)
        view.backgroundColor = .blue
        view.cornerRadius = 22.0
        view.aiAnswerBlock = { [weak self] in
            self?.tapClicked()
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapClicked))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    var expand: Bool = false
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // 1. 自身不可见/无交互 → 剪枝
        if alpha <= 0.01 || isHidden || !isUserInteractionEnabled { return nil }
        
        // 2. 自身命中（含子视图）→ 正常返回
        let hit = super.hitTest(point, with: event)
        if hit != nil { return hit }
        
        // 3. 自身没命中，继续测**所有子视图（含超框）**
        for sub in subviews.reversed() {
            let converted = sub.convert(point, from: self)
            if sub.bounds.contains(converted) {
                return sub.hitTest(converted, with: event)
            }
        }
        return nil
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = false   // 允许子视图绘制到框外
        setupViews()
        setupData()
        setupEvent()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tapClicked() {
        print("tapClicked 被调用 - expand: \(expand)")
        self.expandView.expandStatusChanged(!self.expand)
        UIView.animate(withDuration: 0.25) {
            // 同时调整自身和expandView的高度
            self.expandView.snp.updateConstraints { make in
                make.height.equalTo(self.expand ? 44 : 152)
            }
            
            self.layoutIfNeeded()
        } completion: { finish in
            if finish {
                self.expand = !self.expand
                
                print("动画完成 - 新的 expand 状态: \(self.expand)")
            }
        }
        
    }
    
    private func setupViews() {
        
        addSubview(expandView)
        
        expandView.snp.makeConstraints { make in
            make.height.width.equalTo(44.0)
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        // 设置自身的高度约束，允许动态调整
        self.snp.makeConstraints { make in
            make.height.equalTo(44.0)
        }
        
    }
    
    private func setupData() {
        
    }
    
    private func setupEvent() {
        
    }
}
