import { setCurrentView, setDashboardTab, setMobileSidebar, setSelectedApp, setSelectedTab } from './state'

let _render: () => void

export function navigate(href: string) {
  history.pushState(null, '', href)
  route()
}

export function initRouter(render: () => void) {
  _render = render

  // Intercept link clicks
  document.addEventListener('click', e => {
    const a = (e.target as Element).closest('a')
    if (!a || !a.href || a.origin !== location.origin || a.target === '_blank') return
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
    e.preventDefault()
    history.pushState(null, '', a.href)
    route()
  })

  // Handle back/forward
  window.addEventListener('popstate', route)

  // Initial route from URL
  route()
}

function route() {
  setMobileSidebar(false)
  const path = location.pathname

  if (path.startsWith('/app/')) {
    const rest = decodeURIComponent(path.slice(5))
    const slashIdx = rest.indexOf('/')
    const name = slashIdx === -1 ? rest : rest.slice(0, slashIdx)
    const tab = slashIdx === -1 ? 'overview' : rest.slice(slashIdx + 1)
    setSelectedApp(name)
    setSelectedTab(name, tab)
    setCurrentView('dashboard')
  } else if (path === '/settings') {
    setSelectedApp(null)
    setCurrentView('settings')
  } else {
    setSelectedApp(null)
    const segment = path.slice(1)
    setDashboardTab(segment || 'urls')
    setCurrentView('dashboard')
  }

  _render()
}
