import { ref } from 'vue'
import { canLeave, hasUnsaved } from './guard'

export type View =
  | 'dashboard'
  | 'apps'
  | 'plugins'
  | 'sites'
  | 'docker'
  | 'database'
  | 'waf'
  | 'files'
  | 'terminal'
  | 'ai'
  | 'security'
  | 'settings'

const views: View[] = [
  'dashboard',
  'apps',
  'plugins',
  'sites',
  'docker',
  'database',
  'waf',
  'files',
  'terminal',
  'ai',
  'security',
  'settings',
]

export interface RouteState {
  view: View
  /** Detail id carried by the hash, e.g. #/sites/12/logs */
  id?: number
  tab?: string
  query: URLSearchParams
}

function parseHash(hash: string): RouteState {
  const raw = hash.replace(/^#\/?/, '')
  const [pathPart, queryPart] = raw.split('?')
  const seg = pathPart.split('/').filter(Boolean)
  const candidate = seg[0] as View
  const view: View = views.includes(candidate) ? candidate : 'dashboard'
  const id = seg[1] && /^\d+$/.test(seg[1]) ? Number(seg[1]) : undefined
  const tab = seg[2] ? decodeURIComponent(seg[2]) : undefined
  return { view, id, tab, query: new URLSearchParams(queryPart ?? '') }
}

function toHash(route: RouteState): string {
  const seg: string[] = [route.view]
  if (route.id) seg.push(String(route.id))
  if (route.tab) seg.push(encodeURIComponent(route.tab))
  const qs = route.query.toString()
  return '#/' + seg.join('/') + (qs ? '?' + qs : '')
}

export const route = ref<RouteState>(parseHash(window.location.hash))

export function navigate(
  view: View,
  opts: { id?: number; tab?: string; query?: Record<string, string> } = {},
) {
  const next: RouteState = {
    view,
    id: opts.id,
    tab: opts.tab,
    query: new URLSearchParams(opts.query ?? {}),
  }
  if (!canLeave()) return
  route.value = next
  const hash = toHash(next)
  if (window.location.hash !== hash) window.location.hash = hash
  window.scrollTo({ top: 0, behavior: 'auto' })
}

/** Replace query parameters without adding a history entry. */
export function updateQuery(patch: Record<string, string | undefined>) {
  const q = new URLSearchParams(route.value.query)
  for (const [k, v] of Object.entries(patch)) {
    if (v === undefined || v === '') q.delete(k)
    else q.set(k, v)
  }
  route.value = { ...route.value, query: q }
  history.replaceState(null, '', toHash(route.value))
}

window.addEventListener('hashchange', () => {
  const next = parseHash(window.location.hash)
  // Our own navigate() already updated route; only real history moves get the
  // guard treatment.
  if (toHash(route.value) === window.location.hash) {
    route.value = next
    return
  }
  if (!canLeave()) {
    history.replaceState(null, '', toHash(route.value))
    return
  }
  route.value = next
  window.scrollTo({ top: 0, behavior: 'auto' })
})

window.addEventListener('beforeunload', (e) => {
  if (hasUnsaved()) {
    e.preventDefault()
    e.returnValue = ''
  }
})
