'use client';
import { createContext, FunctionComponent, ReactNode, useContext, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { ROUTES } from '@/constants';
import { usePathname } from '@/i18n/navigation';

interface TitleEntry {
  path: string;
  key: string;
}

/**
 * Static route→title table (longest-prefix wins), read from the existing `nav` namespace — one
 * key per shell console/tab. Dynamic titles (a nurse's name, a booking reference) are layered on
 * top via `usePageTitleOverride`; the area phases (4-6, 9) wire those in, this phase ships the
 * static baseline.
 */
const TITLE_ENTRIES: TitleEntry[] = [
  // Customer — pushed routes only; the 5 root tabs render the brand lockup instead (see CUSTOMER_ROOT_TABS)
  { path: ROUTES.SEARCH, key: 'search' },
  { path: ROUTES.SEARCH_RESULTS, key: 'search' },
  { path: ROUTES.SEARCH_NURSE, key: 'search' },
  { path: ROUTES.BOOKING_REQUEST, key: 'bookings' },
  { path: ROUTES.CHECKOUT, key: 'checkout' },
  { path: ROUTES.BOOKINGS, key: 'bookings' },
  { path: ROUTES.PATIENTS, key: 'patients' },
  { path: ROUTES.ADDRESSES, key: 'addresses' },
  { path: ROUTES.WALLET, key: 'wallet' },
  { path: ROUTES.PROFILE, key: 'profile' },
  { path: ROUTES.SUPPORT_TICKETS, key: 'support' },
  { path: ROUTES.NOTIFICATIONS, key: 'notifications' },
  { path: ROUTES.ONBOARDING, key: 'home' },
  // Nurse
  { path: ROUTES.NURSE_REQUESTS, key: 'requests' },
  { path: ROUTES.NURSE_PROFILE, key: 'profile' },
  { path: ROUTES.NURSE_SERVICES, key: 'services' },
  { path: ROUTES.NURSE_COVERAGE, key: 'coverage' },
  { path: ROUTES.NURSE_BANK, key: 'bank' },
  { path: ROUTES.NURSE_VERIFICATION, key: 'verification' },
  { path: ROUTES.NURSE_VISITS, key: 'visits' },
  { path: ROUTES.NURSE_EARNINGS, key: 'earnings' },
  { path: ROUTES.NURSE_SUPPORT_TICKETS, key: 'support' },
  { path: ROUTES.NURSE_NOTIFICATIONS, key: 'notifications' },
  { path: ROUTES.NURSE, key: 'dashboard' },
  // Admin
  { path: ROUTES.ADMIN_VERIFICATION, key: 'verification' },
  { path: ROUTES.ADMIN_TICKETS, key: 'tickets' },
  { path: ROUTES.ADMIN_PAYOUTS, key: 'payouts' },
  { path: ROUTES.ADMIN_REVIEWS, key: 'reviews' },
  { path: ROUTES.ADMIN_CONFIG, key: 'config' },
  { path: ROUTES.ADMIN_HOLIDAYS, key: 'holidays' },
  { path: ROUTES.ADMIN_ALERTS, key: 'alerts' },
  { path: ROUTES.ADMIN_AUDIT, key: 'audit' },
  { path: ROUTES.ADMIN_PARTNERS, key: 'partners' },
  { path: ROUTES.ADMIN_ROLES, key: 'roles' },
  { path: ROUTES.ADMIN_USERS, key: 'users' },
  { path: ROUTES.ADMIN_NOTIFICATIONS, key: 'notifications' },
  { path: ROUTES.ADMIN, key: 'overview' },
  // Partner
  { path: ROUTES.PARTNER_NURSES, key: 'partner_nurses' },
  { path: ROUTES.PARTNER_BOOKINGS, key: 'partner_bookings' },
  { path: ROUTES.PARTNER_SETTLEMENT, key: 'partner_settlement' },
  { path: ROUTES.PARTNER, key: 'partner_home' },
].sort((a, b) => b.path.length - a.path.length);

function findTitleEntry(pathname: string): TitleEntry | undefined {
  return TITLE_ENTRIES.find((entry) =>
    entry.path === '/' ? pathname === entry.path : pathname === entry.path || pathname.startsWith(`${entry.path}/`)
  );
}

/** The customer shell's 5 root tabs — these render the brand lockup, never a title. */
export const CUSTOMER_ROOT_TABS: string[] = [ROUTES.HOME, ROUTES.BOOKINGS, ROUTES.PATIENTS, ROUTES.WALLET, ROUTES.PROFILE];

export function isCustomerRootTab(pathname: string): boolean {
  return CUSTOMER_ROOT_TABS.includes(pathname);
}

const PageTitleOverrideContext = createContext<string | null>(null);
const SetPageTitleOverrideContext = createContext<(title: string | null) => void>(() => {});

/**
 * Provides the per-page dynamic-title override slot. Mount once per shell (around the scrollable
 * content), above wherever `usePageTitleOverride`/`useRouteTitle` are read.
 * @component PageTitleProvider
 */
export const PageTitleProvider: FunctionComponent<{ children: ReactNode }> = ({ children }) => {
  const [override, setOverride] = useState<string | null>(null);
  return (
    <SetPageTitleOverrideContext.Provider value={setOverride}>
      <PageTitleOverrideContext.Provider value={override}>{children}</PageTitleOverrideContext.Provider>
    </SetPageTitleOverrideContext.Provider>
  );
};

/**
 * Lets a pushed-route page set a dynamic chrome header title (e.g. a nurse's name, a booking
 * reference) that wins over the static route→title map. Pass `null`/omit to clear. The override
 * is cleared automatically on unmount so navigating away never leaks a stale title.
 */
export function usePageTitleOverride(title: string | null | undefined) {
  const setOverride = useContext(SetPageTitleOverrideContext);
  useEffect(() => {
    setOverride(title ?? null);
    return () => setOverride(null);
  }, [title, setOverride]);
}

/** The current chrome header title: the per-page override if set, else the static route→title map. */
export function useRouteTitle(): string | null {
  const pathname = usePathname();
  const t = useTranslations('nav');
  const override = useContext(PageTitleOverrideContext);
  return useMemo(() => {
    if (override) return override;
    const entry = findTitleEntry(pathname);
    return entry ? t(entry.key) : null;
  }, [override, pathname, t]);
}
