//
//  PageCurlView.swift
//  Baccarat
//
//  A SwiftUI wrapper around UIPageViewController to provide native iBooks-style
//  page curl transitions for card reveals, treated as a single double-sided sheet.
//

import SwiftUI
import UIKit
import CasinoKit

struct PageCurlView: View {
    let card: Card
    let width: CGFloat
    let onReveal: () -> Void
    /// Called when user starts interacting with the page curl
    var onInteractionStarted: (() -> Void)? = nil
    
    @State private var currentIndex = 0
    
    private var height: CGFloat {
        width * CasinoDesign.Size.cardAspectRatio
    }
    
    var body: some View {
        PageCurlRepresentable(
            currentIndex: $currentIndex,
            width: width,
            height: height,
            onReveal: onReveal,
            onInteractionStarted: onInteractionStarted,
            pages: [
            // Page 0: Card Back (Top side)
            AnyView(
                CardBackView(width: width, height: height)
                    .tag(0)
                    .contentShape(Rectangle())
            ),
            // Page 1: Card Front (Underside/Reveal side)
            AnyView(
                CardFrontView(card: card, width: width, height: height)
                    .tag(1)
            ),
            // Page 2: Empty space behind the card
            AnyView(
                Color.clear
                    .frame(width: width, height: height)
                    .tag(2)
            )
        ])
        .frame(width: width, height: height)
        // Use both card ID and size to force recreation on rotation
        .id("page-curl-\(card.id)-\(Int(width))")
    }
}

private struct PageCurlRepresentable: UIViewControllerRepresentable {
    @Binding var currentIndex: Int
    let width: CGFloat
    let height: CGFloat
    let onReveal: () -> Void
    let onInteractionStarted: (() -> Void)?
    let pages: [AnyView]
    
    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageVC = UIPageViewController(
            transitionStyle: .pageCurl,
            navigationOrientation: .vertical,
            options: [UIPageViewController.OptionsKey.spineLocation: UIPageViewController.SpineLocation.min.rawValue]
        )
        
        pageVC.isDoubleSided = true
        pageVC.dataSource = context.coordinator
        pageVC.delegate   = context.coordinator
        
        let vc = UIHostingController(rootView: pages[0])
        vc.view.tag = 0
        vc.view.backgroundColor = .clear
        pageVC.setViewControllers([vc], direction: .forward, animated: false)
        
        // Disable internal tap gesture recognizers to ensure purely gestural interaction
        for gesture in pageVC.gestureRecognizers {
            if gesture is UITapGestureRecognizer {
                gesture.isEnabled = false
            }
        }
        
        return pageVC
    }
    
    func updateUIViewController(_ pageVC: UIPageViewController, context: Context) {
        // Update the page view controller's preferred content size when dimensions change
        pageVC.preferredContentSize = CGSize(width: width, height: height)
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        let parent: PageCurlRepresentable
        
        init(_ parent: PageCurlRepresentable) {
            self.parent = parent
        }
        
        func pageViewController(_ pageVC: UIPageViewController,
                                viewControllerBefore vc: UIViewController) -> UIViewController? {
            let index = vc.view.tag
            guard index > 0 else { return nil }
            
            let prevVC = UIHostingController(rootView: parent.pages[index - 1])
            prevVC.view.tag = index - 1
            prevVC.view.backgroundColor = .clear
            return prevVC
        }
        
        func pageViewController(_ pageVC: UIPageViewController,
                                viewControllerAfter vc: UIViewController) -> UIViewController? {
            let index = vc.view.tag
            guard index < parent.pages.count - 1 else { return nil }
            
            let nextVC = UIHostingController(rootView: parent.pages[index + 1])
            nextVC.view.tag = index + 1
            nextVC.view.backgroundColor = .clear
            return nextVC
        }
        
        func pageViewController(_ pageVC: UIPageViewController,
                                willTransitionTo pendingViewControllers: [UIViewController]) {
            // User started interacting with the page curl
            parent.onInteractionStarted?()
        }
        
        func pageViewController(_ pageVC: UIPageViewController,
                                didFinishAnimating finished: Bool,
                                previousViewControllers: [UIViewController],
                                transitionCompleted completed: Bool) {
            guard completed,
                  let visibleVC = pageVC.viewControllers?.first else { return }
            
            let newIndex = visibleVC.view.tag
            parent.currentIndex = newIndex
            if newIndex >= 1 {
                parent.onReveal()
            }
        }
    }
}
