import Link from 'next/link'
import { UserMenu } from './user-menu'
import { AdminPreviewBar } from './admin-preview-bar'
import { EmailDeliveryBanner } from './email-delivery-banner'
import { getSessionUser } from '@/lib/auth'
import { loadActiveMode } from '@/lib/data/active-mode'
import { switchableContexts } from '@/lib/domain/modes'
import type { Profile } from '@/types/db'

export async function AppShell({ profile, children }: { profile: Profile; children: React.ReactNode }) {
  const user = await getSessionUser()
  const mode = await loadActiveMode()
  return (
    <div className="min-h-screen bg-neutral-50">
      <header className="sticky top-0 z-30 border-b bg-white">
        <div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4">
          {/* Mobile QA 2026-09-13: the nav lives in its own scrollable lane so
              "History" can never slide under the avatar on a phone. */}
          <div className="flex min-w-0 flex-1 items-center gap-4 sm:gap-5">
            <Link href="/dashboard" className="flex items-center gap-2">
              <span className="grid h-8 w-8 place-items-center rounded-lg bg-[#0f1b2d] text-sm font-extrabold text-[#f5a623]">
                H
              </span>
              <span className="hidden text-sm font-bold sm:block">HeavyHaul Agent</span>
            </Link>
            <nav className="flex min-w-0 items-center gap-3 overflow-x-auto whitespace-nowrap text-sm font-medium text-neutral-600 [scrollbar-width:none] sm:gap-4 [&::-webkit-scrollbar]:hidden">
              <Link href="/dashboard" className="hover:text-neutral-900">
                Dashboard
              </Link>
              {/* Estimator removed from the menu (Nash, 2026-09-22): "we don't have that
                  functionality yet… later maybe". src/app/estimator/ stays in the tree. */}
              <Link href="/billing" className="hover:text-neutral-900">
                Billing
              </Link>
              <Link href="/history" className="hover:text-neutral-900">
                History
              </Link>
            </nav>
          </div>
          <div className="flex shrink-0 items-center gap-3">
            <div className="hidden text-right sm:block">
              <p className="text-xs font-semibold leading-tight">{profile.full_name || profile.email}</p>
              <p className="text-[11px] capitalize text-neutral-500">{profile.default_role}</p>
            </div>
            <UserMenu name={profile.full_name || profile.email} role={user?.role ?? profile.default_role} surfaces={user?.surfaces} modes={mode ? switchableContexts(mode.contexts) : []} activeKey={mode?.active?.key ?? null} />
          </div>
        </div>
      </header>
      <AdminPreviewBar />
      <EmailDeliveryBanner email={profile.email} deliveryEmail={profile.delivery_email} />
      {children}
    </div>
  )
}
