//
//  DuckedPlaceholderView.swift
//  Duckable
//
//  Created by Shadowfacts on 11/7/22.
//

import UIKit

@available(iOS 16.0, *)
class DuckedPlaceholderViewController: UIViewController {
    private unowned let owner: DuckableContainerViewController
    private let navBar = UINavigationBar()
    
    var topConstraint: NSLayoutConstraint!
    
    init(for duckableViewController: DuckableViewController, owner: DuckableContainerViewController) {
        self.owner = owner
        
        super.init(nibName: nil, bundle: nil)
        
        let item = UINavigationItem()
        item.title = duckableViewController.navigationItem.title
        item.titleView = duckableViewController.navigationItem.titleView
        navBar.setItems([item], animated: false)
    }
    
    required init?(coder: NSCoder) {
        fatalError()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setBackgroundColor()
        view.layer.cornerRadius = duckedCornerRadius
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.05
        
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(placeholderTapped)))
        
        let appearance = UINavigationBarAppearance()
        appearance.configureWithTransparentBackground()
        navBar.standardAppearance = appearance
        navBar.isUserInteractionEnabled = false
        navBar.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(navBar)
        NSLayoutConstraint.activate([
            navBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            navBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            navBar.topAnchor.constraint(equalTo: view.topAnchor),
        ])
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        
        setBackgroundColor()
    }
    
    private func setBackgroundColor() {
        // when just using .systemBackground and setting the override trait collection for the placeholder VC,
        // the color doesn't change until after the dismiss animation occurs (but only when tapping the grabber to duck, not when swiping)
        view.backgroundColor = .systemBackground.resolvedColor(with: UITraitCollection(traitsFrom: [traitCollection, UITraitCollection(userInterfaceLevel: .elevated)]))
    }
    
    @objc private func placeholderTapped() {
        owner.unduckViewController()
    }
}
