//
//  MFCardV3View.swift
//  MyfatoorahReactnative
//
//  The React Native host view for the V3 embedded card. A thin, NON-singleton
//  UIView that wraps the SDK's `MFCardViewV3` (a fresh instance per mounted RN
//  component). Each view registers itself under a JS-assigned `cardId` so
//  `MFCardV3Module`'s promise methods can reach the exact instance — this works
//  identically under the old and new (bridgeless) RN architecture, with no
//  reliance on findNodeHandle / UIManager view resolution.
//

import UIKit
import MFSDK

final class MFCardV3View: UIView {

    /// cardId -> view. Weak values auto-clear when a view is deallocated. Only
    /// touched on the main thread (RN sets props and the module resolves on main).
    private static let registry = NSMapTable<NSString, MFCardV3View>.strongToWeakObjects()

    static func view(for cardId: String) -> MFCardV3View? {
        return registry.object(forKey: cardId as NSString)
    }

    /// The underlying SDK card view (independent per instance — no singleton).
    let cardView = MFCardViewV3()

    /// Unique id assigned by the JS component; used to route module calls + events.
    @objc var cardId: NSString? {
        didSet {
            if let old = oldValue { MFCardV3View.registry.removeObject(forKey: old) }
            if let cardId = cardId { MFCardV3View.registry.setObject(self, forKey: cardId) }
        }
    }

    /// Reused JS `MFCardViewStyle` dictionary, applied to the SDK view's
    /// `configuration` before `load(session:)`.
    @objc var paymentStyle: NSDictionary? {
        didSet {
            cardView.configuration = MFCardV3ConfigTranslator.configuration(from: paymentStyle)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    deinit {
        if let cardId = cardId { MFCardV3View.registry.removeObject(forKey: cardId) }
    }

    private func setup() {
        cardView.delegate = self
        cardView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(cardView)
        NSLayoutConstraint.activate([
            cardView.leadingAnchor.constraint(equalTo: leadingAnchor),
            cardView.trailingAnchor.constraint(equalTo: trailingAnchor),
            cardView.topAnchor.constraint(equalTo: topAnchor),
            cardView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
}

// MARK: - SDK delegate -> tagged RN events

extension MFCardV3View: MFCardViewV3Delegate {
    func cardView(_ cardView: MFCardViewV3, didChangeHeight height: CGFloat) {
        MFCardV3Module.emitCardResized(cardId: cardId as String?, height: height)
    }

    func cardView(_ cardView: MFCardViewV3, didReceive event: MFV3WidgetEvent, payload: MFV3EventPayload) {
        MFCardV3Module.emitWidgetEvent(cardId: cardId as String?,
                                       name: event.rawValue,
                                       id: payload.id,
                                       paymentMethodName: payload.paymentMethodName)
    }

    func cardView(_ cardView: MFCardViewV3, didFailToLoad error: MFFailResponse) {
        MFCardV3Module.emitError(cardId: cardId as String?,
                                 code: error.statusCode,
                                 message: error.errorDescription)
    }
}
