<script>
  import { onMount } from 'svelte'
  import { getSession, clearSession } from './db.js'
  import { syncPull, startSSE, startSyncLoop } from './sync.js'
  import Login from './pages/Login.svelte'
  import Dashboard from './pages/Dashboard.svelte'
  import Participants from './pages/Participants.svelte'
  import Volunteers from './pages/Volunteers.svelte'
  import Departments from './pages/Departments.svelte'
  import Users from './pages/Users.svelte'
  import Import from './pages/Import.svelte'
  import Kiosk from './pages/Kiosk.svelte'
  import VolunteerSignup from './pages/VolunteerSignup.svelte'
  import ConfirmEmail from './pages/ConfirmEmail.svelte'
  import GateUI from './pages/GateUI.svelte'
  import ScheduleBoard from './pages/ScheduleBoard.svelte'
  import Settings from './pages/Settings.svelte'
  import Nav from './components/Nav.svelte'
  import SyncStatus from './components/SyncStatus.svelte'

  const clientBuild = __BUILD_ID__

  let session = $state(null)
  let loading = $state(true)
  let route = $state(window.location.pathname)
  let updateAvailable = $state(false)
  let mobileNavOpen = $state(false)

  // Check if this is a public page (no auth needed)
  const kioskToken = $derived(route.match(/^\/v\/([A-Z0-9]+)/i)?.[1] ?? '')
  const isVolunteerSignup = $derived(route.startsWith('/volunteer-signup'))
  const isConfirmEmail = $derived(route.startsWith('/confirm/'))
  const isPublicPage = $derived(!!kioskToken || isVolunteerSignup || isConfirmEmail)

  function navigate(path) {
    history.pushState(null, '', path)
    route = path
    mobileNavOpen = false
  }

  async function checkVersion() {
    try {
      const res = await fetch('/api/version')
      const { build } = await res.json()
      if (build && build !== clientBuild) updateAvailable = true
    } catch {}
  }

  onMount(async () => {
    checkVersion()

    // Public pages don't need auth
    if (isPublicPage) {
      loading = false
      return
    }
    session = await getSession()
    loading = false
    if (session) {
      await syncPull()
      startSSE()
      startSyncLoop()
    }
    window.addEventListener('popstate', () => {
      route = window.location.pathname
      mobileNavOpen = false
    })

    // Periodically check for updates
    setInterval(checkVersion, 60000)
  })

  function onLogin(s) {
    session = s
    navigate('/')
    syncPull().then(() => { startSSE(); startSyncLoop() })
  }

  async function onLogout() {
    await clearSession()
    session = null
    navigate('/login')
  }

  const path = $derived(route || '/')
  const role = $derived(session?.user?.role ?? '')
</script>

{#if updateAvailable}
  <div class="update-banner">
    A new version is available.
    <button onclick={() => location.reload()}>Refresh</button>
  </div>
{/if}

{#if loading}
  <!-- checking session -->
{:else if kioskToken}
  <Kiosk />
{:else if isVolunteerSignup}
  <VolunteerSignup />
{:else if isConfirmEmail}
  <ConfirmEmail />
{:else if !session}
  <Login onlogin={onLogin} />
{:else if role === 'gatekeeper'}
  <!-- Gate users get the full-screen GateUI instead of the standard layout -->
  <GateUI {session} {onLogout} />
{:else}
  <div class="layout">
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    {#if mobileNavOpen}
      <div class="nav-overlay" onclick={() => mobileNavOpen = false} onkeydown={() => {}}></div>
    {/if}
    <Nav {session} {onLogout} {navigate} active={path} open={mobileNavOpen} />
    <div class="main">
      <header class="mobile-header">
        <button class="hamburger" onclick={() => mobileNavOpen = !mobileNavOpen} aria-label="Menu">
          <span></span><span></span><span></span>
        </button>
        <span class="mobile-brand">Turn<span class="accent">pike</span></span>
      </header>
      {#if path === '/' || path === ''}
        {#if role === 'colead'}
          <ScheduleBoard {session} />
        {:else}
          <Dashboard {session} />
        {/if}
      {:else if path.startsWith('/participants')}
        <Participants {session} />
      {:else if path.startsWith('/volunteers')}
        <Volunteers {session} />
      {:else if path.startsWith('/departments')}
        <Departments {session} />
      {:else if path.startsWith('/schedule')}
        <ScheduleBoard {session} />
      {:else if path.startsWith('/users')}
        <Users {session} />
      {:else if path.startsWith('/import')}
        <Import {session} />
      {:else if path.startsWith('/settings')}
        <Settings {session} />
      {:else}
        <div class="page"><p class="text-muted">Page not found.</p></div>
      {/if}
      <SyncStatus />
    </div>
  </div>
{/if}

<style>
  .update-banner {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 9999;
    padding: 8px 16px;
    background: var(--c-accent);
    color: white;
    text-align: center;
    font-size: 14px;
  }

  .update-banner button {
    margin-left: 12px;
    padding: 2px 12px;
    border: 1px solid rgba(255,255,255,0.5);
    border-radius: var(--radius);
    background: transparent;
    color: white;
    cursor: pointer;
    font-size: 14px;
  }

  .update-banner button:hover {
    background: rgba(255,255,255,0.15);
  }
</style>
