/* global React, Ico, MENU, NWO_ENDPOINTS */
const { useState, useEffect, useRef, useMemo } = React;

/* =========================================================
   SHELL: Header, Rail, Footer, AuthModal (wallet-only), Tweaks
   ========================================================= */

function Header({ walletAddr, onConnect, onDisconnect, onMenu }) {
  return (
    <header className="hdr">
      <div className="hdr-brand">
        <button className="rail-toggle-mobile btn-muted" onClick={onMenu} style={{padding:'6px 8px'}}>{Ico.menu({width:16,height:16})}</button>
        <img src="logo.jpg" alt="NWO" className="hdr-logo" onError={(e)=>{e.target.style.display='none'; e.target.nextSibling.style.display='flex';}}/>
        <div className="dot" style={{display:'none'}}/> 
        NWO<span className="sub"> CAPITAL</span>
      </div>
      <div className="hdr-center">
        <div className="hdr-stat api-status"><span className="status-dot-glow"></span><b>API V2.0 · LIVE</b></div>
      </div>
      <div className="hdr-right">
        {walletAddr ? (
          <button className="wallet-btn connected" onClick={onDisconnect} title={walletAddr}>
            {Ico.unlock({className:'unlock-ico'})}
            {walletAddr.slice(0,6)}…{walletAddr.slice(-4)}
          </button>
        ) : (
          <button className="wallet-btn" onClick={onConnect}>
            {Ico.lock({className:'lock-ico'})}
            Connect Wallet
          </button>
        )}
      </div>
    </header>
  );
}

function Rail({ active, onNav, open, setOpen }) {
  return (
    <nav className={'rail ' + (open ? 'open' : '')} onMouseLeave={()=>{ /* CSS handles hover */ }}>
      <div className="rail-inner">
        {MENU.map((item, idx) => {
          if (item.group) {
            return <div key={'g'+idx} className="rail-section-label">{item.group}</div>;
          }
          const IcoFn = Ico[item.icon] || Ico.dashboard;
          return (
            <div
              key={item.id}
              className={'rail-item ' + (item.lvl===1?'lvl-1 ':'') + (item.lvl===2?'lvl-2 ':'') + (active===item.id?'active':'')}
              onClick={(e)=>{ e.stopPropagation(); onNav(item); setOpen(false); }}
            >
              <span className="ico">{IcoFn({width:16,height:16})}</span>
              <span className="label">{item.label}</span>
              {item.private && <span className="lock" title="Wallet required">{Ico.lock({width:10,height:10})}</span>}
            </div>
          );
        })}
      </div>
    </nav>
  );
}

function Footer() {
  return (
    <footer className="ftr">
      <div className="ftr-left">© 2026 NWO Capital · All rights reserved by nwo.capital · Base Mainnet 8453</div>
      <div className="ftr-icons">
        <a className="ftr-ico" href="https://nwocardiac.cloud" target="_blank" title="NWO Cardiac">{Ico.heart()}</a>
        <a className="ftr-ico" href="https://nworobotics.cloud" target="_blank" title="NWO Robotics">{Ico.robot()}</a>
        <a className="ftr-ico" href="https://nwo.capital/webapp/ethics-engine.html" target="_blank" title="Ethics Engine">{Ico.scales()}</a>
        <a className="ftr-ico" href="https://nwoautobot.cloud" target="_blank" title="NWO Autobot">{Ico.bird()}</a>
        <a className="ftr-ico" href="mailto:state@nwo.capital" title="state@nwo.capital">{Ico.envelope()}</a>
        <a className="ftr-ico" href="https://x.com/nworobotics" target="_blank" title="x.com/nworobotics">{Ico.x()}</a>
      </div>
    </footer>
  );
}

/* ================ WALLET-ONLY CONNECT MODAL ================ */
/* No email/password. No register tab. No PHP backend.
   Single purpose: show a styled "Connect MetaMask" prompt with the
   boot animation, OR an "install MetaMask" hint if ethereum isn't found. */
function AuthModal({ onClose, onConnect, walletAvailable }) {
  const [boot, setBoot] = useState([]);
  const [connecting, setConnecting] = useState(false);

  useEffect(() => {
    const lines = [
      ['SYS', 'NWO CAPITAL // AUTH GATEWAY v2.0'],
      ['NET', 'base mainnet · chain 8453'],
      ['ORA', 'oracle hardware attestation: READY'],
      ['REL', 'relayer: online'],
      ['AUT', walletAvailable ? 'awaiting wallet signature...' : 'metamask not detected'],
    ];
    let i = 0;
    setBoot([]);
    const t = setInterval(() => {
      if (i >= lines.length) { clearInterval(t); return; }
      setBoot(b => [...b, lines[i]]);
      i++;
    }, 140);
    return () => clearInterval(t);
  }, [walletAvailable]);

  const handleConnect = async () => {
    setConnecting(true);
    try { await onConnect(); }
    finally { setConnecting(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()}>
        <div className="modal-chrome">
          <div className="modal-chrome-left">
            <div className="modal-chrome-dots"><span/><span/><span/></div>
            /bin/nwo-wallet-connect
          </div>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <div className="modal-boot">
            {boot.map((l, i) => l && (
              <span className="line" key={i}>
                <span className="k">[{l[0]}]</span> <span className="v">{l[1]}</span>
              </span>
            ))}
            <span className="cursor"/>
          </div>

          <div style={{
            margin:'18px 0 14px',
            padding:'14px',
            border:'1px solid var(--g-dim)',
            background:'rgba(0,0,0,0.25)',
            fontSize:11,
            lineHeight:1.6,
            color:'var(--text-dim)',
            fontFamily:'"Share Tech Mono", monospace'
          }}>
            <div style={{color:'var(--g-primary)', marginBottom:8, letterSpacing:'0.1em'}}>
              &gt; WALLET-ONLY AUTHENTICATION
            </div>
            NWO Capital uses your MetaMask wallet as your identity.
            No email. No password. No account creation.
            Your wallet address is your operator ID across the platform.
          </div>

          {walletAvailable ? (
            <button
              className="btn btn-primary"
              style={{width:'100%', marginBottom: 14}}
              onClick={handleConnect}
              disabled={connecting}
            >
              {Ico.wallet({width:16,height:16,style:{marginRight:8,verticalAlign:'middle'}})}
              {connecting ? 'Awaiting wallet signature…' : 'Connect MetaMask'}
            </button>
          ) : (
            <div>
              <button className="wallet-opt" disabled style={{opacity:0.6, cursor:'not-allowed'}}>
                <span>{Ico.wallet({width:18,height:18,style:{marginRight:10,verticalAlign:'middle'}})} MetaMask</span>
                <span className="meta">NOT FOUND</span>
              </button>
              <a
                href="https://metamask.io/download/"
                target="_blank"
                rel="noopener"
                className="btn btn-outline"
                style={{display:'block', textAlign:'center', marginTop:14, textDecoration:'none'}}
              >
                Install MetaMask →
              </a>
              <div style={{
                marginTop:14, fontSize:10, color:'var(--text-dim)',
                lineHeight:1.5, textAlign:'center'
              }}>
                After installing, refresh this page and click Connect Wallet.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ================ TWEAKS PANEL (unchanged) ================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "greenHue": 135,
  "scanOpacity": 0.03,
  "gridOpacity": 0.04,
  "fontBody": "Exo 2"
}/*EDITMODE-END*/;

function TweaksPanel({ tweaks, setTweaks, onClose }) {
  const up = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v }}, '*');
  };
  return (
    <div className="tweaks-panel">
      <h4>Tweaks <button onClick={onClose} style={{background:'transparent',border:'none',color:'var(--g-primary)',cursor:'pointer'}}>✕</button></h4>
      <div className="body">
        <div className="tweak-row">
          <div className="lab">Green hue <span>{tweaks.greenHue}°</span></div>
          <input type="range" min="80" max="200" value={tweaks.greenHue}
            onChange={e=>up('greenHue', +e.target.value)}/>
        </div>
        <div className="tweak-row">
          <div className="lab">Scan lines <span>{tweaks.scanOpacity.toFixed(2)}</span></div>
          <input type="range" min="0" max="0.15" step="0.01" value={tweaks.scanOpacity}
            onChange={e=>up('scanOpacity', +e.target.value)}/>
        </div>
        <div className="tweak-row">
          <div className="lab">Grid density <span>{tweaks.gridOpacity.toFixed(2)}</span></div>
          <input type="range" min="0" max="0.15" step="0.01" value={tweaks.gridOpacity}
            onChange={e=>up('gridOpacity', +e.target.value)}/>
        </div>
        <div className="tweak-row">
          <div className="lab">Body font</div>
          <select value={tweaks.fontBody} onChange={e=>up('fontBody', e.target.value)}>
            <option>Exo 2</option>
            <option>Inter</option>
            <option>Share Tech Mono</option>
            <option>Rajdhani</option>
          </select>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Header, Rail, Footer, AuthModal, TweaksPanel, TWEAK_DEFAULTS });
