// console-auth.jsx — Login gate for the Operations Console. Authenticates
// against Supabase (for @demo-rwic.com accounts) or falls back to the
// in-memory directory (for prototype @railflagspro.com accounts).

function ConsoleLogin({ onAuthed }) {
  const { tweaks } = useTweakValues();
  const [mode, setMode] = useState('password'); // 'password' | 'code'
  const [email, setEmail] = useState('dwhitfield@demo-rwic.com');
  const [pw, setPw] = useState('demo123');
  const [code, setCode] = useState('');
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    setErr('');
    setLoading(true);
    try {
      let res;
      if (mode === 'code') {
        res = RFP.loginCode(code, 'console');
      } else {
        // Use async Supabase login if available, sync fallback otherwise
        if (RFP.loginAsync) {
          res = await RFP.loginAsync(email, pw, 'console');
        } else {
          res = RFP.login(email, pw, 'console');
        }
      }
      if (res.ok) onAuthed(res.session);
      else setErr(res.error);
    } catch (e) {
      setErr(e.message || 'Login failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e) => { if (e.key === 'Enter') submit(); };

  // Demo accounts — show both live (demo-rwic.com) and prototype options
  const demoAccts = [
    ['Officer (full access)', 'dwhitfield@demo-rwic.com'],
    ['Operations', 'lpark@demo-rwic.com'],
    ['Accounting', 'skessler@demo-rwic.com'],
    ['Safety', 'rcalderon@demo-rwic.com'],
    ['Dispatch', 'oreyes@demo-rwic.com'],
  ];

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.1fr 0.9fr' }}>
      {/* Brand panel */}
      <div style={{ background: 'linear-gradient(160deg, #0E1622 0%, #1a2536 100%)', color: '#fff', padding: 56, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -80, right: -80, width: 320, height: 320, borderRadius: '50%', background: 'var(--accent)', opacity: 0.16, filter: 'blur(10px)' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: '#0F172A', border: '1px solid rgba(255,255,255,0.15)', display: 'grid', placeItems: 'center', fontWeight: 700, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'var(--accent)', clipPath: 'polygon(0 100%, 100% 100%, 100% 58%, 0 90%)' }} />
            <span style={{ position: 'relative', zIndex: 1 }}>{(tweaks.companyName || 'RF').split(/\s+/).map(w => w[0]).join('').slice(0, 2).toUpperCase()}</span>
          </div>
          <div style={{ fontWeight: 700, fontSize: 17 }}>{tweaks.companyName}</div>
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: -0.8, lineHeight: 1.15 }}>Operations Console</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.65)', marginTop: 12, lineHeight: 1.6, maxWidth: 340 }}>Sign in with your company account. Your role determines which workspaces you can see — officers have full access.</div>
        </div>
        <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.4)', position: 'relative' }} className="mono">Single sign-on · shared identity across Console · Tablet · Portal</div>
      </div>

      {/* Form */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48, background: 'var(--paper)' }}>
        <div style={{ width: '100%', maxWidth: 340 }}>
          <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>Sign in</div>
          <div style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 4, marginBottom: 18 }}>Operations staff & officers.</div>

          {/* mode toggle */}
          <div style={{ display: 'flex', gap: 4, background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 10, padding: 3, marginBottom: 18 }}>
            {[['password', 'Email & password'], ['code', 'Access code']].map(([m, label]) => (
              <button key={m} onClick={() => { setMode(m); setErr(''); }} style={{
                flex: 1, padding: '7px 10px', border: 'none', borderRadius: 7, cursor: 'pointer',
                background: mode === m ? 'var(--panel)' : 'transparent',
                boxShadow: mode === m ? 'var(--shadow-sm)' : 'none',
                fontWeight: mode === m ? 600 : 500, fontSize: 12.5, color: mode === m ? 'var(--text)' : 'var(--muted)',
              }}>{label}</button>
            ))}
          </div>

          {mode === 'password' ? (
            <>
              <label style={{ display: 'block', marginBottom: 12 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 5 }}>Work email</div>
                <input value={email} onChange={e => setEmail(e.target.value)} onKeyDown={handleKeyDown} style={authInput} />
              </label>
              <label style={{ display: 'block', marginBottom: 14 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 5 }}>Password</div>
                <input type="password" value={pw} onChange={e => setPw(e.target.value)} onKeyDown={handleKeyDown} style={authInput} />
              </label>
            </>
          ) : (
            <label style={{ display: 'block', marginBottom: 14 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 5 }}>Access code</div>
              <input value={code} onChange={e => setCode(e.target.value.toUpperCase())} onKeyDown={handleKeyDown} placeholder="e.g. ACCT-2026-6605" style={{ ...authInput, fontFamily: 'var(--font-mono)' }} />
            </label>
          )}

          {err && <div style={{ background: 'var(--bad-soft)', color: 'var(--bad)', padding: '8px 12px', borderRadius: 8, fontSize: 12.5, marginBottom: 14 }}>{err}</div>}

          <Button variant="primary" size="lg" style={{ width: '100%', opacity: loading ? 0.7 : 1 }} onClick={submit} disabled={loading}>
            {loading ? 'Signing in…' : 'Sign in'}
          </Button>

          <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{mode === 'password' ? 'Demo accounts · password demo123' : 'Demo codes'}</div>
            {mode === 'password' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {demoAccts.map(([label, em]) => (
                  <button key={em} onClick={() => { setEmail(em); setPw('demo123'); }} style={demoRow}>
                    <span style={{ color: 'var(--text-2)', fontWeight: 600 }}>{label}</span>
                    <span className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>{em.split('@')[0]}</span>
                  </button>
                ))}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {Object.entries(RFP.ACCESS_CODES).slice(0, 5).map(([c, role]) => (
                  <button key={c} onClick={() => setCode(c)} style={demoRow}>
                    <span style={{ color: 'var(--text-2)', fontWeight: 600, textTransform: 'capitalize' }}>{role}</span>
                    <span className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>{c}</span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

const authInput = { width: '100%', padding: '10px 12px', border: '1px solid var(--line-strong)', borderRadius: 9, fontSize: 14, fontFamily: 'inherit', background: 'var(--panel)', outline: 'none' };
const demoRow = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 10px', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, cursor: 'pointer', fontSize: 12.5, width: '100%' };

Object.assign(window, { ConsoleLogin });
