import { Group, Stack, Text, Title } from '@mantine/core';
import type { ReactNode } from 'react';

interface PageHeaderProps {
  /**
   * The page's name. A `ReactNode` rather than a string because detail pages
   * title themselves with the record they are showing, which is often a
   * localised or composed value rather than a literal.
   */
  title: ReactNode;
  subtitle?: ReactNode;
  /**
   * Identifiers that belong beside the title rather than under it — a
   * reference number, a status badge. Rendered inline, small and dimmed.
   */
  meta?: ReactNode;
  /** Right-aligned actions (e.g. a primary button). */
  action?: ReactNode;
  /**
   * Set when the header sits directly inside a gapped `<Stack>`, which already
   * spaces it from what follows — the built-in margin would double that gap.
   */
  noMargin?: boolean;
}

/**
 * The heading every backoffice page starts with.
 *
 * It exists because 25 pages each rolled their own: eight at `order={2}`,
 * seventeen at `order={3}`, with `mb="xs"`, `mb={4}`, `mb="lg"` and nothing at
 * all between them. Clicking between two screens moved the title, which is the
 * single loudest signal that a product was assembled rather than designed.
 *
 * `order={2}` is deliberate — it is the page's only `h2`, sitting under the
 * app-level `h1`, so the heading outline reads correctly for a screen reader.
 * Section headings inside cards stay at `order={4}`/`{5}` and are not this
 * component's business.
 */
export function PageHeader({ title, subtitle, meta, action, noMargin }: PageHeaderProps) {
  return (
    <Group
      justify="space-between"
      align="flex-end"
      wrap="wrap"
      gap="sm"
      mb={noMargin ? undefined : 'lg'}
    >
      <Stack gap={2}>
        <Group gap="sm" align="center" wrap="wrap">
          <Title order={2}>{title}</Title>
          {meta}
        </Group>
        {subtitle && (
          <Text c="dimmed" size="sm">
            {subtitle}
          </Text>
        )}
      </Stack>
      {action}
    </Group>
  );
}
