import type { EventClickArg, EventInput } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin, {
	type DateClickArg,
} from '@fullcalendar/interaction';
import FullCalendar from '@fullcalendar/react';
import { useEffect, useMemo, useState } from '@wordpress/element';
import type { ReactNode } from 'react';

import {
	field,
	safeArray,
	safeRecord,
	type AdminData,
	type AdminRecord,
} from '../admin-data';
import { itemTargetKey, targetHistoryRows } from '../item-history-helpers';
import { friendlyStatusCard } from '../launch-detail-helpers';
import { buildDesignSystemViewModel } from './view-model';
import { formatFriendlyDateTime, formatFriendlyFieldLabel } from './format';
import { SectionHead } from './DesignSystemSection';
import { ChangeDiff } from './composites/ChangeDiff';
import { Countdown } from './composites/Countdown';
import { DataTable } from './composites/DataTable';
import { RowList } from './composites/RowList';
import { CompatibilityMatrix } from './composites/CompatibilityMatrix';
import { EmptyState } from './primitives/EmptyState';
import { Button } from './primitives/Button';
import { Card } from './primitives/Card';
import { LoadingState, Skeleton } from './primitives/LoadingState';
import { StatusBadge } from './primitives/StatusBadge';
import { Toast } from './composites/Toast';
import { IconifyIcon, type ScheduledChangesIconName } from './iconify';
import { useLaunchDetail } from './hooks/useLaunchDetail';
import { useToast } from './hooks/useToast';
import {
	selectNextChange,
	selectLaunchRows,
	selectSupportedAreas,
	toLaunchRow,
	type CompatibilityRow,
	type LaunchRow,
} from './selectors';
import type { DesignSystemViewModel } from './types';

const PRODUCT_SCREEN_SECTIONS: Record< string, string[] > = {
	'schedule-center': [ 'overview' ],
	'all-changes': [ 'changes' ],
	calendar: [ 'calendar' ],
	targets: [ 'supported-areas' ],
	recordings: [ 'recordings' ],
	'runs-logs': [ 'history' ],
	notifications: [ 'notifications' ],
	settings: [ 'settings' ],
	'system-status': [ 'system-status' ],
	modules: [ 'modules' ],
};

const PRODUCT_PAGE_CLASS = 'view active scds-product-grid';
const PRODUCT_LAUNCH_PAGE_SIZE = 10;
const PRODUCT_NAV_ORDER = [
	'schedule-center',
	'all-changes',
	'calendar',
	'targets',
	'recordings',
	'runs-logs',
	'notifications',
	'settings',
	'system-status',
	'modules',
];
const VISIBLE_PRODUCT_NAV_SCREENS = new Set( PRODUCT_NAV_ORDER );
const HIDDEN_PRODUCT_NAV_SCREENS = new Set( [ 'design-system' ] );

const productSectionIds = ( screen: string ): string[] =>
	PRODUCT_SCREEN_SECTIONS[ screen ] ||
	PRODUCT_SCREEN_SECTIONS[ 'schedule-center' ];

const productLaunchPageWindow = (
	currentPage: number,
	totalPages: number
): number[] => {
	const length = Math.min( 5, totalPages );
	const start = Math.min(
		Math.max( 1, currentPage - Math.floor( length / 2 ) ),
		Math.max( 1, totalPages - length + 1 )
	);

	return Array.from( { length }, ( _, index ) => start + index );
};

const BurgerIcon = () => (
	<svg
		width="20"
		height="20"
		viewBox="0 0 24 24"
		stroke="#2c3338"
		strokeWidth="2"
	>
		<path d="M3 6h18M3 12h18M3 18h18" strokeLinecap="round" />
	</svg>
);

const CollapseIcon = ( { collapsed }: { collapsed: boolean } ) => (
	<svg
		width="18"
		height="18"
		viewBox="0 0 24 24"
		aria-hidden="true"
		focusable="false"
	>
		<path
			d={ collapsed ? 'M9 6l6 6-6 6' : 'M15 6l-6 6 6 6' }
			fill="none"
			stroke="currentColor"
			strokeLinecap="round"
			strokeLinejoin="round"
			strokeWidth="2"
		/>
	</svg>
);

const NAV_ICONS: Record< string, ScheduledChangesIconName > = {
	'schedule-center': 'dashboard',
	'all-changes': 'list',
	calendar: 'calendar',
	targets: 'target',
	recordings: 'copy',
	'runs-logs': 'history',
	notifications: 'notification',
	settings: 'settings',
	'system-status': 'protect',
	modules: 'module',
};

const NavIcon = ( { id }: { id: string } ) => (
	<IconifyIcon
		className="nav-icon scds-iconify-icon"
		fallbackClassName="nav-icon scds-nav-icon-fallback"
		name={ NAV_ICONS[ id ] || 'list' }
	/>
);

const BrandLogoGlyph = ( { model }: { model: DesignSystemViewModel } ) => {
	const fallback = model.brandLogoFallbackUrl || model.brandLogoUrl;
	const [ preferredLogo, setPreferredLogo ] = useState( fallback );

	useEffect( () => {
		setPreferredLogo( fallback );

		if (
			'undefined' === typeof window ||
			! model.brandLogoUrl ||
			model.brandLogoUrl === fallback
		) {
			return;
		}

		let active = true;
		const image = new window.Image();
		image.onload = () => {
			if ( active ) {
				setPreferredLogo( model.brandLogoUrl );
			}
		};
		image.onerror = () => {
			if ( active ) {
				setPreferredLogo( fallback );
			}
		};
		image.src = model.brandLogoUrl;

		return () => {
			active = false;
		};
	}, [ fallback, model.brandLogoUrl ] );

	return (
		<div className="glyph">
			{ fallback ? (
				<img src={ preferredLogo || fallback } alt="" />
			) : (
				<IconifyIcon
					name="protect"
					fallbackClassName="scds-sidebar-glyph-fallback"
				/>
			) }
		</div>
	);
};

const fallbackOverviewTarget = (): number =>
	Date.now() + ( 2 * 86400 + 4 * 3600 + 12 * 60 ) * 1000;

const overviewTargetMs = ( value: string ): number => {
	const normalized = value ? value.replace( ' ', 'T' ) : '';
	const parsed = normalized ? Date.parse( normalized ) : Number.NaN;

	return Number.isFinite( parsed ) ? parsed : fallbackOverviewTarget();
};

const productScreenHref = (
	model: DesignSystemViewModel,
	screen: string,
	fallback: string
): string => {
	const item = model.navigation.find(
		( navigationItem ) => field( navigationItem, 'id' ) === screen
	);

	return field( item || {}, 'href', fallback );
};

const launchStartMs = ( launch: AdminRecord ): number => {
	const value = field( launch, 'startAt', field( launch, 'scheduledAt' ) );
	const normalized = value ? value.replace( ' ', 'T' ) : '';
	const parsed = normalized ? Date.parse( normalized ) : Number.NaN;

	return Number.isFinite( parsed ) ? parsed : Number.POSITIVE_INFINITY;
};

const calendarDayFromLocation = (): string => {
	if ( 'undefined' === typeof window ) {
		return '';
	}

	const value = new URLSearchParams( window.location.search ).get(
		'calendar_day'
	);

	return value && /^\d{4}-\d{2}-\d{2}$/.test( value ) ? value : '';
};

const pushCalendarDayRoute = ( day: string ): void => {
	if ( 'undefined' === typeof window || ! window.history ) {
		return;
	}

	const url = new URL( window.location.href );
	if ( day ) {
		url.searchParams.set( 'calendar_day', day );
	} else {
		url.searchParams.delete( 'calendar_day' );
	}

	window.history.pushState(
		{
			...( 'object' === typeof window.history.state &&
			null !== window.history.state
				? window.history.state
				: {} ),
			scheduledChangesCalendarDay: day,
		},
		'',
		url.toString()
	);
};

const dateKeyFromValue = ( value: string ): string => {
	if ( /^\d{4}-\d{2}-\d{2}/.test( value ) ) {
		return value.slice( 0, 10 );
	}

	const parsed = value ? Date.parse( value.replace( ' ', 'T' ) ) : Number.NaN;

	return Number.isFinite( parsed )
		? new Date( parsed ).toISOString().slice( 0, 10 )
		: '';
};

const firstDateKey = ( row: AdminRecord, keys: string[] ): string => {
	for ( const key of keys ) {
		const dateKey = dateKeyFromValue( field( row, key ) );
		if ( dateKey ) {
			return dateKey;
		}
	}

	return '';
};

interface ProductDetailRoute {
	type: 'change' | 'recording';
	uuid: string;
}

interface DetailProps {
	model: DesignSystemViewModel;
	detailRoute: ProductDetailRoute;
	onBack: () => void;
	onOpenItemSchedules: ( target: AdminRecord ) => void;
}

const statusTone = ( value: string ) => {
	if ( /success|ready|active|valid|complete|rollback/.test( value ) ) {
		return 'success';
	}
	if ( /fail|error|unsupported/.test( value ) ) {
		return 'failed';
	}
	return 'scheduled';
};

const cleanDetailValue = ( value: unknown ): string =>
	String( value ?? '' )
		.replace( /^"|"$/g, '' )
		.replace( /^\[redacted\]$/, '' );

const changeRowsFrom = ( rows: AdminRecord[] ) =>
	rows.map( ( row, index ) => {
		const sensitive =
			true === row.sensitive ||
			'[redacted]' === field( row, 'before' ) ||
			'[redacted]' === field( row, 'after' );

		return {
			id: field( row, 'id', String( index ) ),
			field: formatFriendlyFieldLabel(
				field(
					row,
					'field',
					field( row, 'label', field( row, 'fieldId' ) )
				)
			),
			before: sensitive
				? ''
				: cleanDetailValue(
						field(
							row,
							'before',
							field(
								row,
								'previousValue',
								field( row, 'oldValue' )
							)
						)
				  ),
			after: sensitive
				? ''
				: cleanDetailValue(
						field(
							row,
							'after',
							field( row, 'nextValue', field( row, 'newValue' ) )
						)
				  ),
			sensitive,
			supported: 'unsupported' !== field( row, 'validation' ),
		};
	} );

const detailChanges = ( detail: AdminRecord | null ): AdminRecord[] => {
	const direct = safeArray< AdminRecord >( detail?.changes );
	if ( direct.length ) {
		return direct;
	}

	return safeArray< AdminRecord >( detail?.operations );
};

const findLaunch = (
	model: DesignSystemViewModel,
	uuid: string
): AdminRecord => {
	const matches = [ ...model.launches, ...model.calendar ].find(
		( launch ) =>
			field( launch, 'uuid' ) === uuid || field( launch, 'id' ) === uuid
	);

	return matches || { uuid };
};

const findRecording = (
	model: DesignSystemViewModel,
	uuid: string
): AdminRecord => {
	const matches = model.recordings.find(
		( recording ) =>
			field( recording, 'uuid' ) === uuid ||
			field( recording, 'id' ) === uuid
	);

	return matches || { uuid };
};

const normalizedItemValue = ( value: unknown ): string =>
	String( value ?? '' )
		.trim()
		.toLowerCase();

const itemScheduleValues = ( record: AdminRecord ): string[] => [
	field( record, 'targetReference' ),
	field( record, 'reference' ),
	field( record, 'targetId' ),
	field( record, 'id' ),
	field( record, 'primaryItemName' ),
	field( record, 'name' ),
	field( record, 'title' ),
];

const launchScheduleValues = ( launch: AdminRecord ): string[] => [
	...itemScheduleValues( launch ),
	...safeArray< AdminRecord >( launch.targets ).flatMap( itemScheduleValues ),
];

const schedulesForTarget = (
	model: DesignSystemViewModel,
	target: AdminRecord
): AdminRecord[] => {
	const targetValues = new Set(
		itemScheduleValues( target )
			.map( normalizedItemValue )
			.filter( Boolean )
	);
	const historyRows = targetHistoryRows( target );
	const matchedLaunches = model.launches.filter( ( launch ) =>
		launchScheduleValues( launch ).some( ( value ) =>
			targetValues.has( normalizedItemValue( value ) )
		)
	);
	const seen = new Set< string >();

	return [ ...historyRows, ...matchedLaunches ].filter( ( launch, index ) => {
		const key =
			field( launch, 'uuid' ) ||
			field( launch, 'id' ) ||
			`${ field( launch, 'name' ) }-${ field(
				launch,
				'startAt'
			) }-${ index }`;

		if ( seen.has( key ) ) {
			return false;
		}

		seen.add( key );
		return true;
	} );
};

const isLiteProfile = ( model: DesignSystemViewModel ): boolean =>
	'lite' === model.entitlementProfile;

const liteAddOnRows = (): CompatibilityRow[] => [
	{
		name: 'Posts and Pages',
		detail: 'Included for WordPress titles, content, status, featured images, categories, tags, dates, and hierarchy.',
		status: 'ok',
	},
	{
		name: 'WooCommerce',
		detail: 'Included for WooCommerce product scheduling in this package.',
		status: 'ok',
	},
	{
		name: 'Advanced Custom Fields',
		detail: 'ACF field scheduling is coming soon as a focused addon.',
		status: 'soon',
	},
];

const catalogSearchText = ( row: AdminRecord ): string =>
	[
		'slug',
		'name',
		'moduleName',
		'description',
		'coverageSummary',
		'group',
		'sourcePackage',
		'extensionPluginFile',
	]
		.map( ( key ) => field( row, key ) )
		.join( ' ' )
		.toLowerCase();

const catalogHas = ( rows: AdminRecord[], needles: string[] ): boolean =>
	rows.some( ( row ) => {
		const text = catalogSearchText( row );
		return needles.some( ( needle ) => text.includes( needle ) );
	} );

const addonRowsFromCatalog = (
	model: DesignSystemViewModel
): CompatibilityRow[] => {
	const rows = model.adapters;
	const postsReady = catalogHas( rows, [
		'native wordpress',
		'posts',
		'pages',
		'categories',
		'tags',
	] );
	const wooReady = catalogHas( rows, [
		'scheduled changes for woocommerce',
		'woocommerce',
	] );
	const acfReady = catalogHas( rows, [ 'advanced custom fields', 'acf' ] );

	return [
		{
			name: 'Posts and Pages',
			detail: postsReady
				? 'Ready for native WordPress titles, content, status, images, categories, tags, dates, and hierarchy.'
				: 'Native post and page scheduling appears here when the core modules are available.',
			status: postsReady ? 'ok' : 'off',
		},
		{
			name: 'WooCommerce',
			detail: wooReady
				? 'Ready for WooCommerce product scheduling, including product data, variations, inventory, pricing, media, and recording workspaces.'
				: 'Enable WooCommerce when product scheduling is needed.',
			status: wooReady ? 'ok' : 'off',
		},
		{
			name: 'Advanced Custom Fields',
			detail: acfReady
				? 'ACF addon detected for field ownership and scheduling support.'
				: 'ACF field scheduling is coming soon as a focused addon.',
			status: acfReady ? 'ok' : 'soon',
		},
	];
};

const ProductTableEmptyState = ( {
	title = 'No scheduled changes yet',
	body = 'Record a change from a post or page, then save the recording to schedule it.',
	action,
}: {
	title?: string;
	body?: string;
	action?: ReactNode;
} ) => (
	<div className="table-card scds-empty-table">
		<div className="empty">
			<div className="e-ic" aria-hidden="true">
				<IconifyIcon name="calendar" />
			</div>
			<h4>{ title }</h4>
			<p>{ body }</p>
			{ action ? (
				<div style={ { marginTop: 'var(--s-4)' } }>{ action }</div>
			) : null }
		</div>
	</div>
);

const ProductLaunchDataTable = ( {
	rows,
	onOpenChangeDetail,
	emptyTitle,
	emptyBody,
	emptyAction,
}: {
	rows: LaunchRow[];
	onOpenChangeDetail: ( uuid: string ) => void;
	emptyTitle?: string;
	emptyBody?: string;
	emptyAction?: ReactNode;
} ) => {
	if ( ! rows.length ) {
		return (
			<ProductTableEmptyState
				title={ emptyTitle }
				body={ emptyBody }
				action={ emptyAction }
			/>
		);
	}

	return (
		<DataTable
			rows={ rows }
			rowKey={ ( row ) => row.uuid }
			columns={ [
				{
					key: 'target',
					header: 'Target',
					render: ( row ) => (
						<>
							<div className="t-name">{ row.name }</div>
							<div className="t-sub">{ row.reference }</div>
						</>
					),
				},
				{
					key: 'status',
					header: 'Status',
					render: ( row ) => (
						<StatusBadge tone={ row.statusTone }>
							{ row.statusLabel }
						</StatusBadge>
					),
				},
				{
					key: 'go-live',
					header: 'Go-live',
					render: ( row ) => row.goLive,
				},
				{
					key: 'details',
					header: 'Action',
					className: 'num action-col',
					render: ( row ) => (
						<div className="row-actions">
							<Button
								variant="ghost"
								size="tiny"
								onClick={ () => onOpenChangeDetail( row.uuid ) }
								disabled={ ! row.uuid }
							>
								Details
							</Button>
						</div>
					),
				},
			] }
		/>
	);
};

const ProductOverview = ( {
	model,
	onOpenChangeDetail,
}: {
	model: DesignSystemViewModel;
	onOpenChangeDetail: ( uuid: string ) => void;
} ) => {
	const next = selectNextChange( model );
	const nextRow = next ? toLaunchRow( model, next ) : null;
	const overviewLaunchRows = selectLaunchRows( model ).slice( 0, 5 );
	const allChangesHref = productScreenHref(
		model,
		'all-changes',
		'admin.php?page=jjs-scheduler-list'
	);
	const targetMs = overviewTargetMs( field( next || {}, 'startAt' ) );

	return (
		<>
			<SectionHead
				kicker="Overview"
				title={
					model.applicationName || "JJ's Post and Product Scheduler"
				}
				summary="See what is planned, what needs attention, and where to go next."
			/>

			<Card
				className="glassy pad callout lift"
				style={ { marginBottom: 'var(--s-5)' } }
			>
				<div>
					<div className="lead-lbl">Next scheduled change</div>
					<div className="lead-title">
						{ nextRow?.name || 'No scheduled change yet' }
					</div>
					<div className="lead-meta">
						<StatusBadge
							tone={ nextRow?.statusTone || 'scheduled' }
						>
							{ nextRow?.statusLabel || 'Not scheduled' }
						</StatusBadge>
						<span>
							{ nextRow?.reference ||
								'Record a change to get started' }
						</span>
						<span>-</span>
						<span>
							{ nextRow?.goLive ||
								formatFriendlyDateTime(
									'2026-06-25T09:00:00'
								) }
						</span>
					</div>
					<div className="cta">
						<Button
							variant="primary"
							size="tiny"
							disabled={ ! nextRow }
							onClick={ () => {
								if ( nextRow ) {
									onOpenChangeDetail( nextRow.uuid );
								}
							} }
						>
							View details
						</Button>
					</div>
				</div>
				<Countdown targetMs={ targetMs } />
			</Card>

			<Card
				className="glassy pad lift"
				style={ { marginBottom: 'var(--s-5)' } }
			>
				<div className="subhead-row">
					<div className="subhead">Recent activity</div>
					<Button
						variant="secondary"
						size="tiny"
						href={ allChangesHref }
					>
						Load more
					</Button>
				</div>
				<ProductLaunchDataTable
					rows={ overviewLaunchRows }
					onOpenChangeDetail={ onOpenChangeDetail }
					emptyTitle="No recent activity yet"
					emptyBody="Scheduled, completed, failed, canceled, and restored changes will appear here after your first recording."
				/>
			</Card>
		</>
	);
};

const ProductLaunchTable = ( {
	model,
	onOpenChangeDetail,
}: {
	model: DesignSystemViewModel;
	onOpenChangeDetail: ( uuid: string ) => void;
} ) => {
	const rows = selectLaunchRows( model );
	const [ page, setPage ] = useState( 1 );
	const actualTotalPages = Math.max(
		1,
		Math.ceil( rows.length / PRODUCT_LAUNCH_PAGE_SIZE )
	);
	const displayTotalPages =
		rows.length >= PRODUCT_LAUNCH_PAGE_SIZE
			? Math.max( actualTotalPages, 5 )
			: actualTotalPages;
	const currentPage = Math.min( page, actualTotalPages );
	const visiblePages = productLaunchPageWindow(
		currentPage,
		displayTotalPages
	);
	const pagedRows =
		actualTotalPages > 1
			? rows.slice(
					( currentPage - 1 ) * PRODUCT_LAUNCH_PAGE_SIZE,
					currentPage * PRODUCT_LAUNCH_PAGE_SIZE
			  )
			: rows;

	return (
		<>
			<SectionHead
				kicker="Scheduled changes"
				title="Every scheduled change"
				summary="Review what is planned, what already ran, and what needs attention."
			/>
			<ProductLaunchDataTable
				rows={ pagedRows }
				onOpenChangeDetail={ onOpenChangeDetail }
				emptyTitle="No scheduled changes yet"
				emptyBody="Open a post or page, start recording, make the edit, then save the recording to choose when it goes live."
			/>
			{ displayTotalPages > 1 && (
				<div
					className="card glassy pad scds-list-pagination"
					style={ { display: 'flex', justifyContent: 'center' } }
				>
					<div className="pg-dots">
						<button
							type="button"
							aria-label="Previous page"
							disabled={ currentPage <= 1 }
							onClick={ () =>
								setPage( Math.max( 1, currentPage - 1 ) )
							}
						>
							‹
						</button>
						<div className="pg-dots-row">
							{ visiblePages.map( ( pageNumber ) => {
								const loadedPage =
									pageNumber <= actualTotalPages;

								return (
									<button
										type="button"
										key={ pageNumber }
										aria-label={ `Page ${ pageNumber }` }
										aria-current={
											pageNumber === currentPage
												? 'page'
												: undefined
										}
										aria-disabled={
											loadedPage ? undefined : true
										}
										className={
											pageNumber === currentPage
												? 'is-on'
												: ''
										}
										onClick={ () => {
											if ( loadedPage ) {
												setPage( pageNumber );
											}
										} }
									></button>
								);
							} ) }
						</div>
						<button
							type="button"
							aria-label="Next page"
							disabled={ currentPage >= actualTotalPages }
							onClick={ () =>
								setPage(
									Math.min(
										actualTotalPages,
										currentPage + 1
									)
								)
							}
						>
							›
						</button>
					</div>
				</div>
			) }
		</>
	);
};

const ProductCalendar = ( {
	model,
	onOpenChangeDetail,
}: {
	model: DesignSystemViewModel;
	onOpenChangeDetail: ( uuid: string ) => void;
} ) => {
	const [ selectedDay, setSelectedDay ] = useState( calendarDayFromLocation );
	const futureCalendarItems = model.calendar.filter( ( item ) => {
		const startMs = launchStartMs( item );

		return Number.isFinite( startMs ) && startMs >= Date.now();
	} );
	const dayItems = selectedDay
		? futureCalendarItems.filter(
				( item ) =>
					firstDateKey( item, [ 'startDate', 'startAt' ] ) ===
					selectedDay
		  )
		: [];
	const dayRows = dayItems.map( ( item ) => toLaunchRow( model, item ) );
	const events: EventInput[] = futureCalendarItems.map( ( item ) => {
		const row = toLaunchRow( model, item );

		return {
			id: row.uuid,
			title: row.name,
			start: field( item, 'startAt', field( item, 'startDate' ) ),
			classNames: [ 'scds-fc-event', `ev-${ row.statusTone }` ],
			extendedProps: { uuid: row.uuid },
		};
	} );

	if ( ! futureCalendarItems.length ) {
		return (
			<EmptyState
				title="No calendar items yet"
				body="Scheduled changes will appear here by date."
			/>
		);
	}

	const selectDay = ( arg: DateClickArg ) => {
		setSelectedDay( arg.dateStr );
		pushCalendarDayRoute( arg.dateStr );
	};
	const selectEvent = ( eventClick: EventClickArg ) => {
		eventClick.jsEvent.preventDefault();
		const uuid = String(
			eventClick.event.extendedProps.uuid || eventClick.event.id || ''
		);
		if ( uuid ) {
			onOpenChangeDetail( uuid );
		}
	};
	const clearDay = () => {
		setSelectedDay( '' );
		pushCalendarDayRoute( '' );
	};

	if ( selectedDay ) {
		return (
			<>
				<SectionHead
					kicker="Calendar"
					title="Every scheduled change"
					summary={ `Scheduled for ${ selectedDay }.` }
					action={
						<Button
							variant="secondary"
							size="tiny"
							onClick={ clearDay }
						>
							Back to calendar
						</Button>
					}
				/>
				<ProductLaunchDataTable
					rows={ dayRows }
					onOpenChangeDetail={ onOpenChangeDetail }
					emptyTitle="No scheduled changes on this day"
					emptyBody="Pick another day from the calendar, or record a new change for this date."
				/>
			</>
		);
	}

	return (
		<>
			<SectionHead
				kicker="Calendar"
				title="Calendar"
				summary="Click a day to see everything scheduled for it. Click an item to open its full change detail page."
			/>
			<Card className="glassy pad scds-fc-card">
				<FullCalendar
					plugins={ [ dayGridPlugin, interactionPlugin ] }
					initialView="dayGridMonth"
					events={ events }
					dateClick={ selectDay }
					eventClick={ selectEvent }
					dayMaxEvents={ 3 }
					displayEventTime={ false }
					fixedWeekCount={ false }
					height="auto"
					headerToolbar={ {
						left: 'prev,next today',
						center: 'title',
						right: '',
					} }
					eventContent={ ( eventInfo ) => (
						<span>{ eventInfo.event.title }</span>
					) }
				/>
			</Card>
		</>
	);
};

const ProductRecordings = ( {
	model,
	onOpenRecordingDetail,
}: {
	model: DesignSystemViewModel;
	onOpenRecordingDetail: ( uuid: string ) => void;
} ) => {
	const rows = model.recordings;

	return (
		<>
			<SectionHead
				kicker="Record a change"
				title="Recordings"
				summary="Review safe copies, captured field changes, and cleanup state before scheduling."
			/>
			<DataTable
				rows={ rows }
				rowKey={ ( row ) => field( row, 'uuid', field( row, 'id' ) ) }
				columns={ [
					{
						key: 'source',
						header: 'Item',
						render: ( row ) => (
							<>
								<div className="t-name">
									{ field( row, 'sourceTitle', 'Recording' ) }
								</div>
								<div className="t-sub">
									{ field( row, 'sourceTypeLabel', 'Item' ) }
								</div>
							</>
						),
					},
					{
						key: 'status',
						header: 'Status',
						render: ( row ) => (
							<StatusBadge
								tone={ statusTone( field( row, 'status' ) ) }
							>
								{ field( row, 'status', 'active' ) }
							</StatusBadge>
						),
					},
					{
						key: 'changes',
						header: 'Changes',
						className: 'num',
						render: ( row ) =>
							field(
								row,
								'selectedCount',
								field( row, 'changeCount', '0' )
							),
					},
					{
						key: 'cleanup',
						header: 'Cleanup',
						render: ( row ) =>
							field( row, 'cleanupStatus', 'pending' ),
					},
					{
						key: 'actions',
						header: 'Actions',
						render: ( row ) => (
							<Button
								variant="ghost"
								onClick={ () =>
									onOpenRecordingDetail(
										field( row, 'uuid', field( row, 'id' ) )
									)
								}
							>
								Details
							</Button>
						),
					},
				] }
			/>
		</>
	);
};

const ProductTargets = ( { model }: { model: DesignSystemViewModel } ) => {
	const areas = isLiteProfile( model )
		? liteAddOnRows()
		: selectSupportedAreas( model );

	return (
		<>
			<SectionHead
				kicker="Addons"
				title="Addons"
				summary="See which site areas are ready now and which ones need an addon or manual review."
			/>
			{ areas.length ? (
				<CompatibilityMatrix rows={ areas } variant="grid" />
			) : (
				<EmptyState
					title="No supported areas found"
					body="Supported areas will appear here after providers report what they can schedule."
				/>
			) }
		</>
	);
};

const ProductHistory = ( {
	model,
	onOpenChangeDetail,
}: {
	model: DesignSystemViewModel;
	onOpenChangeDetail: ( uuid: string ) => void;
} ) => {
	const rows = model.runs;

	return (
		<>
			<SectionHead
				kicker="History"
				title="Run history"
				summary="Review each run, what happened, and open the scheduled change behind it."
			/>
			<DataTable
				rows={ rows }
				rowKey={ ( row ) => field( row, 'uuid', field( row, 'id' ) ) }
				columns={ [
					{
						key: 'change',
						header: 'Change',
						render: ( row ) => (
							<>
								<div className="t-name">
									{ field(
										row,
										'launchName',
										'Scheduled change'
									) }
								</div>
								<div className="t-sub">
									{ formatFriendlyDateTime(
										field(
											row,
											'startedAt',
											field( row, 'scheduledAt' )
										)
									) }
								</div>
							</>
						),
					},
					{
						key: 'status',
						header: 'Status',
						render: ( row ) => (
							<StatusBadge
								tone={ statusTone( field( row, 'status' ) ) }
							>
								{ field( row, 'status', 'run' ) }
							</StatusBadge>
						),
					},
					{
						key: 'summary',
						header: 'Summary',
						render: ( row ) =>
							field( row, 'summary', 'Run details' ),
					},
					{
						key: 'actions',
						header: 'Actions',
						render: ( row ) => (
							<Button
								variant="ghost"
								onClick={ () =>
									onOpenChangeDetail(
										field( row, 'launchUuid' )
									)
								}
								disabled={ ! field( row, 'launchUuid' ) }
							>
								Details
							</Button>
						),
					},
				] }
			/>
		</>
	);
};

const ProductNotifications = ( {
	model,
}: {
	model: DesignSystemViewModel;
} ) => {
	const preferenceRows = safeArray< AdminRecord >(
		model.notificationPreferences.events
	);
	const notificationRows = model.notifications;

	return (
		<>
			<SectionHead
				kicker="Notifications"
				title="Notifications"
				summary="Review delivery preferences and recent notification results."
			/>
			<div style={ { display: 'grid', gap: 'var(--s-5)' } }>
				<div>
					<div className="subhead">Delivery preferences</div>
					{ preferenceRows.length ? (
						<DataTable
							rows={ preferenceRows }
							rowKey={ ( row ) =>
								field( row, 'value', field( row, 'label' ) )
							}
							columns={ [
								{
									key: 'event',
									header: 'Event',
									render: ( row ) => (
										<>
											<div className="t-name">
												{ field( row, 'label' ) }
											</div>
											<div className="t-sub">
												{ field(
													row,
													'description',
													'Notification event'
												) }
											</div>
										</>
									),
								},
								{
									key: 'status',
									header: 'Status',
									render: ( row ) => (
										<StatusBadge
											tone={
												true === row.enabled
													? 'success'
													: 'scheduled'
											}
										>
											{ true === row.enabled
												? 'Enabled'
												: 'Off' }
										</StatusBadge>
									),
								},
							] }
						/>
					) : (
						<EmptyState
							title="No notification preferences yet"
							body="Notification preferences will appear here when notification delivery is enabled."
						/>
					) }
				</div>
				<div>
					<div className="subhead">Recent results</div>
					{ notificationRows.length ? (
						<DataTable
							rows={ notificationRows }
							rowKey={ ( row ) =>
								field(
									row,
									'id',
									field(
										row,
										'uuid',
										`${ field( row, 'event' ) }-${ field(
											row,
											'createdAt'
										) }`
									)
								)
							}
							columns={ [
								{
									key: 'event',
									header: 'Event',
									render: ( row ) => (
										<>
											<div className="t-name">
												{ field(
													row,
													'eventLabel',
													field(
														row,
														'event',
														'Notification'
													)
												) }
											</div>
											<div className="t-sub">
												{ field(
													row,
													'launchName',
													field(
														row,
														'targetLabel',
														'Scheduled change'
													)
												) }
											</div>
										</>
									),
								},
								{
									key: 'status',
									header: 'Status',
									render: ( row ) => (
										<StatusBadge
											tone={ statusTone(
												field( row, 'status' )
											) }
										>
											{ field(
												row,
												'statusLabel',
												field( row, 'status', 'Sent' )
											) }
										</StatusBadge>
									),
								},
								{
									key: 'time',
									header: 'Time',
									render: ( row ) =>
										formatFriendlyDateTime(
											field(
												row,
												'createdAt',
												field( row, 'sentAt' )
											)
										),
								},
							] }
						/>
					) : (
						<EmptyState
							title="No notification results yet"
							body="Notification delivery attempts will appear here after scheduled changes run."
						/>
					) }
				</div>
			</div>
		</>
	);
};

const systemValue = (
	rows: AdminRecord[],
	label: string,
	fallback = 'Not reported'
): string => {
	const row = rows.find( ( item ) => field( item, 'label' ) === label );

	return field( row || {}, 'value', fallback );
};

const ProductSystemStatus = ( { model }: { model: DesignSystemViewModel } ) => {
	const diagnosticRows = [
		...model.featureDiagnostics,
		...model.ownershipCollisions,
		...model.schedulerDiagnostics,
	];

	return (
		<>
			<SectionHead
				kicker="Help & System Check"
				title="Help & System Check"
				summary="Review scheduler health, runtime facts, and compatibility diagnostics."
			/>
			<div className="stats-grid">
				<Card className="glassy pad">
					<div className="kicker">Queue health</div>
					<h3>{ systemValue( model.system, 'Queue health' ) }</h3>
				</Card>
				<Card className="glassy pad">
					<div className="kicker">Action Scheduler</div>
					<h3>{ systemValue( model.system, 'Action Scheduler' ) }</h3>
				</Card>
				<Card className="glassy pad">
					<div className="kicker">WordPress</div>
					<h3>{ systemValue( model.system, 'WordPress' ) }</h3>
				</Card>
			</div>
			<div style={ { display: 'grid', gap: 'var(--s-5)' } }>
				<div>
					<div className="subhead">System facts</div>
					{ model.system.length ? (
						<DataTable
							rows={ model.system }
							rowKey={ ( row ) => field( row, 'label' ) }
							columns={ [
								{
									key: 'label',
									header: 'Check',
									render: ( row ) => field( row, 'label' ),
								},
								{
									key: 'value',
									header: 'Value',
									render: ( row ) => field( row, 'value' ),
								},
							] }
						/>
					) : (
						<EmptyState
							title="No system facts reported"
							body="System checks will appear here when diagnostics are available."
						/>
					) }
				</div>
				<div>
					<div className="subhead">Diagnostics</div>
					{ diagnosticRows.length ? (
						<DataTable
							rows={ diagnosticRows }
							rowKey={ ( row ) =>
								field(
									row,
									'id',
									field(
										row,
										'key',
										field(
											row,
											'label',
											field( row, 'name' )
										)
									)
								)
							}
							columns={ [
								{
									key: 'name',
									header: 'Diagnostic',
									render: ( row ) => (
										<>
											<div className="t-name">
												{ field(
													row,
													'label',
													field(
														row,
														'name',
														'Diagnostic'
													)
												) }
											</div>
											<div className="t-sub">
												{ field(
													row,
													'description',
													field( row, 'summary' )
												) }
											</div>
										</>
									),
								},
								{
									key: 'status',
									header: 'Status',
									render: ( row ) => (
										<StatusBadge
											tone={ statusTone(
												field( row, 'status' )
											) }
										>
											{ field(
												row,
												'statusLabel',
												field( row, 'status', 'Ready' )
											) }
										</StatusBadge>
									),
								},
							] }
						/>
					) : (
						<EmptyState
							title="No diagnostics need attention"
							body="Compatibility and scheduler diagnostics will appear here when something needs review."
						/>
					) }
				</div>
			</div>
		</>
	);
};

const ProductModules = ( { model }: { model: DesignSystemViewModel } ) => {
	const rows = isLiteProfile( model )
		? liteAddOnRows()
		: addonRowsFromCatalog( model );

	return (
		<>
			<SectionHead
				kicker="Addons"
				title="Addons"
				summary="Review the high-level scheduling areas available on this site."
			/>
			{ rows.length ? (
				<CompatibilityMatrix rows={ rows } variant="grid" />
			) : (
				<EmptyState
					title="No addons reported"
					body="Addon availability will appear here when compatibility data is available."
				/>
			) }
		</>
	);
};

const ProductSettings = ( { model }: { model: DesignSystemViewModel } ) => {
	const approvalRequired =
		true === model.settingsState.requireApprovalBeforeScheduling;

	return (
		<>
			<SectionHead
				kicker="Settings"
				title="Scheduling preferences"
				summary="Manage review policy and safe defaults without exposing internal diagnostics."
			/>
			<div style={ { display: 'grid', gap: 'var(--s-5)' } }>
				<Card className="glassy pad scds-workflow-card">
					<div className="subhead-row">
						<div>
							<div className="subhead">Workflow review</div>
							<p className="scds-settings-policy">
								Choose whether scheduled changes need approval
								before they can run.
							</p>
						</div>
						<StatusBadge
							tone={ approvalRequired ? 'scheduled' : 'success' }
						>
							{ approvalRequired
								? 'Approval required'
								: 'Direct scheduling' }
						</StatusBadge>
					</div>
					<p className="scds-settings-policy">
						Users with scheduling permission can record a change,
						schedule it, and let it run at the planned time.
					</p>
				</Card>
			</div>
		</>
	);
};

const ProductChangeDetail = ( {
	model,
	detailRoute,
	onBack,
	onOpenItemSchedules,
}: DetailProps ) => {
	const seedLaunch = findLaunch( model, detailRoute.uuid );
	const detailState = useLaunchDetail( model, detailRoute.uuid );
	const detailLaunch = safeRecord( detailState.detail?.launch );
	const launch = Object.keys( detailLaunch ).length
		? detailLaunch
		: seedLaunch;
	const row: LaunchRow = toLaunchRow( model, launch );
	const changes = changeRowsFrom( detailChanges( detailState.detail ) );
	const targets = safeArray< AdminRecord >( detailState.detail?.targets );
	const runs = safeArray< AdminRecord >( detailState.detail?.runs );
	const statusCard = friendlyStatusCard( launch );

	return (
		<>
			<SectionHead
				kicker="Scheduled change detail"
				title={ row.name }
				summary="Everything that will change, where it applies, and what happened when this run executed."
			/>
			<article
				className={ `ef-card is-${ statusCard.tone } is-wide scds-detail-friendly-status` }
				data-scds-item-label={ statusCard.title }
				style={ { marginBottom: 'var(--s-5)' } }
			>
				<div className="ef-card-head">
					<span className="ef-kicker">{ statusCard.kicker }</span>
					<span className="ef-glow" aria-hidden="true"></span>
				</div>
				<h3>{ statusCard.title }</h3>
				<p>{ statusCard.body }</p>
				{ statusCard.confetti && (
					<div className="ef-confetti" aria-hidden="true">
						<span></span>
						<span></span>
						<span></span>
					</div>
				) }
			</article>
			<Card className="glassy pad lift">
				<div
					style={ {
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'space-between',
						gap: 'var(--s-3)',
						marginBottom: 'var(--s-4)',
					} }
				>
					<div>
						<div className="subhead">At a glance</div>
						<p className="token-note">
							{ row.reference } - { row.goLive } -{ ' ' }
							{ row.timezone || 'site timezone' }
						</p>
					</div>
					<div style={ { display: 'flex', gap: '8px' } }>
						<StatusBadge tone={ row.statusTone }>
							{ row.statusLabel }
						</StatusBadge>
						<Button variant="ghost" size="tiny" onClick={ onBack }>
							Back
						</Button>
					</div>
				</div>
				{ detailState.loading && (
					<LoadingState label="Loading change details">
						<Skeleton lines={ 4 } />
					</LoadingState>
				) }
				{ detailState.error && (
					<p className="token-note">{ detailState.error }</p>
				) }
				<div className="subhead">Exactly what changes</div>
				{ ! detailState.loading && (
					<>
						{ changes.length ? (
							<ChangeDiff rows={ changes } />
						) : (
							<p className="token-note">
								No saved field-level changes were returned for
								this scheduled change.
							</p>
						) }
					</>
				) }
			</Card>
			<Card className="glassy pad" style={ { marginTop: 'var(--s-5)' } }>
				<div className="subhead">Affected items</div>
				{ targets.length ? (
					<RowList
						rows={ targets.map( ( target, index ) => ( {
							id: itemTargetKey( target, index ),
							title: field(
								target,
								'name',
								field( target, 'title', 'Affected item' )
							),
							subtitle: field(
								target,
								'typeLabel',
								field( target, 'providerLabel', 'Item' )
							),
							trail: <span className="lr-chev">›</span>,
							ariaLabel: `View schedules for ${ field(
								target,
								'name',
								field( target, 'title', 'this item' )
							) }`,
							onClick: () => onOpenItemSchedules( target ),
						} ) ) }
					/>
				) : (
					<p className="token-note">
						Affected item details appear after the change detail
						payload loads.
					</p>
				) }
			</Card>
			<Card className="glassy pad" style={ { marginTop: 'var(--s-5)' } }>
				<div className="subhead">Run history</div>
				{ runs.length ? (
					<DataTable
						rows={ runs }
						rowKey={ ( run ) =>
							field( run, 'uuid', field( run, 'id' ) )
						}
						columns={ [
							{
								key: 'status',
								header: 'Status',
								render: ( run ) => (
									<StatusBadge
										tone={ statusTone(
											field( run, 'status' )
										) }
									>
										{ field( run, 'status', 'run' ) }
									</StatusBadge>
								),
							},
							{
								key: 'started',
								header: 'Started',
								render: ( run ) =>
									formatFriendlyDateTime(
										field(
											run,
											'startedAt',
											field( run, 'scheduledAt', '-' )
										)
									),
							},
							{
								key: 'summary',
								header: 'Summary',
								render: ( run ) =>
									field( run, 'summary', 'Run details' ),
							},
						] }
					/>
				) : (
					<p className="token-note">
						Run details appear after this change starts running.
					</p>
				) }
			</Card>
		</>
	);
};

const ProductItemSchedulesPage = ( {
	model,
	target,
	onBack,
	onOpenChangeDetail,
}: {
	model: DesignSystemViewModel;
	target: AdminRecord;
	onBack: () => void;
	onOpenChangeDetail: ( uuid: string ) => void;
} ) => {
	const targetName = field(
		target,
		'name',
		field( target, 'title', 'item' )
	);
	const rows = schedulesForTarget( model, target ).map( ( launch ) =>
		toLaunchRow( model, launch )
	);

	return (
		<>
			<SectionHead
				kicker="Affected item"
				title={ `Schedules for ${ targetName }` }
				summary="Every scheduled change related to this item."
				action={
					<Button variant="secondary" size="tiny" onClick={ onBack }>
						Back
					</Button>
				}
			/>
			<ProductLaunchDataTable
				rows={ rows }
				onOpenChangeDetail={ onOpenChangeDetail }
				emptyTitle="No schedules found for this item"
				emptyBody="When this item is scheduled, completed, failed, canceled, or restored, it will appear here."
			/>
		</>
	);
};

const ProductRecordingDetail = ( {
	model,
	detailRoute,
	onBack,
}: DetailProps ) => {
	const recording = findRecording( model, detailRoute.uuid );
	const changes = changeRowsFrom(
		safeArray< AdminRecord >( recording.changes )
	);

	return (
		<>
			<SectionHead
				kicker="Recording detail"
				title={ field( recording, 'sourceTitle', 'Recording' ) }
				summary="Everything captured on the safe copy before it becomes a scheduled change."
			/>
			<Card className="glassy pad lift">
				<div
					style={ {
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'space-between',
						gap: 'var(--s-3)',
						marginBottom: 'var(--s-4)',
					} }
				>
					<div>
						<div className="subhead">Safe copy</div>
						<p className="token-note">
							{ field(
								recording,
								'workspaceTitle',
								'Workspace'
							) }{ ' ' }
							- { field( recording, 'cleanupStatus', 'pending' ) }
						</p>
					</div>
					<div style={ { display: 'flex', gap: '8px' } }>
						<StatusBadge
							tone={ statusTone( field( recording, 'status' ) ) }
						>
							{ field( recording, 'status', 'active' ) }
						</StatusBadge>
						<Button variant="ghost" size="tiny" onClick={ onBack }>
							Back
						</Button>
					</div>
				</div>
				<div className="subhead">Exactly what changed</div>
				{ changes.length ? (
					<ChangeDiff rows={ changes } />
				) : (
					<p className="token-note">
						No field-level changes were captured for this recording.
					</p>
				) }
			</Card>
		</>
	);
};

const ProductDetailPage = ( props: DetailProps ) =>
	'recording' === props.detailRoute.type ? (
		<ProductRecordingDetail { ...props } />
	) : (
		<ProductChangeDetail { ...props } />
	);

/**
 * Product admin page assembled from shared admin assets, sections, and
 * primitives.
 * @param root0
 * @param root0.data
 * @param root0.currentScreen
 * @param root0.detailRoute
 * @param root0.onOpenChangeDetail
 * @param root0.onOpenRecordingDetail
 * @param root0.onCloseDetail
 */
export const SchedulerAdminApp = ( {
	data,
	currentScreen,
	detailRoute,
	onOpenChangeDetail,
	onOpenRecordingDetail,
	onCloseDetail,
}: {
	data: AdminData;
	currentScreen: string;
	detailRoute: ProductDetailRoute | null;
	onOpenChangeDetail: ( uuid: string ) => void;
	onOpenRecordingDetail: ( uuid: string ) => void;
	onCloseDetail: () => void;
} ) => {
	const [ drawerOpen, setDrawerOpen ] = useState( false );
	const [ sidebarCollapsed, setSidebarCollapsed ] = useState( false );
	const [ itemSchedulesTarget, setItemSchedulesTarget ] =
		useState< AdminRecord | null >( null );
	const model = useMemo( () => buildDesignSystemViewModel( data ), [ data ] );
	const toast = useToast();
	const selectedSectionIds = productSectionIds( currentScreen );
	const activeNavigation = model.navigation
		.map( ( item ) => ( {
			id: field( item, 'id' ),
			label: field( item, 'label' ),
			href: field( item, 'href', '#' ),
		} ) )
		.filter(
			( item ) =>
				VISIBLE_PRODUCT_NAV_SCREENS.has( item.id ) &&
				! HIDDEN_PRODUCT_NAV_SCREENS.has( item.id )
		)
		.sort(
			( left, right ) =>
				PRODUCT_NAV_ORDER.indexOf( left.id ) -
				PRODUCT_NAV_ORDER.indexOf( right.id )
		);

	useEffect( () => {
		setItemSchedulesTarget( null );
	}, [ currentScreen, detailRoute?.type, detailRoute?.uuid ] );

	let pageContent: ReactNode = (
		<EmptyState
			title="This page is not available yet."
			body="This product page is not available in the current admin phase."
		/>
	);

	if ( itemSchedulesTarget ) {
		pageContent = (
			<section id="item-schedules" className={ PRODUCT_PAGE_CLASS }>
				<ProductItemSchedulesPage
					model={ model }
					target={ itemSchedulesTarget }
					onBack={ () => setItemSchedulesTarget( null ) }
					onOpenChangeDetail={ onOpenChangeDetail }
				/>
			</section>
		);
	} else if ( detailRoute ) {
		pageContent = (
			<section
				id={ `detail-${ detailRoute.type }` }
				className={ PRODUCT_PAGE_CLASS }
			>
				<ProductDetailPage
					model={ model }
					detailRoute={ detailRoute }
					onBack={ onCloseDetail }
					onOpenItemSchedules={ setItemSchedulesTarget }
				/>
			</section>
		);
	} else if ( 'schedule-center' === currentScreen ) {
		pageContent = (
			<section id="overview" className={ PRODUCT_PAGE_CLASS }>
				<ProductOverview
					model={ model }
					onOpenChangeDetail={ onOpenChangeDetail }
				/>
			</section>
		);
	} else if ( 'all-changes' === currentScreen ) {
		pageContent = (
			<section id="changes" className={ PRODUCT_PAGE_CLASS }>
				<ProductLaunchTable
					model={ model }
					onOpenChangeDetail={ onOpenChangeDetail }
				/>
			</section>
		);
	} else if ( 'calendar' === currentScreen ) {
		pageContent = (
			<section id="calendar" className={ PRODUCT_PAGE_CLASS }>
				<ProductCalendar
					model={ model }
					onOpenChangeDetail={ onOpenChangeDetail }
				/>
			</section>
		);
	} else if ( 'targets' === currentScreen ) {
		pageContent = (
			<section id="supported-areas" className={ PRODUCT_PAGE_CLASS }>
				<ProductTargets model={ model } />
			</section>
		);
	} else if ( 'recordings' === currentScreen ) {
		pageContent = (
			<section id="recordings" className={ PRODUCT_PAGE_CLASS }>
				<ProductRecordings
					model={ model }
					onOpenRecordingDetail={ onOpenRecordingDetail }
				/>
			</section>
		);
	} else if ( 'runs-logs' === currentScreen ) {
		pageContent = (
			<section id="history" className={ PRODUCT_PAGE_CLASS }>
				<ProductHistory
					model={ model }
					onOpenChangeDetail={ onOpenChangeDetail }
				/>
			</section>
		);
	} else if ( 'notifications' === currentScreen ) {
		pageContent = (
			<section id="notifications" className={ PRODUCT_PAGE_CLASS }>
				<ProductNotifications model={ model } />
			</section>
		);
	} else if ( 'settings' === currentScreen ) {
		pageContent = (
			<section id="settings" className={ PRODUCT_PAGE_CLASS }>
				<ProductSettings model={ model } />
			</section>
		);
	} else if ( 'system-status' === currentScreen ) {
		pageContent = (
			<section id="system-status" className={ PRODUCT_PAGE_CLASS }>
				<ProductSystemStatus model={ model } />
			</section>
		);
	} else if ( 'modules' === currentScreen ) {
		pageContent = (
			<section id="modules" className={ PRODUCT_PAGE_CLASS }>
				<ProductModules model={ model } />
			</section>
		);
	}

	return (
		<div className="scds-reference scds-reference--sections">
			{ /* The scrim is a decorative backdrop; the drawer is also closed by
			   selecting a navigation link, so it carries no keyboard handler. */ }
			{ /* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */ }
			<div
				className={ drawerOpen ? 'scrim show' : 'scrim' }
				id="scrim"
				onClick={ () => setDrawerOpen( false ) }
			></div>
			<div
				className={
					sidebarCollapsed ? 'shell sidebar-collapsed' : 'shell'
				}
			>
				<aside
					className={ [
						'sidebar',
						drawerOpen ? 'open' : '',
						sidebarCollapsed ? 'collapsed' : '',
					]
						.filter( Boolean )
						.join( ' ' ) }
				>
					<div className="brandmark">
						<BrandLogoGlyph model={ model } />
						<div>
							<div className="name">
								{ model.applicationName ||
									"JJ's Post and Product Scheduler" }
							</div>
						</div>
						<button
							className="sidebar-toggle"
							type="button"
							aria-label={
								sidebarCollapsed
									? 'Expand sidebar'
									: 'Collapse sidebar'
							}
							aria-pressed={ sidebarCollapsed }
							onClick={ () =>
								setSidebarCollapsed(
									( collapsed ) => ! collapsed
								)
							}
						>
							<CollapseIcon collapsed={ sidebarCollapsed } />
						</button>
					</div>
					<div className="nav-group">
						{ activeNavigation.map( ( item ) => {
							const active = item.id === currentScreen;

							return (
								<a
									className={
										active ? 'nav-item active' : 'nav-item'
									}
									href={ item.href }
									aria-current={ active ? 'page' : undefined }
									aria-label={ item.label || item.id }
									key={ item.id || item.href }
									onClick={ () => setDrawerOpen( false ) }
								>
									<NavIcon id={ item.id } />
									<span className="nav-label">
										{ item.label || item.id }
									</span>
								</a>
							);
						} ) }
					</div>
				</aside>
				<main>
					<div className="topbar glass">
						<button
							className="burger"
							aria-label="Menu"
							type="button"
							onClick={ () => setDrawerOpen( true ) }
						>
							<BurgerIcon />
						</button>
						<BrandLogoGlyph model={ model } />
						<strong style={ { fontSize: '14px' } }>
							{ model.applicationName ||
								"JJ's Post and Product Scheduler" }
						</strong>
					</div>
					<div
						className="content"
						id="stage"
						data-scheduled-changes-product-sections={ selectedSectionIds.join(
							' '
						) }
					>
						{ pageContent }
					</div>
				</main>
			</div>
			<Toast message={ toast.message } visible={ toast.visible } />
		</div>
	);
};
