//
//  AuthorizationViewController.m
//  HotPocket (macOS)
//
//  Created by Tomek Wójcik on 20/09/2025.
//

#import "AuthorizationViewController.h"

#import "AppDelegate.h"
#import "AuthorizationProgressViewController.h"
#import "HPAuthFlow.h"
#import "ReplaceAnimator.h"

@interface AuthorizationViewController (AuthorizationViewControllerPrivate)

#pragma mark - Private interface

@end

@implementation AuthorizationViewController

#pragma mark - View lifecycle

-(void)viewDidLoad {
    [super viewDidLoad];
    self.baseURL = nil;
    self.authorizationSessionToken = nil;
}

#pragma mark - Actions

-(IBAction)doStartAuthorizationFlow:(id)sender {
    NSAlert *alert = [[NSAlert alloc] init];
    alert.alertStyle = NSAlertStyleInformational;
    alert.messageText = NSLocalizedString(@"Continue in the browser", @"Continue in the browser");
    alert.informativeText = NSLocalizedString(@"HotPocket will now open the instance in your browser and you can continue to sign in.", @"HotPocket will now open the instance in your browser and you can continue to sign in.");
    
    [alert addButtonWithTitle:NSLocalizedString(@"Let's go!", @"Let's go!")];
    [alert addButtonWithTitle:NSLocalizedString(@"Cancel", @"Cancel")];
    
    [alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse response) {
        if (response == NSAlertFirstButtonReturn) {
            AppDelegate *appDeleate = [[NSApplication sharedApplication] delegate];
            appDeleate.authFlow.baseURL = [NSURL URLWithString:self.baseURL];
            
            NSURL *authURL = [appDeleate.authFlow start];
            if (authURL == nil) {
                NSBeep();
                return;
            }

            AuthorizationProgressViewController *authProgressViewController = [self.storyboard instantiateControllerWithIdentifier:@"AuthorizationProgressViewController"];
            [self presentViewController:authProgressViewController animator:[[ReplaceAnimator alloc] init]];
            
            [[NSWorkspace sharedWorkspace] openURL:authURL];
        }
    }];
}

@end
