'use client'

import { useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { ADMIN_HOME, adminWorkspaceForContext } from '@/lib/domain/modes'
import { viewAsFor } from '@/lib/domain/view-as'

/**
 * "Admin Preview: Carrier Dashboard — Exit Preview" (Nash, 2026-09-24, §40).
 * Shows only while an admin is inside a product view; nothing on admin pages.
 * Exiting clears the preview on the session, so it is a real state change and
 * not just a link.
 */
export function AdminPreviewBarClient() {
  const pathname = usePathname()
  const router = useRouter()
  const [busy, setBusy] = useState(false)
  const item = viewAsFor(pathname ?? '')
  if (!item || !item.context) return null
  const workspace = adminWorkspaceForContext(item.context)

  async function exitPreview() {
    setBusy(true)
    try {
      const r = await fetch('/api/modes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ op: 'exit_preview' }) })
      const json = await r.json().catch(() => ({}))
      router.push((json.next as string) ?? ADMIN_HOME)
      router.refresh()
    } catch {
      toast.error('Could not leave the preview.')
      setBusy(false)
    }
  }

  return (
    <div className="flex items-center justify-center gap-3 border-b bg-[#0f1b2d] px-4 py-1.5 text-center text-[11px] text-neutral-200">
      <span className="font-semibold text-[#f5a623]">Admin Preview</span>
      <span>{workspace?.label ?? item.label}</span>
      <span className="hidden text-neutral-400 sm:inline">No company role is created for you here.</span>
      <button onClick={exitPreview} disabled={busy} className="rounded-full border border-neutral-500 px-2.5 py-0.5 font-semibold text-white transition hover:bg-white/10 disabled:opacity-50">
        {busy ? 'Leaving…' : 'Exit Preview'}
      </button>
    </div>
  )
}
