// ─────────────────────────────────────────────
// DEV_Login.jsx — Developer login
// Reuses same auth API as app login
// ─────────────────────────────────────────────

// ── Device fingerprint ────────────────────────
async function getDeviceHashDev() {
  const components = [
    navigator.userAgent, navigator.language || '',
    (screen.width||0) + 'x' + (screen.height||0),
    Intl.DateTimeFormat().resolvedOptions().timeZone || '',
    navigator.platform || '',
  ].join('|');
  if (window.crypto?.subtle) {
    try {
      const encoded    = new TextEncoder().encode(components);
      const hashBuffer = await crypto.subtle.digest('SHA-256', encoded);
      return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2,'0')).join('');
    } catch(e) {}
  }
  let h = 0;
  for (let i = 0; i < components.length; i++) { h = ((h << 5) - h) + components.charCodeAt(i); h |= 0; }
  return Math.abs(h).toString(16).padStart(8, '0');
}

function getDeviceNameDev() {
  const ua = navigator.userAgent;
  let browser = 'Browser', os = 'Unknown';
  if      (ua.includes('Edg'))     browser = 'Edge';
  else if (ua.includes('Chrome'))  browser = 'Chrome';
  else if (ua.includes('Firefox')) browser = 'Firefox';
  else if (ua.includes('Safari'))  browser = 'Safari';
  if      (ua.includes('iPhone'))  os = 'iPhone';
  else if (ua.includes('iPad'))    os = 'iPad';
  else if (ua.includes('Android')) os = 'Android';
  else if (ua.includes('Mac'))     os = 'Mac';
  else if (ua.includes('Windows')) os = 'Windows';
  else if (ua.includes('Linux'))   os = 'Linux';
  return `${browser} on ${os}`;
}

function DEVLogin({ onLogin }) {
  const [step,       setStep]       = React.useState('email');
  const [email,      setEmail]      = React.useState('');
  const [password,   setPassword]   = React.useState('');
  const [code,       setCode]       = React.useState('');
  const [showPw,     setShowPw]     = React.useState(false);
  const [remember,   setRemember]   = React.useState(false);
  const [loading,    setLoading]    = React.useState(false);
  const [error,      setError]      = React.useState(null);
  const [info,       setInfo]       = React.useState(null);
  const [hasPassword,setHasPassword]= React.useState(false);
  const [deviceHash, setDeviceHash] = React.useState(null);
  const [deviceName, setDeviceName] = React.useState('');

  React.useEffect(() => {
    getDeviceHashDev().then(h => setDeviceHash(h));
    setDeviceName(getDeviceNameDev());
  }, []);

  const DEV_APP_ID = 'DEV';

  function clear() { setError(null); setInfo(null); }

  async function apiPost(endpoint, body) {
    const res = await fetch(`${API_BASE}/v6/auth/${endpoint}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    return res.json();
  }

  async function handleEmailSubmit(e) {
    e.preventDefault();
    clear();
    if (!email.trim()) return;
    setLoading(true);
    try {
      const data = await apiPost('check', { app: DEV_APP_ID, email: email.trim(), deviceHash });
      if (data.status !== 'ok') throw new Error(data.message || 'Email not found');
      setHasPassword(!!data.hasPassword);
      if (data.need2fa && !data.hasPassword) {
        await handleSendCode('email');
        return;
      }
      setStep('options');
    } catch(err) { setError(err.message); }
    setLoading(false);
  }

  async function handlePasswordSubmit(e) {
    e.preventDefault();
    clear();
    setLoading(true);
    try {
      const data = await apiPost('password', { app: DEV_APP_ID, email, password, remember, deviceHash, deviceName });
      if (data.status === 'need_2fa') {
        await handleSendCode('email');
        return;
      }
      if (data.status !== 'ok') throw new Error(data.message || 'Incorrect password');
      onLogin(data.token, data.user);
    } catch(err) { setError(err.message); }
    setLoading(false);
  }

  async function handleSendCode(via) {
    clear();
    setLoading(true);
    try {
      const data = await apiPost('code', { app: DEV_APP_ID, email, via });
      if (data.status !== 'ok') throw new Error(data.message);
      setInfo(`Code sent to your ${via === 'sms' ? 'phone' : 'email'}`);
      setStep('code');
    } catch(err) { setError(err.message); }
    setLoading(false);
  }

  async function handleVerifyCode(e) {
    e.preventDefault();
    clear();
    setLoading(true);
    try {
      const data = await apiPost('verify', { app: DEV_APP_ID, email, code, remember, deviceHash, deviceName });
      if (data.status !== 'ok') throw new Error(data.message || 'Invalid code');
      onLogin(data.token, data.user);
    } catch(err) { setError(err.message); }
    setLoading(false);
  }

  return (
    <div style={SL.page}>
      {/* Left panel — branding */}
      <div style={SL.left}>
        <div style={SL.brand}>
          <div style={SL.logo}>
            <span style={SL.logoIcon}>⟨/⟩</span>
          </div>
          <div style={SL.brandName}>DataObjects</div>
          <div style={SL.brandSub}>Developer Platform</div>
        </div>
        <div style={SL.tagline}>
          Build, deploy, and manage<br />data applications at scale.
        </div>
      </div>

      {/* Right panel — login form */}
      <div style={SL.right}>
        <div style={SL.card}>
          <div style={SL.cardTitle}>
            {step === 'email'   ? 'Sign in'        : null}
            {step === 'options' ? 'Welcome back'   : null}
            {step === 'code'    ? 'Enter your code': null}
          </div>

          {step !== 'email' && (
            <button style={SL.backBtn} onClick={() => {
              setStep(step === 'code' ? 'options' : 'email');
              clear();
            }}>← {step === 'code' ? email : 'Back'}</button>
          )}

          {error && <div style={SL.error}>{error}</div>}
          {info  && <div style={SL.info}>{info}</div>}

          {/* Email step */}
          {step === 'email' && (
            <form onSubmit={handleEmailSubmit}>
              <label style={SL.label}>Email address</label>
              <input
                style={SL.input}
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@company.com"
                autoFocus required
              />
              <button style={SL.btnPrimary} type="submit" disabled={loading || !email.trim()}>
                {loading ? 'Checking…' : 'Continue →'}
              </button>
            </form>
          )}

          {/* Options step */}
          {step === 'options' && (
            <>
              {hasPassword && (
                <>
                  <form onSubmit={handlePasswordSubmit}>
                    <label style={SL.label}>Password</label>
                    <div style={{ position:'relative' }}>
                      <input
                        style={{ ...SL.input, paddingRight:40 }}
                        type={showPw ? 'text' : 'password'}
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        placeholder="Your password"
                        autoFocus required
                      />
                      <button type="button" onClick={() => setShowPw(!showPw)}
                        style={SL.eyeBtn}>{showPw ? '🙈' : '👁'}</button>
                    </div>
                    <label style={SL.checkRow}>
                      <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} />
                      <span style={{ marginLeft:8, fontSize:13, color:'#64748b' }}>Remember me for 30 days</span>
                    </label>
                    <button style={SL.btnPrimary} type="submit" disabled={loading || !password}>
                      {loading ? 'Signing in…' : 'Sign In →'}
                    </button>
                    <div style={{ textAlign:'right', marginTop:8 }}>
                      <button type="button" style={SL.forgotBtn}
                        onClick={() => { setPassword(''); handleSendCode('email'); }}>
                        Forgot password?
                      </button>
                    </div>
                  </form>
                  <div style={SL.divider}><div style={SL.divLine}/><span style={SL.orLabel}>or</span><div style={SL.divLine}/></div>
                </>
              )}
              <button style={SL.btnSecondary} onClick={() => handleSendCode('email')} disabled={loading}>
                {loading ? 'Sending…' : '✉ Send me a code'}
              </button>
            </>
          )}

          {/* Code step */}
          {step === 'code' && (
            <form onSubmit={handleVerifyCode}>
              <label style={SL.label}>6-digit code</label>
              <input
                style={{ ...SL.input, letterSpacing:'0.25em', fontSize:22, textAlign:'center', fontFamily:'DM Mono, monospace' }}
                type="text" inputMode="numeric" maxLength={6}
                value={code} onChange={e => setCode(e.target.value.replace(/\D/g,''))}
                placeholder="000000" autoFocus required
              />
              <button style={SL.btnPrimary} type="submit" disabled={loading || code.length < 6}>
                {loading ? 'Verifying…' : 'Verify →'}
              </button>
              <div style={{ textAlign:'center', marginTop:12 }}>
                <button type="button" style={SL.forgotBtn}
                  onClick={() => handleSendCode('email')}>Resend code</button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

const SL = {
  page:      { display:'flex', minHeight:'100vh', fontFamily:'DM Sans, sans-serif' },
  left:      { flex:'0 0 420px', background:'#0f1923', display:'flex', flexDirection:'column',
               justifyContent:'center', padding:'60px 48px', position:'relative', overflow:'hidden' },
  brand:     { marginBottom:48 },
  logo:      { width:52, height:52, background:'rgba(255,255,255,0.1)', borderRadius:14,
               display:'flex', alignItems:'center', justifyContent:'center', marginBottom:20 },
  logoIcon:  { color:'#fff', fontSize:20, fontFamily:'DM Mono, monospace', fontWeight:500 },
  brandName: { color:'#fff', fontSize:28, fontWeight:700, letterSpacing:'-0.02em', marginBottom:4 },
  brandSub:  { color:'rgba(255,255,255,0.45)', fontSize:13, fontWeight:400, letterSpacing:'0.08em',
               textTransform:'uppercase' },
  tagline:   { color:'rgba(255,255,255,0.6)', fontSize:16, lineHeight:1.7, fontWeight:300 },
  right:     { flex:1, display:'flex', alignItems:'center', justifyContent:'center',
               background:'#f0f2f5', padding:40 },
  card:      { background:'#fff', borderRadius:16, padding:'40px 44px', width:'100%', maxWidth:420,
               boxShadow:'0 4px 24px rgba(0,0,0,0.08)' },
  cardTitle: { fontSize:22, fontWeight:700, color:'#0f1923', marginBottom:28, letterSpacing:'-0.02em' },
  backBtn:   { background:'none', border:'none', color:'#2563eb', fontSize:13, padding:0,
               marginBottom:20, cursor:'pointer', fontFamily:'inherit' },
  label:     { display:'block', fontSize:13, fontWeight:500, color:'#374151', marginBottom:6 },
  input:     { width:'100%', padding:'10px 14px', border:'1.5px solid #e2e8f0', borderRadius:8,
               fontSize:14, fontFamily:'DM Sans, sans-serif', outline:'none', marginBottom:14,
               transition:'border-color 0.15s', color:'#0f1923', background:'#fff' },
  btnPrimary:{ width:'100%', padding:'11px 0', background:'#0f1923', color:'#fff',
               border:'none', borderRadius:8, fontSize:14, fontWeight:600,
               cursor:'pointer', marginTop:4, letterSpacing:'0.01em' },
  btnSecondary:{ width:'100%', padding:'11px 0', background:'#fff', color:'#0f1923',
                 border:'1.5px solid #e2e8f0', borderRadius:8, fontSize:14, fontWeight:500,
                 cursor:'pointer' },
  eyeBtn:    { position:'absolute', right:12, top:'50%', transform:'translateY(-60%)',
               background:'none', border:'none', cursor:'pointer', color:'#94a3b8', fontSize:16,
               padding:0 },
  checkRow:  { display:'flex', alignItems:'center', marginBottom:14, cursor:'pointer' },
  forgotBtn: { background:'none', border:'none', color:'#94a3b8', fontSize:12,
               cursor:'pointer', fontFamily:'inherit', textDecoration:'underline' },
  divider:   { display:'flex', alignItems:'center', gap:10, margin:'16px 0' },
  divLine:   { flex:1, height:1, background:'#e2e8f0' },
  orLabel:   { color:'#94a3b8', fontSize:12 },
  error:     { background:'#fef2f2', color:'#dc2626', padding:'10px 14px', borderRadius:8,
               fontSize:13, marginBottom:16, border:'1px solid #fecaca' },
  info:      { background:'#eff6ff', color:'#2563eb', padding:'10px 14px', borderRadius:8,
               fontSize:13, marginBottom:16, border:'1px solid #bfdbfe' },
};
