import * as plugins from './plugins.js';
import * as appstate from './appstate.js';

const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;

export const validViews = [
  'dashboard', 'app-store', 'services', 'domains', 'dns-records', 'network',
  'registries', 'tokens', 'settings',
] as const;

export type TValidView = typeof validViews[number];

class AppRouter {
  private router: InstanceType<typeof SmartRouter>;
  private initialized = false;
  private suppressStateUpdate = false;

  constructor() {
    this.router = new SmartRouter({ debug: false });
  }

  public init(): void {
    if (this.initialized) return;
    this.setupRoutes();
    this.setupStateSync();
    this.handleInitialRoute();
    this.initialized = true;
  }

  private setupRoutes(): void {
    for (const view of validViews) {
      this.router.on(`/${view}`, async () => {
        this.updateViewState(view);
      });
    }

    // Root redirect
    this.router.on('/', async () => {
      this.navigateTo('/dashboard');
    });
  }

  private setupStateSync(): void {
    appstate.uiStatePart.select((s) => s.activeView).subscribe((activeView) => {
      if (this.suppressStateUpdate) return;

      const currentPath = window.location.pathname;
      const expectedPath = `/${activeView}`;

      if (currentPath !== expectedPath) {
        this.suppressStateUpdate = true;
        this.router.pushUrl(expectedPath);
        this.suppressStateUpdate = false;
      }
    });
  }

  private handleInitialRoute(): void {
    const path = window.location.pathname;

    if (!path || path === '/') {
      this.router.pushUrl('/dashboard');
    } else {
      const segments = path.split('/').filter(Boolean);
      const view = segments[0];

      if (validViews.includes(view as TValidView)) {
        this.updateViewState(view as TValidView);
      } else {
        this.router.pushUrl('/dashboard');
      }
    }
  }

  private updateViewState(view: string): void {
    this.suppressStateUpdate = true;
    const currentState = appstate.uiStatePart.getState();
    if (currentState.activeView !== view) {
      appstate.uiStatePart.setState({
        ...currentState,
        activeView: view,
      });
    }
    this.suppressStateUpdate = false;
  }

  public navigateTo(path: string): void {
    this.router.pushUrl(path);
  }

  public navigateToView(view: string): void {
    const normalized = view.toLowerCase().replace(/\s+/g, '-');
    if (validViews.includes(normalized as TValidView)) {
      this.navigateTo(`/${normalized}`);
    } else {
      this.navigateTo('/dashboard');
    }
  }

  public getCurrentView(): string {
    return appstate.uiStatePart.getState().activeView;
  }

  public destroy(): void {
    this.router.destroy();
    this.initialized = false;
  }
}

export const appRouter = new AppRouter();
