import React, { ReactNode } from 'react';
import styled from 'styled-components';

export interface PageHeaderProps {
  title: ReactNode;
  subtitle?: ReactNode;
  overline?: ReactNode;
  actions?: ReactNode;
  breadcrumbs?: ReactNode;
  /** When false, omit bottom margin (e.g. followed by in-page chrome). Default true. */
  spacingBottom?: boolean;
}

const HeaderWrap = styled.header<{ $spacingBottom: boolean }>`
  margin-bottom: ${({ theme, $spacingBottom }) =>
    $spacingBottom ? theme.layout.sectionGap : 0};
`;

const Breadcrumbs = styled.div`
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.tertiary};
`;

const Overline = styled.p`
  margin: 0 0 ${({ theme }) => theme.spacing[2]};
  font-size: 0.6875rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.widest};
  text-transform: uppercase;
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-align: start;
`;

const Row = styled.div`
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[6]};
  flex-wrap: wrap;
`;

const TextBlock = styled.div`
  min-width: 0;
  flex: 1;
`;

const Title = styled.h1`
  margin: 0;
  font-family: ${({ theme }) => theme.typography.fontFamily.headline};
  font-size: ${({ theme }) => theme.typography.fontSize['3xl']};
  font-weight: ${({ theme }) => theme.typography.fontWeight.bold};
  line-height: ${({ theme }) => theme.typography.lineHeight.heading};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.tight};
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: start;
`;

const Subtitle = styled.p`
  margin: ${({ theme }) => theme.spacing[2]} 0 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  line-height: ${({ theme }) => theme.typography.lineHeight.normal};
  text-align: start;
  max-width: 42rem;
`;

const Actions = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  flex-shrink: 0;
  flex-wrap: wrap;
`;

export const PageHeader: React.FC<PageHeaderProps> = ({
  title,
  subtitle,
  overline,
  actions,
  breadcrumbs,
  spacingBottom = true,
}) => (
  <HeaderWrap $spacingBottom={spacingBottom}>
    {breadcrumbs && <Breadcrumbs>{breadcrumbs}</Breadcrumbs>}
    {overline && <Overline>{overline}</Overline>}
    <Row>
      <TextBlock>
        <Title>{title}</Title>
        {subtitle && <Subtitle>{subtitle}</Subtitle>}
      </TextBlock>
      {actions && <Actions>{actions}</Actions>}
    </Row>
  </HeaderWrap>
);
