import { getLocalizedString } from "@olenbetong/appframe-core";
import type { DataObject } from "@olenbetong/appframe-data";

import { AppMenuUserMenu, type AppMenuUser } from "./AppMenuUserMenu.js";
import { CloseIcon, HomeIcon, ReloadIcon } from "./icons.js";
import type { AppMenuLink } from "./types.js";

export type AppMenuHeaderProps = {
	/** Link shown at the start of the header, e.g. the portal/front page. */
	homeLink?: AppMenuLink;
	/** Which pane is shown on narrow viewports. */
	mobilePane: "apps" | "groups";
	onToggleMobilePane: () => void;
	hasUpdate: boolean;
	onInstallUpdate?: () => void;
	userDataObject?: DataObject<AppMenuUser>;
	userMenuItems?: AppMenuLink[];
	userSubtitle?: string;
	onClose: () => void;
};

/**
 * Header of the app menu's content pane, holding the navigation shortcuts on
 * the start side and the user/update/close controls on the end side.
 *
 * It is rendered after the app list so it comes last in the tab order, and is
 * moved back to the top visually with `order: -1`.
 */
export function AppMenuHeader({
	homeLink,
	mobilePane,
	onToggleMobilePane,
	hasUpdate,
	onInstallUpdate,
	userDataObject,
	userMenuItems,
	userSubtitle,
	onClose,
}: AppMenuHeaderProps) {
	return (
		<div className="ob-app-menu__content-header">
			<div className="ob-app-menu__header-start">
				{homeLink && (
					<a
						className="ob-app-menu__home"
						href={homeLink.href}
						target={homeLink.target}
						rel={homeLink.rel}
						onClick={() => {
							homeLink.onClick?.();
							if (!homeLink.keepOpen) onClose();
						}}
					>
						<HomeIcon />
						<span className="ob-app-menu__home-label">{homeLink.label}</span>
					</a>
				)}
				<button type="button" className="ob-app-menu__pane-toggle" onClick={onToggleMobilePane}>
					{mobilePane === "apps" ? getLocalizedString("Categories") : getLocalizedString("Applications")}
				</button>
			</div>
			{hasUpdate && (
				<button
					type="button"
					className="ob-app-menu__update"
					aria-label={getLocalizedString("Install update and reload")}
					onClick={onInstallUpdate}
				>
					<ReloadIcon />
					<span className="ob-app-menu__update-label">{getLocalizedString("Install update and reload")}</span>
				</button>
			)}
			{userDataObject && <AppMenuUserMenu dataObject={userDataObject} items={userMenuItems} subtitle={userSubtitle} />}
			<button type="button" className="ob-app-menu__close" aria-label={getLocalizedString("Close")} onClick={onClose}>
				<CloseIcon />
			</button>
		</div>
	);
}
