/*
 * last modified---
 * 	06-06-26 add DOM ids for browser automation support
 * 	03-14-25 reorganize Full Navigation Menu
 * 	02-25-25 add Dropdown menu for chain switching
 * 	07-16-24 add Staking menu
 *  12-29-23 add Greylisting to admin menu (greylistAdmin key)
 * 	12-05-23 add History link in top menu (to receipts.jsx page)
 * 	11-02-23 remove Connect Wallet link from offCanvas menu
 * 	09-14-23 add real (possibly temp) logo
 * 	07-19-23 remove Connect and network dropdown (now controlled from wallet)
 * 	07-18-23 set ChainConnection in caller (<Enshroud/>)
 * 	07-10-23 add enshMinting admin eventKey
 * 	05-31-23 add downloadMVOconfig()
 *
 * purpose---
 * 	supply menus for dApp
 */

import React from 'react';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import NavDropdown from 'react-bootstrap/NavDropdown';
import Offcanvas from 'react-bootstrap/Offcanvas';
import Dropdown from 'react-bootstrap/Dropdown';
import useEth from './EthContext/useEth';


/**
 * Component to render the top navigation bar with sub-menus
 * @param props.onSelect method to change page selection
 * @param props.activePage the currently active page
 * @param props.chainConfig the complete supported chain configurations
 * @param props.updateChain the method to change current chain or account
 */
function EnshNavbar(props) {
	// enable use of our connection and accounts
	const { state: { accounts, chainConn, web3 } } = useEth();

	if (accounts == null || chainConn == null) {
		// NB: this is normal on first render before chainConn gets established
		return;
	}

	// show account in shorthand
	const acct
		= accounts[0].substring(0, 7) + '...' + accounts[0].substring(37);

	// build list of supported chains for Dropdown menu
	const availChains = [];
	props.chainConfig.availConfigs.forEach((chainConf, key) => {
		let chainName = chainConf.chain;
		if (key === 1337) {
			chainName += " (Local Testnet)";
		}
		if (key === 11155111) {
			chainName += " (Ethereum Testnet)";
		}
		availChains.push({chName: chainName, chId: key});
	});

	// ask wallet software to switch chains
	async function switchChains(chainId) {
		// convert Id to hex
		const hexId = web3.utils.numberToHex(chainId);
		// ask wallet API to switch to this chain
		await window.ethereum.request({
			"method": "wallet_switchEthereumChain",
			"params": [{
				chainId: hexId
			}],
		})
		.then(res => {
			props.onSelect("home");
		})
		.catch(err => {
			alert("Chain switch failed: " + err.message);
		});
	}

	// set our parent to know about the current ChainConnection state
	// (does nothing if no change occurred)
	props.updateChain(chainConn, accounts[0]);

	return (
		<Container align="center" valign="top">
			<Navbar expand="none" fixed="top" variant="dark" bg="dark">
				<Container fluid>
					<Nav className="d-flex justify-content-start">
						{ /* right side offCanvas menu, left side of screen */ }
						<Navbar.Toggle aria-controls={'offcanvasNavbar-expand'} title="Menu toggle"/>
						<Navbar.Offcanvas
						 id='offcanvasNavbar-expand'
						 aria-labelledby={'offcanvasNavbarLabel-expand'}
						 placement="end"
						 className="text-bg-dark"
						 tabIndex="-1"
						 scroll="true"
						>
							<Offcanvas.Header closeButton="true" closeVariant="white">
								<Offcanvas.Title id={'offcanvasNavbarLabel-expand'}>
									Full Navigation Menu
								</Offcanvas.Title>
							</Offcanvas.Header>
							<Offcanvas.Body>
								<Nav variant="tabs"
									activeKey={props.activePage}
									onSelect={(selectedKey) => props.onSelect(selectedKey)}
								>
									<Nav.Link eventKey="home" id="offHome">Home</Nav.Link>
									<Nav.Link eventKey="depositAssets" id="offDeposit">Deposit Assets</Nav.Link>
									<Nav.Link eventKey="mintENFTs" id="offMint">Mint eNFTs</Nav.Link>
									<Nav.Link eventKey="spendENFTs" id="offSpend">Spend eNFTs</Nav.Link>
									<Nav.Link eventKey="burnENFTs" id="offBurn">Burn eNFTs</Nav.Link>
									<Nav.Link eventKey="receipts" id="offHistory">Transaction History</Nav.Link>
									<Nav.Link eventKey="assetConfig" id="offAssetConfig">Asset Config</Nav.Link>
									<Nav.Link eventKey="downloadWallet" id="offDownloadwallet">Backup Wallet</Nav.Link>
									<Nav.Link eventKey="restoreWallet" id="offRestoreWallet">Restore Wallet Backup</Nav.Link>
									<Nav.Link eventKey="daoStaking" id="offDaoStaking">User Staking</Nav.Link>
									<Nav.Link eventKey="mvoStaking" id="offMvoStaking">MVO Management</Nav.Link>
									<Nav.Link eventKey="crowdSale" id="offCrowdsale">Crowdsale</Nav.Link>
								</Nav>
							</Offcanvas.Body>
						</Navbar.Offcanvas>
					</Nav>

					{ /* regular navbar */ }
					<Nav className="flex-row flex-grow-1 justify-content-start"
						defaultActiveKey="home"
						onSelect={(selectedKey) => props.onSelect(selectedKey)}
					>
						<Navbar.Brand href="#" title="Enshroud Logo" className="navbar-brand p-1 m-1"><img src="images/eye-slash.svg" width="45" height="45" className="d-inline-block align-top" alt="Enshroud logo"/></Navbar.Brand>
						<Nav.Link eventKey="home" title="Home Page" className="p-2 m-2" id="goHome">Home</Nav.Link>
						<Nav.Link eventKey="depositAssets" title="Deposit assets to Enshroud smart contract" className="p-2 m-2" id="goDeposit">Deposit</Nav.Link>
						<Nav.Link eventKey="mintENFTs" title="Mint eNFTs from deposited assets" className="p-2 m-2" id="goMint">Mint</Nav.Link>
						<Nav.Link eventKey="spendENFTs" title="Spend eNFTs" className="p-2 m-2" id="goSpend">Spend</Nav.Link>
						<Nav.Link eventKey="burnENFTs" title="Redeem eNFTs for backing assets" className="p-2 m-2" id="goBurn">Burn</Nav.Link>
						<Nav.Link eventKey="receipts" title="Go to Transaction History" className="p-2 m-2" id="goHistory">History</Nav.Link>

						{ /* staking navbar */ }
						<NavDropdown title="Staking" id="stakingDropdown"
							className="p-2" menuVariant="dark"
						>
							<NavDropdown.Item eventKey="daoStaking" id="goDaoStaking">DAO Staking</NavDropdown.Item>
							<NavDropdown.Item eventKey="mvoStaking" id="goMvoStaking">MVO Staking</NavDropdown.Item>
							<NavDropdown.Item eventKey="crowdSale" id="goCrowdsale">Buy $ENSHROUD</NavDropdown.Item>
						</NavDropdown>

						{ /* admin navbar */ }
						<NavDropdown title="Admin" id="adminDropdown"
							className="p-2" menuVariant="dark"
						>
							<NavDropdown.Item eventKey="mvoConfig">MVO Config</NavDropdown.Item>
							<NavDropdown.Item eventKey="enshMinting">ENSHROUD Minting</NavDropdown.Item>
							<NavDropdown.Item eventKey="greylistAdmin">Greylisting</NavDropdown.Item>
						</NavDropdown>
					</Nav>
					{ /* drop-down selector for supported chains */ }
					<Dropdown align="end" data-bs-theme="dark"
						onSelect={(chId) => switchChains(chId)}
						activekey={chainConn.chainConfig.chainId}
						id="selectChain"
					>
						<Dropdown.Toggle variant="dark" id="chain-select"
							title="Select blockchain to connect to dApp"
						>
							Network
						</Dropdown.Toggle>
						<Dropdown.Menu>
							{availChains.map((chain) =>
								<Dropdown.Item eventKey={chain.chId} href="#"
									key={chain.chId}
									id={`chain-${chain.chName}`}
								>
									{chain.chName}
								</Dropdown.Item>
							)}
						</Dropdown.Menu>
					</Dropdown>
					<Nav className="flex-row flex-grow-1 justify-content-end">
						<Nav.Link href="#" title="Connected Network / Account" className="p-2 m-2" id="curChain">{chainConn.chainConfig.chain} / {acct}</Nav.Link>
					</Nav>
				</Container>
			</Navbar>
		</Container>
	);
}

export default EnshNavbar;
