import UIKit
import Capacitor
import WebKit

class ViewController: CAPBridgeViewController {
    
    private var splashView: UIView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 스플래시 뷰 생성
        setupSplashView()
        
        // 웹뷰 로드 완료 감지
        NotificationCenter.default.addObserver(self, selector: #selector(webViewDidFinishLoad), name: NSNotification.Name(rawValue: "capacitorWebViewDidLoad"), object: nil)
    }
    
    private func setupSplashView() {
        // 스플래시 뷰 생성
        splashView = UIView(frame: self.view.bounds)
        splashView?.backgroundColor = UIColor.white
        
        // 스플래시 이미지 추가
        let imageView = UIImageView(image: UIImage(named: "Splash"))
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        
        if let splashView = splashView {
            self.view.addSubview(splashView)
            splashView.addSubview(imageView)
            
            NSLayoutConstraint.activate([
                imageView.centerXAnchor.constraint(equalTo: splashView.centerXAnchor),
                imageView.centerYAnchor.constraint(equalTo: splashView.centerYAnchor),
                imageView.widthAnchor.constraint(equalToConstant: 200),
                imageView.heightAnchor.constraint(equalToConstant: 200)
            ])
        }
    }
    
    @objc private func webViewDidFinishLoad() {
        // 웹뷰 로드 완료 시 스플래시 화면 제거 (2초 후)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            UIView.animate(withDuration: 0.3, animations: {
                self.splashView?.alpha = 0
            }, completion: { _ in
                self.splashView?.removeFromSuperview()
                self.splashView = nil
            })
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 웹뷰 로드 시작 시 스크립트 실행 (최대 2초 후 스플래시 제거)
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            if self.splashView != nil && self.splashView?.alpha == 1 {
                UIView.animate(withDuration: 0.3, animations: {
                    self.splashView?.alpha = 0
                }, completion: { _ in
                    self.splashView?.removeFromSuperview()
                    self.splashView = nil
                })
            }
        }
    }
}
