// Phone + OTP login screen for the driver prototype.
// Dev backend accepts code "123456" for any +972 phone.

function LoginScreen({ onAuthed }) {
  const [step, setStep] = React.useState('phone'); // 'phone' | 'code'
  // Pre-fill the seeded demo number only in dev; production starts blank.
  const [phone, setPhone] = React.useState(window.RESDRI_DEV ? '+972500000001' : '');
  const [code, setCode] = React.useState('');
  const [devCode, setDevCode] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const sendOtp = async () => {
    setError(null); setBusy(true);
    try {
      const r = await window.api.requestOtp(phone);
      setDevCode(r.devCode || null);
      setStep('code');
    } catch (e) {
      setError(e.message || 'تعذّر الإرسال');
    } finally {
      setBusy(false);
    }
  };

  const verify = async () => {
    setError(null); setBusy(true);
    try {
      const r = await window.api.verifyOtp(phone, code);
      onAuthed(r.driver);
    } catch (e) {
      setError(e.message || 'رمز غير صحيح');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'var(--bg)',
      display: 'flex', flexDirection: 'column', padding: '70px 22px 26px',
    }}>
      {/* Logo / title */}
      <div style={{ textAlign: 'center', marginBottom: 36 }}>
        <div style={{
          width: 64, height: 64, borderRadius: 20,
          background: 'var(--primary)', color: '#fff',
          display: 'grid', placeItems: 'center',
          fontFamily: 'inherit', fontWeight: 900, fontSize: 28,
          margin: '0 auto 14px',
          boxShadow: '0 12px 30px color-mix(in oklch, var(--primary) 32%, transparent)',
        }}>R</div>
        <div style={{ fontSize: 26, fontWeight: 900, color: 'var(--text)' }}>ResDri</div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 4 }}>
          {step === 'phone' ? 'أدخل رقم هاتفك للمتابعة' : 'أدخل رمز التحقق المرسل'}
        </div>
      </div>

      {step === 'phone' && (
        <>
          <label style={labelStyle}>رقم الهاتف</label>
          <input
            type="tel" dir="ltr"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            placeholder="+972 5X XXX XXXX"
            style={inputStyle}
          />
          <div style={{ flex: 1 }} />
          {error && <ErrorBanner>{error}</ErrorBanner>}
          <PrimaryButton tone="primary" size="lg" onClick={sendOtp} disabled={busy || !phone.startsWith('+972')}>
            {busy ? '...' : 'إرسال رمز التحقق'}
          </PrimaryButton>
          {window.RESDRI_DEV && (
            <>
              <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--text-3)', marginTop: 10, lineHeight: 1.6 }}>
                للتجربة: الرقم <span dir="ltr" className="num">+972500000001</span> · الرمز <span dir="ltr" className="num">123456</span>
              </div>
              <div dir="ltr" style={{ textAlign: 'center', fontSize: 9, color: 'var(--text-3)', marginTop: 6, fontFamily: 'ui-monospace, monospace', opacity: 0.6, wordBreak: 'break-all' }}>
                API → {window.api?.BASE || '?'}
              </div>
            </>
          )}
        </>
      )}

      {step === 'code' && (
        <>
          <label style={labelStyle}>رمز التحقق</label>
          <input
            type="tel" inputMode="numeric" maxLength={6}
            value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
            placeholder="••••••"
            style={{ ...inputStyle, textAlign: 'center', letterSpacing: 14, fontSize: 28, fontWeight: 800 }}
          />
          {/* Pilot test-code hint — only in dev mode (localhost or ?dev=1).
              Production users see a normal OTP entry with no leakage. */}
          {window.RESDRI_DEV && (
            <>
              <div style={{
                background: 'color-mix(in oklch, var(--accent) 16%, transparent)',
                border: '1px dashed color-mix(in oklch, var(--accent) 40%, transparent)',
                borderRadius: 12, padding: 10,
                fontSize: 12, color: 'var(--accent-700)', fontWeight: 700,
                marginTop: 12, textAlign: 'center',
              }}>
                للتجربة استخدم الرمز <span dir="ltr" className="num" style={{ fontSize: 16, fontWeight: 900 }}>{devCode || '123456'}</span>
              </div>
              <button className="tap" onClick={() => setCode(devCode || '123456')} style={{
                background: 'transparent', border: 'none',
                color: 'var(--primary)', fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
                padding: 6, marginTop: 4, cursor: 'pointer',
              }}>
                تعبئة الرمز تلقائياً
              </button>
            </>
          )}
          <div style={{ flex: 1 }} />
          {error && <ErrorBanner>{error}</ErrorBanner>}
          <PrimaryButton tone="success" size="lg" onClick={verify} disabled={busy || code.length !== 6}>
            {busy ? '...' : 'دخول'}
          </PrimaryButton>
          <button className="tap" onClick={() => { setStep('phone'); setCode(''); setError(null); }} style={{
            background: 'transparent', border: 'none',
            color: 'var(--text-2)', fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
            padding: 12, marginTop: 6, cursor: 'pointer',
          }}>
            تغيير الرقم
          </button>
        </>
      )}
    </div>
  );
}

const labelStyle = {
  display: 'block',
  fontSize: 11, fontWeight: 800,
  color: 'var(--text-2)',
  letterSpacing: '0.08em', textTransform: 'uppercase',
  marginBottom: 8,
};
const inputStyle = {
  width: '100%',
  height: 56,
  borderRadius: 16,
  border: '1.5px solid var(--line-strong)',
  background: 'var(--surface)',
  color: 'var(--text)',
  fontFamily: 'inherit', fontSize: 18, fontWeight: 700,
  padding: '0 16px',
  outline: 'none',
  boxSizing: 'border-box',
};

function ErrorBanner({ children }) {
  return (
    <div style={{
      background: 'color-mix(in oklch, var(--danger) 14%, transparent)',
      border: '1px solid color-mix(in oklch, var(--danger) 32%, transparent)',
      color: 'var(--danger)',
      borderRadius: 12, padding: 10,
      fontSize: 13, fontWeight: 700,
      marginBottom: 10, textAlign: 'center',
    }}>{children}</div>
  );
}

Object.assign(window, { LoginScreen });
