/**
 * Minimaler Hash-Router
 * Kein Framework nötig — einfaches Hash-basiertes Routing.
 *
 * Routen:
 *   #/          → Landing Page
 *   #/sim/05    → Simulation 05 (Treibhauseffekt)
 *   #/sim/07    → Simulation 07 (Erdbeben)
 *   #/dashboard → Lehrkräfte-Dashboard (später)
 */

type RouteHandler = (params: Record<string, string>) => void

interface Route {
  pattern: RegExp
  handler: RouteHandler
}

export class Router {
  private routes: Route[] = []
  private currentCleanup: (() => void) | null = null

  constructor() {
    window.addEventListener('hashchange', () => this.resolve())
    window.addEventListener('load', () => this.resolve())
  }

  on(path: string, handler: RouteHandler): this {
    // Convert path like '/sim/:id' to regex
    const pattern = new RegExp(
      '^' + path.replace(/:[a-zA-Z]+/g, '([^/]+)') + '$'
    )
    this.routes.push({ pattern, handler })
    return this
  }

  navigate(path: string): void {
    window.location.hash = path
  }

  resolve(): void {
    const hash = window.location.hash.slice(1) || '/'

    for (const route of this.routes) {
      const match = hash.match(route.pattern)
      if (match) {
        // Cleanup previous view
        if (this.currentCleanup) {
          this.currentCleanup()
          this.currentCleanup = null
        }

        // Extract params
        const params: Record<string, string> = {}
        const paramNames = route.pattern.source.match(/\([^)]+\)/g) || []
        paramNames.forEach((_, i) => {
          params[`p${i}`] = match[i + 1]
        })

        route.handler(params)
        return
      }
    }
  }

  setCleanup(fn: () => void): void {
    this.currentCleanup = fn
  }
}
