#import "FGToast.h"

static const NSInteger kFGToastTag = 0xF6001;

@implementation FGToast

+ (void)show:(NSString *)message inView:(UIView *)view {
    if (!view || message.length == 0) return;

    dispatch_async(dispatch_get_main_queue(), ^{
        UIView *existing = [view viewWithTag:kFGToastTag];
        [existing removeFromSuperview];

        UIView *container = [[UIView alloc] initWithFrame:CGRectZero];
        container.tag = kFGToastTag;
        container.backgroundColor = [UIColor colorWithWhite:0.08 alpha:0.92];
        container.layer.cornerRadius = 14.0;
        container.layer.cornerCurve = kCACornerCurveContinuous;
        container.translatesAutoresizingMaskIntoConstraints = NO;
        container.alpha = 0.0;

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.text = message;
        label.textColor = UIColor.whiteColor;
        label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        label.translatesAutoresizingMaskIntoConstraints = NO;

        [container addSubview:label];
        [view addSubview:container];

        [NSLayoutConstraint activateConstraints:@[
            [container.centerXAnchor constraintEqualToAnchor:view.centerXAnchor],
            [container.bottomAnchor constraintEqualToAnchor:view.safeAreaLayoutGuide.bottomAnchor constant:-96.0],
            [container.widthAnchor constraintLessThanOrEqualToAnchor:view.widthAnchor constant:-56.0],

            [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:18.0],
            [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-18.0],
            [label.topAnchor constraintEqualToAnchor:container.topAnchor constant:12.0],
            [label.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-12.0]
        ]];

        container.transform = CGAffineTransformMakeTranslation(0, 10);
        [UIView animateWithDuration:0.24 animations:^{
            container.alpha = 1.0;
            container.transform = CGAffineTransformIdentity;
        }];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.4 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.28 animations:^{
                container.alpha = 0.0;
                container.transform = CGAffineTransformMakeTranslation(0, 8);
            } completion:^(BOOL finished) {
                [container removeFromSuperview];
            }];
        });
    });
}

@end
