import React from 'react';
import cx from 'classnames';
import { PageHeaderBody } from './components/headerBody';
import { PageHeaderBreadcrumbs } from './components/headerBreadcrumbs';
import { PageHeaderUnified } from './components/pageHeaderUnified';
import { CLASSNAME } from './constants';
import type { PageHeaderProps } from './types';

/**
 * PageHeader component is used to set the context of a page. It usually represents an object, or a list of objects. The information and call to actions displayed in the page header are all related to the object presented on the page.
 *
 * @type organism
 * @status revised
 * @tags layout-structure
 *
 * @nested Primary, Secondary, Tertiary, Description, Breadcrumb, ExternalLinks
 */
export function PageHeader(props: PageHeaderProps) {
    // Check if this should render as unified (has mainContent but no children)
    if ('mainContent' in props && props.mainContent) {
        return <PageHeaderUnified {...props} />;
    }

    const { children, className, style, testId } = props;

    if ('grid' in props && props.grid === true)
        return (
            <div
                className={cx(CLASSNAME, className, [`${CLASSNAME}-grid`])}
                style={style}
                data-testid={testId || 'PageHeader'}
            >
                {children}
            </div>
        );

    // Type guard: at this point it must be FlexProps (has children, no grid, no mainContent)
    const breadcrumbs = 'breadcrumbs' in props ? props.breadcrumbs : undefined;
    const coverArtProps = 'coverArt' in props ? props.coverArt : undefined;
    const description = 'description' in props ? props.description : undefined;
    const variant = 'variant' in props ? props.variant : undefined;

    return (
        <div
            className={cx(CLASSNAME, className, `${CLASSNAME}-flex`, {
                [`${CLASSNAME}-standalone`]: variant === 'standalone',
            })}
            style={style}
            data-testid={testId || 'PageHeader'}
        >
            {breadcrumbs && breadcrumbs.length > 1 && <PageHeaderBreadcrumbs items={breadcrumbs} />}
            <PageHeaderBody coverArt={coverArtProps} description={description}>
                {children}
            </PageHeaderBody>
        </div>
    );
}
