
// ViewController.m
#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <GCDWebServer/GCDWebServer.h>
#import <GCDWebServer/GCDWebServerDataResponse.h>

@interface ViewController () <WKNavigationDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) GCDWebServer *webServer;

// UI
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UIBarButtonItem *backButton;
@property (nonatomic, strong) UIBarButtonItem *reloadButton;
@property (nonatomic, strong) UIBarButtonItem *cancelButton;
@end

@implementation ViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1) Create WKWebView
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.webView];

    // 2) Add toolbar with Back, Reload, Cancel
    [self setupToolbar];

    // 3) Observe canGoBack/canGoForward using KVO
    [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:NULL];

    // 4) Start (or reuse) GCDWebServer and register directory handler for bundled "www"
    self.webServer = [[GCDWebServer alloc] init];

    NSString *siteFolderName = @"www";
    NSString *sitePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:siteFolderName];
    BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:sitePath];
    if (!exists) {
        NSString *alt = [[NSBundle mainBundle] pathForResource:siteFolderName ofType:nil];
        if (alt) {
            sitePath = alt;
            exists = [[NSFileManager defaultManager] fileExistsAtPath:sitePath];
        }
    }

    if (exists) {
        [self.webServer addGETHandlerForBasePath:@"/"
                                   directoryPath:sitePath
                                   indexFilename:@"index.html"
                                        cacheAge:3600
                              allowRangeRequests:YES];
    } else {
        // fallback page
        [self.webServer addHandlerForMethod:@"GET"
                                      path:@"/"
                              requestClass:[GCDWebServerRequest class]
                              processBlock:^GCDWebServerResponse *(GCDWebServerRequest *request) {
            NSString *html = @"<html><body><h1>Missing www folder</h1></body></html>";
            return [GCDWebServerDataResponse responseWithHTML:html];
        }];
    }

    NSError *error = nil;
    BOOL started = [self.webServer startWithOptions:@{
        GCDWebServerOption_Port: @(8080),
        GCDWebServerOption_BindToLocalhost: @YES,
        GCDWebServerOption_AutomaticallySuspendInBackground: @NO
    } error:&error];

    if (!started) {
        NSLog(@"Failed to start web server: %@", error);
    } else {
        NSLog(@"GCDWebServer running at: %@", self.webServer.serverURL);
        // 5) Load webview (prefer 127.0.0.1 for consistency)
        NSURL *url = self.webServer.serverURL ?: [NSURL URLWithString:@"http://127.0.0.1:8080/"];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:req];
    }
}

- (void)dealloc {
    // Remove observers
    @try {
        [self.webView removeObserver:self forKeyPath:@"canGoBack"];
        [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    } @catch (NSException *ex) {
        // ignore if not observing
    }
    if (self.webServer.isRunning) {
        [self.webServer stop];
    }
}

#pragma mark - Toolbar / UI

- (void)setupToolbar {
    // Toolbar height at bottom
    CGFloat toolbarHeight = 44.0;
    CGRect bounds = self.view.bounds;
    CGRect toolbarFrame = CGRectMake(0, CGRectGetHeight(bounds) - toolbarHeight, CGRectGetWidth(bounds), toolbarHeight);
    self.toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame];
    self.toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;

    // Back button
    self.backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind
                                                                    target:self
                                                                    action:@selector(backTapped:)];

    // Reload button
    self.reloadButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                                      target:self
                                                                      action:@selector(reloadTapped:)];

    // Flexible space
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                          target:nil
                                                                          action:nil];

    // Cancel button (close/dismiss)
    self.cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop
                                                                      target:self
                                                                      action:@selector(cancelTapped:)];

    [self.toolbar setItems:@[self.backButton, flex, self.reloadButton, flex, self.cancelButton] animated:NO];
    [self.view addSubview:self.toolbar];

    // initial state
    self.backButton.enabled = NO;
}

#pragma mark - Button Actions

- (void)backTapped:(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        // Optionally treat Back as Cancel if no history:
        [self cancelTapped:sender];
    }
}

- (void)reloadTapped:(id)sender {
    [self.webView reload];
}

- (void)cancelTapped:(id)sender {
    // Dismiss if presented modally, otherwise pop if in nav stack, otherwise do nothing
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else if (self.navigationController) {
        if (self.navigationController.viewControllers.firstObject != self) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            // At root — dismiss as fallback
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    } else {
        // no nav controller, no presenting — remove view or do nothing
        NSLog(@"Cancel tapped but no presenting or navigation controller available");
    }
}

#pragma mark - KVO for navigation state

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView) {
        if ([keyPath isEqualToString:@"canGoBack"]) {
            BOOL canGoBack = self.webView.canGoBack;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.backButton.enabled = canGoBack;
            });
        } else if ([keyPath isEqualToString:@"canGoForward"]) {
            // You could add forward button if desired
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - Optional: update toolbar on finish

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // Keep UI in sync as a fallback
    self.backButton.enabled = webView.canGoBack;
}

@end
