#import "FGRootViewController.h"
#import "FGMapViewController.h"
#import "FGSavedViewController.h"
#import "FGHistoryViewController.h"
#import "FGSettingsViewController.h"
#import "FGTheme.h"

@implementation FGRootViewController

+ (instancetype)makePanel {
    FGRootViewController *root = [[FGRootViewController alloc] init];
    [root buildTabs];
    return root;
}

- (void)buildTabs {
    FGMapViewController *map = [[FGMapViewController alloc] init];
    FGSavedViewController *saved = [[FGSavedViewController alloc] init];
    FGHistoryViewController *history = [[FGHistoryViewController alloc] init];
    FGSettingsViewController *settings = [[FGSettingsViewController alloc] init];

    NSArray<UIViewController *> *controllers = @[map, saved, history, settings];
    NSArray<NSString *> *titles = @[@"Bản đồ", @"Đã lưu", @"Lịch sử", @"Cài đặt"];
    NSArray<NSString *> *symbols = @[@"map", @"mappin.and.ellipse", @"clock.arrow.circlepath", @"gearshape"];

    NSMutableArray<UINavigationController *> *navigations = [NSMutableArray array];
    for (NSUInteger i = 0; i < controllers.count; i++) {
        UINavigationController *navigation =
            [[UINavigationController alloc] initWithRootViewController:controllers[i]];
        navigation.navigationBar.prefersLargeTitles = NO;
        navigation.navigationBar.tintColor = [FGTheme accent];

        UITabBarItem *item = [[UITabBarItem alloc]
            initWithTitle:titles[i]
                    image:[FGTheme symbolNamed:symbols[i] size:22 weight:UIFontWeightRegular]
                      tag:(NSInteger)i];
        navigation.tabBarItem = item;

        // Nút Đóng ở mọi tab để thoát nhanh khỏi panel.
        controllers[i].navigationItem.leftBarButtonItem =
            [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemClose
                                                          target:self
                                                          action:@selector(closeTapped)];

        [navigations addObject:navigation];
    }

    self.viewControllers = navigations;
    self.selectedIndex = 0;

    if (@available(iOS 15.0, *)) {
        UITabBarAppearance *appearance = [[UITabBarAppearance alloc] init];
        [appearance configureWithDefaultBackground];
        self.tabBar.standardAppearance = appearance;
        self.tabBar.scrollEdgeAppearance = appearance;
    }
    self.tabBar.tintColor = [FGTheme accent];
    self.view.backgroundColor = [FGTheme screenBackground];
}

- (void)closeTapped {
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FGPanelDidDismissNotification" object:nil];
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.isBeingDismissed || self.presentingViewController == nil) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FGPanelDidDismissNotification" object:nil];
    }
}

@end
