"use strict";

const React = require("react");

const defaultStyle = require("./style.css");
const useTheme = require("../../util/themeable");
const isEventInsideRef = require("../../util/is-event-inside-ref");
const MenuItemContext = require("../../contexts/menu-item");

module.exports = function MenuBar({ style, children }) {
	let { withTheme } = useTheme({ control: "menu", defaultStyle });
	let [ isActive, setIsActive ] = React.useState(false);
	let [ selectedItem, setSelectedItem ] = React.useState([]);
	let element = React.useRef();
	
	React.useEffect(() => {
		function handleGlobalClick(event) {
			if (!isEventInsideRef(element, event)) {
				setIsActive(false);
			}
		}

		document.addEventListener("click", handleGlobalClick);

		return () => {
			document.removeEventListener("click", handleGlobalClick);
		};
	}, []);

	let itemContext = {
		menuType: "menuBar",
		selectedPath: selectedItem,
		isActive: isActive,
		onMouseEnter: (path) => {
			setSelectedItem(path);
		},
		onClick: (_path, hasMenu, isInMenu) => {
			// Only activate the menu bar if this *isn't* a direct-action button directly on the menubar
			if (hasMenu || isInMenu) {
				// NOTE: This is a toggle that sets isActive for the *whole* menu bar rather than an individual item, because pressing *any* button in the menu will trigger menu-display mode; after that, merely hovering over other buttons is enough to switch what menu is displayed.
				setIsActive((isActive) => !isActive);
			}
		}
	};

	return (
		<MenuItemContext.Provider value={itemContext}>
			<div className={withTheme("menuBar")} style={style} ref={element}>
				{children}
			</div>
		</MenuItemContext.Provider>
	);
};
