//
//  XXGProtocolLabel.m
//  XXGPlayKit
//
//  Created by apple on 2025/3/10.
//

#import "XXGProtocolLabel.h"
#import "XXGUIDriver.h"
#import "UIImage+XXGImage.h"

@implementation XXGProtocolLabel

+ (XXGProtocolLabel *)xxpk_protocolLabel {
    return [self xxpk_protocolLabel:YES];
}

+ (XXGProtocolLabel *)xxpk_protocolLabel:(BOOL)isCheckBox {
    // 1. 创建 UILabel 并设置属性
    XXGProtocolLabel *label = [[XXGProtocolLabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor lightGrayColor];
    label.font = [UIFont systemFontOfSize:12];
    label.userInteractionEnabled = YES; // 开启交互

    NSAttributedString *imageAttrString = nil;
    if (isCheckBox) {
        // 2. 创建图片附件（图片状态默认为未选中状态，可根据需要替换图片名称）
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        UIImage *templateImage = [[UIImage xxpk_imageBundleOfName:XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_off] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        attachment.image = templateImage; // 保持模板模式，不立即着色
        // 调整图片位置和大小（例如：上下居中，可根据需要调整）
        attachment.bounds = CGRectMake(0, -5, 20, 20);
        imageAttrString = [NSAttributedString attributedStringWithAttachment:attachment];
    }

    // 3. 创建文本部分
    NSString *text = XXGUIDriver.xxpk_string_ui.xxpk_protocl;
    NSMutableAttributedString *textAttrString = [[NSMutableAttributedString alloc] initWithString:text];
    
    // 假设我们希望“点击事件的文字”这部分支持点击，并设置为主色调（例如蓝色）
    NSRange clickableRange = [text rangeOfString:XXGUIDriver.xxpk_string_ui.xxpk_protoclon];
    if (clickableRange.location != NSNotFound) {
        [textAttrString addAttribute:NSForegroundColorAttributeName value:[XXGUIDriver xxpk_mainColor] range:clickableRange];
        [textAttrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:clickableRange];
    }

    // 4. 将图片附件和文本组合成一个富文本
    NSMutableAttributedString *combinedAttrString = [[NSMutableAttributedString alloc] init];
    if (imageAttrString) {
        [combinedAttrString appendAttributedString:imageAttrString];
    }
    [combinedAttrString appendAttributedString:textAttrString];
    
    label.attributedText = combinedAttrString;
    
    // 5. 为 UILabel 添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:label action:@selector(xxpk_handleLabelTap:)];
    [label addGestureRecognizer:tapGesture];
    
    return label;
}

- (void)setXxpk_isChecked:(BOOL)xxpk_isChecked {
    _xxpk_isChecked = !xxpk_isChecked;
    [self xxpk_toggleCheckboxImageForLabel:self];
}

- (void)xxpk_handleLabelTap:(UITapGestureRecognizer *)tapGesture {
    XXGProtocolLabel *label = (XXGProtocolLabel *)tapGesture.view;
    if (!label.attributedText) return;
    
    // 1. 构造 TextKit 核心对象
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:label.bounds.size];
    
    textContainer.lineFragmentPadding = 0;
    textContainer.maximumNumberOfLines = label.numberOfLines;
    textContainer.lineBreakMode = label.lineBreakMode;
    
    [textStorage addLayoutManager:layoutManager];
    [layoutManager addTextContainer:textContainer];
    
    // 2. 强制完成布局计算
    [layoutManager ensureLayoutForTextContainer:textContainer];
    
    // 3. 获取点击位置（需转换为 TextContainer 坐标系）
    CGPoint tapLocation = [tapGesture locationInView:label];
    CGRect usedRect = [layoutManager usedRectForTextContainer:textContainer];
    CGPoint textContainerOrigin = CGPointMake(
        (label.bounds.size.width - usedRect.size.width) / 2,   // 居中对齐 X 偏移
        (label.bounds.size.height - usedRect.size.height) / 2  // 垂直居中 Y 偏移
    );
    
    // 将点击位置转换为相对于 textContainer 的坐标
    CGPoint locationInTextContainer = CGPointMake(
        tapLocation.x - textContainerOrigin.x,
        tapLocation.y - textContainerOrigin.y
    );
    
    // 4. 检测图片点击（不依赖字符索引）
    __block BOOL isImageTapped = NO;
    [label.attributedText enumerateAttribute:NSAttachmentAttributeName
                                    inRange:NSMakeRange(0, label.attributedText.length)
                                    options:0
                                 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if ([value isKindOfClass:[NSTextAttachment class]]) {
            // 获取附件对应的 glyph 范围
            NSRange glyphRange;
            [layoutManager glyphRangeForCharacterRange:range actualCharacterRange:&glyphRange];
            
            // 获取 glyph 的绘制区域
            CGRect glyphRect = [layoutManager boundingRectForGlyphRange:glyphRange
                                                      inTextContainer:textContainer];
            
            // 转换到 label 的坐标系
            CGRect actualGlyphRect = CGRectOffset(glyphRect, textContainerOrigin.x, textContainerOrigin.y);
            
            // 判断点击是否在区域内
            if (CGRectContainsPoint(actualGlyphRect, tapLocation)) {
                isImageTapped = YES;
                *stop = YES;
            }
        }
    }];
    
    if (isImageTapped) {
        NSLog(@"✅ 精确命中图片区域");
        // 处理图片点击逻辑（如切换选中状态）
        [self xxpk_toggleCheckboxImageForLabel:label];
        return;
    }
    
    // 5. 处理协议文本点击（修正索引偏移）
    NSUInteger characterIndex = [layoutManager characterIndexForPoint:locationInTextContainer
                                                    inTextContainer:textContainer
                           fractionOfDistanceBetweenInsertionPoints:NULL];
    
    NSString *fullText = label.attributedText.string;
    NSRange clickableRange = [fullText rangeOfString:XXGUIDriver.xxpk_string_ui.xxpk_protoclon];
    
    if (characterIndex != NSNotFound && NSLocationInRange(characterIndex, clickableRange)) {
        NSLog(@"📜 点击用户协议");
        // 执行跳转逻辑
        if (self.xxpk_handleProtocolTap) {
            self.xxpk_handleProtocolTap();
        }
    }
}

// 切换图片状态示例方法
- (void)xxpk_toggleCheckboxImageForLabel:(XXGProtocolLabel *)label {
    NSMutableAttributedString *attributedText = [label.attributedText mutableCopy];
    __block BOOL hasChanged = NO;
    
    [attributedText enumerateAttribute:NSAttachmentAttributeName
                             inRange:NSMakeRange(0, attributedText.length)
                             options:0
                          usingBlock:^(NSTextAttachment *oldAttachment, NSRange range, BOOL *stop) {
        if (![oldAttachment isKindOfClass:[NSTextAttachment class]]) return;
        
        // 从富文本属性（非附件属性）读取状态
        BOOL isChecked = !_xxpk_isChecked;
        
        // 创建新附件
        NSTextAttachment *newAttachment = [[NSTextAttachment alloc] init];
        
        // 动态选择颜色
        UIColor *targetColor = isChecked ? [XXGUIDriver xxpk_mainColor]: UIColor.lightGrayColor;
        UIImage *originalImage = [UIImage xxpk_imageBundleOfName:isChecked ? XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_on :XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_off];
        
        // 生成着色后的图片
        newAttachment.image = [[originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]
                                imageWithTintColor:targetColor];
        newAttachment.bounds = oldAttachment.bounds;
        
        // 更新富文本
        [attributedText removeAttribute:NSAttachmentAttributeName range:range];
        [attributedText addAttribute:NSAttachmentAttributeName value:newAttachment range:range];
        
        _xxpk_isChecked = isChecked;
        hasChanged = YES;
        *stop = YES;
    }];
    
    if (hasChanged) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView transitionWithView:label
                              duration:0.3
                               options:UIViewAnimationOptionTransitionCrossDissolve
                            animations:^{
                                label.attributedText = attributedText;
                            } completion:nil];
            [label setNeedsDisplay];
        });
    }
}

@end
