/* ============================================================
   ADMIN SHELL - login gate, sidebar, hash routing.
   Mounts only when location.hash starts with #/admin.
   The public site is never touched: AdminApp returns null off-route.
   ============================================================ */

function useHashRoute() {
  const [hash, setHash] = useState(window.location.hash || '');
  useEffect(() => {
    const on = () => setHash(window.location.hash || '');
    addEventListener('hashchange', on);
    return () => removeEventListener('hashchange', on);
  }, []);
  return hash;
}

/* ---------- Login gate (UI-only role assumption) ---------- */
function AdminLogin({ onAuth }) {
  const [pw, setPw] = useState('');
  const [err, setErr] = useState(false);
  const submit = () => {
    // UI assumption only - real auth is a backend concern.
    if (pw.trim() === "webes-admin-2026") onAuth();
    else setErr(true);
  };
  return (
    <div className="adm-login">
      <div className="light-pool purple" style={{ width: 520, height: 520, top: -160, left: '50%', transform: 'translateX(-50%)' }}/>
      <div className="adm-login-card">
        <GNGLogo size={52} />
        <div className="eyebrow" style={{ marginTop: 18 }}>- gang operations</div>
        <h2 className="adm-login-title">Admin Access</h2>
        <p className="adm-login-sub">Role-gated. Only gang ops crew past this door.</p>
        <input
          className="adm-input" type="password" placeholder="Access key"
          value={pw} onChange={e => { setPw(e.target.value); setErr(false); }}
          onKeyDown={e => e.key === 'Enter' && submit()}
        />
        {err && <div className="adm-login-err">No motion without the key.</div>}
        <button className="btn btn-spark" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }} onClick={submit}>
          Enter HQ <Arrow />
        </button>
        <a className="adm-login-back" href="#top">← back to the site</a>
      </div>
    </div>
  );
}

/* ---------- Sidebar ---------- */
function AdminSidebar({ route, go, live }) {
  const items = [
    { key: 'dash',   label: 'Dashboard',   icon: 'M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z' },
    { key: 'create', label: 'Create Event',icon: 'M12 5v14M5 12h14' },
    { key: 'schedule',label:'Schedule',     icon: 'M7 2v3M17 2v3M3 9h18M5 5h14v15H5z' },
    { key: 'review', label: 'Submissions',  icon: 'M4 6h16M4 12h16M4 18h10' },
    { key: 'live',   label: 'Live Control',  icon: 'M12 2a10 10 0 100 20 10 10 0 000-20zm0 5v5l3 3' },
    { key: 'stats',  label: 'Analytics',    icon: 'M4 20V10M10 20V4M16 20v-7M22 20H2' },
  ];
  return (
    <aside className="adm-sidebar">
      <a className="adm-brand" href="#top">
        <GNGLogo size={34} animate={false}/>
        <div>
          <div className="adm-brand-name">WEBES <span>GNG</span></div>
          <div className="adm-brand-sub">Ops Console</div>
        </div>
      </a>
      <nav className="adm-nav">
        {items.map(it => (
          <button key={it.key}
            className={`adm-navlink ${route === it.key ? 'active' : ''}`}
            onClick={() => go(it.key)}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d={it.icon}/></svg>
            {it.label}
            {it.key === 'live' && live > 0 && <span className="adm-live-badge">{live}</span>}
          </button>
        ))}
      </nav>
      <div className="adm-side-foot">
        <span className="stamp green">ops only</span>
      </div>
    </aside>
  );
}

/* ---------- Admin App (root of the module) ---------- */
function AdminApp() {
  const hash = useHashRoute();
  const isAdmin = hash.startsWith('#/admin');
  const [authed, setAuthed] = useState(false);
  const data = useAdminData();

  // route segment after #/admin/...
  const seg = hash.replace('#/admin', '').replace(/^\//, '') || 'dash';
  const route = ['dash','create','schedule','review','live','stats'].includes(seg) ? seg : 'dash';
  const go = (key) => { window.location.hash = `#/admin/${key}`; };

  if (!isAdmin) return null;            // public site untouched
  if (!authed) return <div className="adm"><AdminLogin onAuth={() => setAuthed(true)} /></div>;

  const liveCount = data.events.filter(e => e.stage === 'live').length;

  return (
    <div className="adm">
      <div className="adm-grain" aria-hidden="true"></div>
      <AdminSidebar route={route} go={go} live={liveCount} />
      <div className="adm-main">
        <AdminTopbar route={route} />
        <div className="adm-content">
          {route === 'dash'     && <AdminDashboard data={data} go={go} />}
          {route === 'create'   && <AdminCreate data={data} go={go} />}
          {route === 'schedule' && <AdminSchedule data={data} />}
          {route === 'review'   && <AdminReview data={data} />}
          {route === 'live'     && <AdminLive data={data} />}
          {route === 'stats'    && <AdminStats data={data} />}
        </div>
      </div>
    </div>
  );
}

function AdminTopbar({ route }) {
  const titles = { dash:'Dashboard', create:'Create Event', schedule:'Schedule', review:'Builder Submissions', live:'Live Event Control', stats:'Analytics' };
  return (
    <header className="adm-topbar">
      <div>
        <div className="eyebrow">- gang ops</div>
        <h1 className="adm-h1">{titles[route]}</h1>
      </div>
      <div className="adm-topbar-right">
        <span className="adm-tz-chip">🕓 UTC+1 · Lagos</span>
        <ThemeToggle/>
        <a href="#top" className="adm-exit">View site ↗</a>
      </div>
    </header>
  );
}

window.AdminApp = AdminApp;
