#!/bin/bash

# 스플래시 화면 표시 시간 강제 설정 스크립트
echo "스플래시 화면 표시 시간 강제 설정 중..."

# 프로젝트 디렉토리로 이동
cd "$(dirname "$0")"

# 1. 기존 Capacitor 스플래시 플러그인 비활성화하고 네이티브 스플래시 사용
echo "Capacitor 스플래시 설정 수정 중..."
cat > capacitor.config.ts << 'EOL'
import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.lovable.zellyfinance',
  appName: '젤리의 적자탈출',
  webDir: 'dist',
  server: {
    androidScheme: 'https',
    iosScheme: 'https',
    cleartext: true
  },
  plugins: {
    SplashScreen: {
      launchShowDuration: 0,
      launchAutoHide: false,
      backgroundColor: "#FFFFFF",
      androidSplashResourceName: "splash",
      androidScaleType: "CENTER_CROP",
      showSpinner: false,
      splashFullScreen: true,
      splashImmersive: false
    },
    Keyboard: {
      resize: "body",
      style: "dark",
      resizeOnFullScreen: true
    }
  },
  ios: {
    scheme: "App",
    contentInset: "always",
    allowsLinkPreview: false,
    scrollEnabled: true,
    limitsNavigationsToAppBoundDomains: true,
    backgroundColor: "#F2F2F2"
  }
};

export default config;
EOL

# 2. AppDelegate.swift 수정 - 스플래시 화면 직접 제어
echo "AppDelegate.swift 수정 중..."
APP_DELEGATE="ios/App/App/AppDelegate.swift"

if [ -f "$APP_DELEGATE" ]; then
  # 백업 생성
  cp "$APP_DELEGATE" "${APP_DELEGATE}.bak_force"
  
  # AppDelegate.swift 내용 교체 - 스플래시 화면 직접 제어
  cat > "$APP_DELEGATE" << 'EOL'
import UIKit
import Capacitor
import WebKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var splashView: UIView?
    var startTime: Date?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 시작 시간 기록
        startTime = Date()
        
        // 배경색 설정
        self.window?.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        
        // 웹뷰 캐시 설정 최적화
        let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
        let date = Date(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
        
        // 웹뷰 설정 최적화
        let webViewConfig = WKWebViewConfiguration()
        webViewConfig.allowsInlineMediaPlayback = true
        webViewConfig.suppressesIncrementalRendering = false
        webViewConfig.allowsAirPlayForMediaPlayback = true
        webViewConfig.mediaTypesRequiringUserActionForPlayback = []
        
        // 스플래시 화면 감지 설정
        NotificationCenter.default.addObserver(self, 
                                              selector: #selector(handleWebViewDidLoad), 
                                              name: NSNotification.Name(rawValue: "capacitorWebViewDidLoad"), 
                                              object: nil)
        
        return true
    }
    
    @objc func handleWebViewDidLoad() {
        // 웹뷰 로드 완료 시 스플래시 화면 제거 (최소 10초 이상 표시)
        let minimumSplashTime: TimeInterval = 10.0
        
        if let startTime = startTime {
            let timeElapsed = Date().timeIntervalSince(startTime)
            let remainingTime = max(0, minimumSplashTime - timeElapsed)
            
            DispatchQueue.main.asyncAfter(deadline: .now() + remainingTime) {
                // 스플래시 화면 제거 요청
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "removeSplashScreen"), object: nil)
            }
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
}
EOL
fi

# 3. ViewController.swift 수정 - 스플래시 화면 직접 제어
echo "ViewController.swift 수정 중..."
VIEWCONTROLLER="ios/App/App/ViewController.swift"

if [ -f "$VIEWCONTROLLER" ]; then
  # 백업 생성
  cp "$VIEWCONTROLLER" "${VIEWCONTROLLER}.bak_force"
  
  # ViewController.swift 내용 교체 - 스플래시 화면 직접 제어
  cat > "$VIEWCONTROLLER" << 'EOL'
import UIKit
import Capacitor
import WebKit

class ViewController: CAPBridgeViewController {
    
    private var splashView: UIView?
    private var splashRemoved = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 배경색 설정 - 밝은 회색
        self.view.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        self.webView?.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        
        // 스플래시 뷰 생성
        setupSplashView()
        
        // 웹뷰 로드 완료 감지
        NotificationCenter.default.addObserver(self, selector: #selector(webViewDidFinishLoad), name: NSNotification.Name(rawValue: "capacitorWebViewDidLoad"), object: nil)
        
        // 스플래시 화면 제거 요청 감지
        NotificationCenter.default.addObserver(self, selector: #selector(removeSplashScreenRequested), name: NSNotification.Name(rawValue: "removeSplashScreen"), object: nil)
        
        // 최대 표시 시간 설정 (15초 후 강제 제거)
        DispatchQueue.main.asyncAfter(deadline: .now() + 15.0) {
            self.removeSplashScreen()
        }
    }
    
    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() {
        // 웹뷰 로드 완료 시 AppDelegate에 알림
        // (AppDelegate에서 최소 표시 시간 계산 후 제거 요청)
        print("웹뷰 로드 완료")
    }
    
    @objc private func removeSplashScreenRequested() {
        // 스플래시 화면 제거 요청 수신
        removeSplashScreen()
    }
    
    private func removeSplashScreen() {
        if !splashRemoved && splashView != nil {
            splashRemoved = true
            print("스플래시 화면 제거 중...")
            UIView.animate(withDuration: 0.8, animations: {
                self.splashView?.alpha = 0
            }, completion: { _ in
                self.splashView?.removeFromSuperview()
                self.splashView = nil
                print("스플래시 화면 제거 완료")
            })
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        // 웹뷰 배경색 설정
        self.webView?.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        self.webView?.scrollView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        self.webView?.isOpaque = false
    }
}
EOL
fi

# 4. index.html 수정 - 웹뷰 로드 완료 알림 지연
echo "index.html 수정 중..."
INDEX_HTML="ios/App/App/public/index.html"

if [ -f "$INDEX_HTML" ]; then
  # 백업 생성
  cp "$INDEX_HTML" "${INDEX_HTML}.bak_force"
  
  # 웹뷰 로드 완료 알림 코드 수정 - 지연 추가
  sed -i '' '/<\/head>/i\
  <style>\
    body, html {\
      background-color: #F2F2F2 !important;\
      margin: 0;\
      padding: 0;\
      height: 100%;\
      width: 100%;\
    }\
  </style>\
  <script>\
    document.addEventListener("DOMContentLoaded", function() {\
      // 배경색 설정\
      document.body.style.backgroundColor = "#F2F2F2";\
      \
      // 스플래시 화면을 더 오래 표시하기 위해 지연 추가\
      setTimeout(function() {\
        console.log("웹뷰 로드 완료 알림 전송");\
        if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.bridge) {\
          window.webkit.messageHandlers.bridge.postMessage({\
            type: "notification",\
            name: "capacitorWebViewDidLoad"\
          });\
        } else if (window.capacitor) {\
          var event = new CustomEvent("capacitorWebViewDidLoad");\
          document.dispatchEvent(event);\
        }\
      }, 3000); // 3초 지연\
    });\
  </script>' "$INDEX_HTML"
fi

# 5. Info.plist 수정 - 스플래시 화면 관련 설정
echo "Info.plist 수정 중..."
INFO_PLIST="ios/App/App/Info.plist"

if [ -f "$INFO_PLIST" ]; then
  # 백업 생성
  cp "$INFO_PLIST" "${INFO_PLIST}.bak_force"
  
  # UIApplicationExitsOnSuspend 설정 제거 (만약 있다면)
  /usr/libexec/PlistBuddy -c "Delete :UIApplicationExitsOnSuspend" "$INFO_PLIST" 2>/dev/null || true
  
  # 콘솔 로그 활성화
  /usr/libexec/PlistBuddy -c "Add :OS_ACTIVITY_MODE string disable" "$INFO_PLIST" 2>/dev/null || true
fi

# 6. Capacitor 설정 동기화
echo "Capacitor 설정 동기화 중..."
npx cap sync ios

echo "완료! 이제 Xcode에서 다시 빌드하세요."
echo "스플래시 화면이 최소 10초 이상 표시되도록 설정했습니다."
