//
//  LNNewbieDiscountView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/9.
//

import Foundation
import UIKit
import SnapKit
import Combine


class LNNewbieDiscountView: UIView {
    var discountOnly = false {
        didSet {
            divider.isHidden = discountOnly
            newOnlyLabel.isHidden = discountOnly
        }
    }
    
    private let newOnlyLabel = UILabel()
    private let divider = UIView()
    private let discountLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ discount: Double) {
        discountLabel.text = .init(key: "A00312", "\(Int(discount * 100))%")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNNewbieDiscountView {
    private func setupViews() {
        backgroundColor = .init(hex: "#FF6F32")
        layer.cornerRadius = 4
        clipsToBounds = true
        
        let contentStack = UIStackView()
        contentStack.axis = .horizontal
        contentStack.alignment = .center
        contentStack.spacing = 4
        addSubview(contentStack)
        contentStack.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(6)
            make.verticalEdges.equalToSuperview().inset(3)
        }
        
        newOnlyLabel.font = .body_xs
        newOnlyLabel.textColor = .text_1
        newOnlyLabel.text = .init(key: "A00311")
        contentStack.addArrangedSubview(newOnlyLabel)
        
        divider.backgroundColor = .clear
        let dividerLayer = CAShapeLayer()
        dividerLayer.strokeColor = UIColor.white.withAlphaComponent(0.9).cgColor
        dividerLayer.lineWidth = 0.5
        dividerLayer.lineDashPattern = [1, 0.5]
        divider.layer.addSublayer(dividerLayer)
        divider.publisher(for: \.bounds).removeDuplicates().sink
        { [weak dividerLayer] newValue in
            guard let dividerLayer else { return }
            dividerLayer.frame = newValue
            let path = UIBezierPath()
            path.move(to: CGPoint(x: newValue.width / 2, y: 0))
            path.addLine(to: CGPoint(x: newValue.width / 2, y: newValue.height))
            dividerLayer.path = path.cgPath
        }.store(in: &cancellables)
        divider.snp.makeConstraints { make in
            make.width.equalTo(0.5)
            make.height.equalTo(12)
        }
        contentStack.addArrangedSubview(divider)
        
        discountLabel.font = .body_xs
        discountLabel.textColor = .text_1
        contentStack.addArrangedSubview(discountLabel)
    }
}
