// /admin — password gate + unconstrained viewer.
//
// Validates the submitted password against the central server's
// ADMIN_PASSWORD env var via POST /api/v1/admin/check, then renders the
// real D3 viewer with no URL params (no entity focus, no hop cap).
//
// Session is stored in sessionStorage so a refresh keeps you in — but
// it dies when the tab closes. This is a UX gate, not a security
// boundary: the underlying viewer URL is itself public. Real
// admin endpoints stay behind the API-key gate on central.

const ADMIN_SESSION_KEY = 'graphite_admin_session';

window.Admin = function Admin({ navigate }) {
  const [authed, setAuthed] = React.useState(
    () => sessionStorage.getItem(ADMIN_SESSION_KEY) === '1'
  );

  function signOut() {
    sessionStorage.removeItem(ADMIN_SESSION_KEY);
    setAuthed(false);
  }

  if (!authed) {
    return <AdminLogin onAuth={() => {
      sessionStorage.setItem(ADMIN_SESSION_KEY, '1');
      setAuthed(true);
    }} navigate={navigate} />;
  }
  return <AdminViewer navigate={navigate} onSignOut={signOut} />;
};

function AdminLogin({ onAuth, navigate }) {
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  async function submit(e) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    const ok = await window.api.adminCheck(password);
    setBusy(false);
    if (ok) {
      onAuth();
    } else {
      setError('Wrong password.');
      setPassword('');
    }
  }

  return (
    <div className="page" style={{
      display:'flex', alignItems:'center', justifyContent:'center',
      minHeight:'100vh', paddingTop:'var(--nav-h)',
    }}>
      <form onSubmit={submit} className="glass" style={{
        width:'100%', maxWidth:420, padding:'32px 28px', borderRadius:16,
      }}>
        <div className="eyebrow"><span className="dot" />Restricted</div>
        <h2 style={{marginTop:14, fontSize:24}}>Admin</h2>
        <p style={{color:'var(--fg-dim)', marginTop:8, fontSize:14, lineHeight:1.5}}>
          Unconstrained graph viewer — no entity focus, no hop cap. Password required.
        </p>

        <label
          htmlFor="admin-password"
          style={{
            display:'block', marginTop:24, marginBottom:6,
            fontSize:11, letterSpacing:'0.12em', textTransform:'uppercase',
            color:'var(--fg-mute)',
          }}
        >Password</label>
        <input
          id="admin-password"
          type="password"
          autoFocus
          required
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          style={{
            width:'100%', padding:'10px 12px', borderRadius:8,
            background:'rgba(255,255,255,0.04)',
            border:'1px solid var(--border)',
            color:'var(--fg)', fontSize:14, fontFamily:'inherit',
            outline:'none',
          }}
        />

        {error && (
          <div style={{marginTop:12, color:'var(--red)', fontSize:13}}>{error}</div>
        )}

        <button
          type="submit"
          className="btn btn-accent"
          disabled={busy}
          style={{width:'100%', marginTop:20, justifyContent:'center'}}
        >
          {busy ? 'Checking…' : 'Enter'}
        </button>

        <a
          href="#/"
          onClick={(e) => { e.preventDefault(); navigate('/'); }}
          style={{
            display:'block', textAlign:'center', marginTop:18,
            fontSize:13, color:'var(--fg-mute)',
          }}
        >← Back to site</a>
      </form>
    </div>
  );
}

function AdminViewer({ navigate, onSignOut }) {
  // Unconstrained: no focus, no hops, no max_hops → full default behavior.
  const src = window.api.viewerUrl(null);
  return (
    <div style={{position:'fixed', inset:0, display:'flex', flexDirection:'column', background:'#0a0a0d'}}>
      <header style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'10px 18px',
        borderBottom:'1px solid var(--border)',
        background:'rgba(10,10,13,0.9)',
        backdropFilter:'blur(8px)',
        WebkitBackdropFilter:'blur(8px)',
      }}>
        <div style={{display:'flex', alignItems:'center', gap:12, minWidth:0}}>
          <a
            href="#/"
            onClick={(e) => { e.preventDefault(); navigate('/'); }}
            style={{fontSize:13, color:'var(--fg-mute)', flexShrink:0}}
          >← Site</a>
          <span style={{color:'var(--fg-faint)'}}>/</span>
          <span style={{fontWeight:600, color:'var(--fg)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>
            Admin · Unconstrained Graph
          </span>
          <span className="badge badge-live" style={{marginLeft:8}}>
            <span className="pulse" />FULL ACCESS
          </span>
        </div>
        <button
          onClick={onSignOut}
          style={{
            background:'none', border:'none', cursor:'pointer',
            fontSize:12, color:'var(--fg-mute)', fontFamily:'inherit',
          }}
        >Sign out</button>
      </header>
      <div style={{flex:1, position:'relative'}}>
        {src ? (
          <iframe
            src={src}
            title="Unconstrained graph viewer"
            style={{position:'absolute', inset:0, width:'100%', height:'100%', border:0, background:'#0a0a0d'}}
          />
        ) : (
          <div style={{
            position:'absolute', inset:0,
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'var(--fg-mute)',
          }}>
            CENTRAL_API_URL not configured — see <code style={{margin:'0 6px'}}>env.js</code>
          </div>
        )}
      </div>
    </div>
  );
}
