'use client';

import { usePathname } from 'next/navigation';

import { cn } from '@/lib/utils';
import { BackButton } from '@/components/layout/back-button';
import { useSmartBack } from '@/hooks/use-smart-back';
import { useMobileChrome } from './mobile-layout-provider';

/**
 * Fixed mobile topbar (56px + safe-area top inset). Marina-editorial premium:
 * deep-navy gradient surface with white type, a back arrow on the left when
 * there's a back affordance (otherwise a balancing spacer), and a soft glow
 * shadow underneath for depth instead of a hard divider line.
 *
 * Slots: title (auto-truncating), back arrow, primary action - all driven by
 * `useMobileChrome()` from the active page. When no page has set a title the
 * URL's last segment is title-cased as a fallback.
 */
export function MobileTopbar() {
  const { title, primaryAction } = useMobileChrome();
  const pathname = usePathname();
  // Mobile back affordance now derives from the same smart-back hook as
  // the desktop topbar so the destination is consistent across viewports
  // (and survives deep-link refresh). When useSmartBack returns null
  // (top-level pages) the brand-mark fallback renders in its place.
  const backTarget = useSmartBack();

  // UUID detection - the URL's last segment on detail pages is the
  // entity's UUID, and title-casing it produces an ugly "Abc 123 Uuid"
  // flash before the page calls `useMobileChrome.setChrome({title: ...})`
  // with the real entity name. When the segment matches the UUID shape,
  // walk back to the parent collection segment ("clients", "yachts",
  // "documents", …) which IS a clean, human-readable label.
  const segments = pathname.split('/').filter(Boolean);
  const last = segments[segments.length - 1] ?? '';
  const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(last);
  const fallbackSegment = isUuid ? segments[segments.length - 2] : last;
  // Derive a sensible title from the current path slug when no
  // page-level title is set. Avoids hardcoding a specific tenant name -
  // a fresh deploy with port slug `marina-alpha` reads as "Marina Alpha"
  // here without code edits.
  const portSlug = segments[0] ?? '';
  const portTitle = portSlug.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
  const fallbackTitle =
    fallbackSegment?.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()) ||
    portTitle ||
    'CRM';

  return (
    <header
      className={cn(
        'fixed top-0 inset-x-0 z-40',
        'bg-linear-to-b from-[#1e2844] to-[#171f35]',
        'shadow-[0_4px_18px_-6px_rgba(15,23,42,0.45)]',
        'h-[calc(56px+env(safe-area-inset-top))] pt-safe-top',
        'flex items-center gap-2 px-3',
      )}
    >
      {backTarget ? (
        <BackButton variant="mobile" />
      ) : (
        // No back affordance on top-level pages. Render an empty spacer the
        // same width as the right-hand action slot so the centered title
        // stays optically centered (the brand "PN" mark was removed here).
        <div className="size-11 shrink-0" aria-hidden />
      )}

      <h1
        className={cn(
          'flex-1 min-w-0 truncate text-center',
          'text-[17px] font-semibold tracking-tight text-white',
        )}
      >
        {title ?? fallbackTitle}
      </h1>

      <div className="size-11 inline-flex items-center justify-center text-white/95">
        {primaryAction}
      </div>
    </header>
  );
}
