/* AUREN — Auth screens: login, signup, connect wallet (all mock) */

function AuthShell({ children, go }) {
  const ref = useThreeScene((c) => window.AURENThree.ambientNetwork(c, { count: 70 }), []);
  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr', position: 'relative' }} className="auth-shell">
      {/* left brand panel */}
      <div className="auth-brand" style={{ position: 'relative', overflow: 'hidden', borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 'clamp(32px,5vw,64px)' }}>
        <div ref={ref} style={{ position: 'absolute', inset: 0, opacity: 0.8 }} />
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 70% 50% at 30% 40%, rgba(24,200,255,0.12), transparent 70%)' }} />
        <button onClick={() => go('landing')} style={{ position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', gap: 12, background: 'none', border: 'none', cursor: 'pointer', alignSelf: 'flex-start' }}>
          <img src="assets/auren-logo.png" alt="AUREN" style={{ height: 42, width: 42, filter: 'drop-shadow(0 0 12px rgba(24,224,255,0.4))' }} />
          <span className="font-display" style={{ fontSize: 22, fontWeight: 800, letterSpacing: '.16em', color: '#fff' }}>AUREN</span>
        </button>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <h2 className="font-display" style={{ fontSize: 'clamp(26px,3.4vw,40px)', fontWeight: 800, lineHeight: 1.08, marginBottom: 18 }}>
            <span className="text-chrome">The autonomous</span><br /><span className="text-cyan-grad">compute mesh</span>
          </h2>
          <p style={{ color: 'var(--text-2)', fontSize: 16, lineHeight: 1.6, maxWidth: 380 }}>Onboard GPUs, route autonomous workloads, and settle compute instantly through Idle-powered rails.</p>
          <div style={{ display: 'flex', gap: 30, marginTop: 34 }}>
            {[['14.8K', 'Nodes'], ['58K', 'GPUs'], ['42', 'Regions']].map(([v, l]) => (
              <div key={l}>
                <div className="font-display" style={{ fontSize: 24, fontWeight: 700, color: '#fff' }}>{v}</div>
                <div className="font-mono" style={{ fontSize: 11.5, color: 'var(--text-3)', letterSpacing: '.08em', marginTop: 3 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 2 }} className="font-mono">
          <span style={{ fontSize: 12, color: 'var(--text-3)', letterSpacing: '.1em' }}>POWERED BY IDLE PROTOCOL</span>
        </div>
      </div>
      {/* right form */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(28px,5vw,56px)', background: 'var(--bg-0)' }}>
        <div style={{ width: '100%', maxWidth: 400 }}>{children}</div>
      </div>
    </div>
  );
}

function Field({ label, type = 'text', value, onChange, placeholder, icon, error }) {
  const [show, setShow] = useState(false);
  const isPw = type === 'password';
  return (
    <div style={{ marginBottom: 18 }}>
      <label style={{ display: 'block', fontSize: 12.5, color: 'var(--text-2)', marginBottom: 8, fontWeight: 500, letterSpacing: '.02em' }}>{label}</label>
      <div style={{ position: 'relative' }}>
        {icon && <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', display: 'flex' }}><Icon name={icon} size={17} /></span>}
        <input type={isPw && show ? 'text' : type} value={value} onChange={onChange} placeholder={placeholder}
          style={{
            width: '100%', padding: icon ? '13px 14px 13px 42px' : '13px 14px', borderRadius: 'var(--r-sm)',
            background: 'var(--surface)', border: '1px solid ' + (error ? 'rgba(255,92,122,0.5)' : 'var(--line-2)'),
            color: '#fff', fontSize: 14.5, fontFamily: 'var(--font-body)', outline: 'none', transition: 'all .2s',
          }}
          onFocus={e => e.target.style.borderColor = 'var(--line-bright)'}
          onBlur={e => e.target.style.borderColor = error ? 'rgba(255,92,122,0.5)' : 'var(--line-2)'} />
        {isPw && <button type="button" onClick={() => setShow(s => !s)} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', color: 'var(--text-3)', cursor: 'pointer', fontSize: 12, fontFamily: 'var(--font-mono)' }}>{show ? 'HIDE' : 'SHOW'}</button>}
      </div>
      {error && <div style={{ fontSize: 12, color: 'var(--red)', marginTop: 6 }}>{error}</div>}
    </div>
  );
}

const WALLETS = [
  { id: 'metamask', name: 'MetaMask', sub: 'Browser extension', color: '#F6851B', glyph: '🦊' },
  { id: 'walletconnect', name: 'WalletConnect', sub: 'Scan with mobile', color: '#3B99FC', glyph: '◇' },
  { id: 'coinbase', name: 'Coinbase Wallet', sub: 'Connect via Coinbase', color: '#0052FF', glyph: '○' },
];

function WalletConnect({ onDone, go }) {
  const [connecting, setConnecting] = useState(null);
  function connect(w) {
    setConnecting(w.id);
    setTimeout(() => onDone({ name: w.name + ' user', email: 'wallet@auren.mesh', wallet: true }), 1400);
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {WALLETS.map(w => (
        <button key={w.id} onClick={() => connect(w)} disabled={!!connecting} style={{
          display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px', borderRadius: 'var(--r-md)',
          background: connecting === w.id ? 'rgba(24,224,255,0.06)' : 'var(--surface)', cursor: connecting ? 'default' : 'pointer',
          border: '1px solid ' + (connecting === w.id ? 'var(--line-cyan)' : 'var(--line-2)'), transition: 'all .25s', textAlign: 'left',
        }}
          onMouseEnter={e => { if (!connecting) e.currentTarget.style.borderColor = 'var(--line-cyan)'; }}
          onMouseLeave={e => { if (!connecting) e.currentTarget.style.borderColor = 'var(--line-2)'; }}>
          <div style={{ width: 42, height: 42, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, background: w.color + '22', border: '1px solid ' + w.color + '55' }}>{w.glyph}</div>
          <div style={{ flex: 1 }}>
            <div className="font-display" style={{ fontSize: 15, fontWeight: 600, color: '#fff' }}>{w.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>{w.sub}</div>
          </div>
          {connecting === w.id
            ? <span className="font-mono" style={{ fontSize: 12, color: 'var(--cyan)' }}>Connecting…</span>
            : <span style={{ color: 'var(--text-3)' }}><Icon name="arrow" size={18} /></span>}
        </button>
      ))}
    </div>
  );
}

function Auth({ mode, go, onAuth }) {
  const [tab, setTab] = useState(mode === 'signup' ? 'signup' : 'login');
  const [method, setMethod] = useState('email'); // email | wallet
  const [email, setEmail] = useState('demo@auren.mesh');
  const [pw, setPw] = useState('meshmesh');
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  useEffect(() => { setTab(mode === 'signup' ? 'signup' : 'login'); }, [mode]);

  function submit(e) {
    e.preventDefault();
    setBusy(true);
    setTimeout(() => onAuth({ name: name || email.split('@')[0], email, wallet: false }), 1100);
  }
  return (
    <AuthShell go={go}>
      <div style={{ marginBottom: 28 }}>
        <h1 className="font-display" style={{ fontSize: 30, fontWeight: 700, color: '#fff', marginBottom: 8 }}>
          {tab === 'signup' ? 'Create account' : 'Welcome back'}
        </h1>
        <p style={{ color: 'var(--text-2)', fontSize: 14.5 }}>
          {tab === 'signup' ? 'Join the autonomous compute mesh.' : 'Sign in to your AUREN dashboard.'}
        </p>
      </div>

      {/* method toggle */}
      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', marginBottom: 24 }}>
        {[['email', 'Email'], ['wallet', 'Connect Wallet']].map(([m, l]) => (
          <button key={m} onClick={() => setMethod(m)} style={{
            flex: 1, padding: '9px', borderRadius: 9, border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 13.5, fontFamily: 'var(--font-body)',
            background: method === m ? 'var(--grad-cyan)' : 'transparent', color: method === m ? '#021018' : 'var(--text-2)', transition: 'all .25s',
          }}>{l}</button>
        ))}
      </div>

      {method === 'wallet' ? (
        <WalletConnect onDone={onAuth} go={go} />
      ) : (
        <form onSubmit={submit}>
          {tab === 'signup' && <Field label="Display name" value={name} onChange={e => setName(e.target.value)} placeholder="satoshi" icon="settings" />}
          <Field label="Email" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@domain.com" icon="settle" />
          <Field label="Password" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" icon="shield" />
          {tab === 'login' && <div style={{ textAlign: 'right', marginBottom: 20, marginTop: -6 }}><a href="#" onClick={e => e.preventDefault()} style={{ fontSize: 12.5, color: 'var(--text-cyan)', textDecoration: 'none' }}>Forgot password?</a></div>}
          <Button variant="primary" size="lg" full type="submit" iconRight={busy ? undefined : 'arrow'} style={{ marginTop: 6 }}>
            {busy ? 'Authenticating…' : (tab === 'signup' ? 'Create account' : 'Sign in')}
          </Button>
        </form>
      )}

      <div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '24px 0' }}>
        <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
        <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-3)', letterSpacing: '.1em' }}>OR</span>
        <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      </div>
      <div style={{ textAlign: 'center', fontSize: 14, color: 'var(--text-2)' }}>
        {tab === 'signup' ? 'Already have an account? ' : "Don't have an account? "}
        <button onClick={() => setTab(tab === 'signup' ? 'login' : 'signup')} style={{ background: 'none', border: 'none', color: 'var(--cyan)', cursor: 'pointer', fontWeight: 600, fontSize: 14, fontFamily: 'var(--font-body)' }}>
          {tab === 'signup' ? 'Sign in' : 'Sign up'}
        </button>
      </div>
      <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--text-3)', marginTop: 24, lineHeight: 1.5 }}>
        Demo build — any credentials work. No data leaves your browser.
      </p>
    </AuthShell>
  );
}

Object.assign(window, { Auth, AuthShell, Field, WalletConnect });
