// Auth.jsx — sign in / sign up sheet: SMS OTP (primary) + Google.
// Calls window.Api; on success hands { token, user, subscription } to onSuccess.

const GOOGLE_CLIENT_ID = (() => {
  try { return (window.__ENV__ && window.__ENV__.GOOGLE_CLIENT_ID) || localStorage.getItem('logi_google_client_id') || ''; }
  catch { return ''; }
})();

function Auth({ open, onClose, onSuccess, intent = 'login', initialName = '' }) {
  const { Icons } = window;
  const [mode, setMode]   = React.useState('phone'); // 'phone' | 'code'
  const [name, setName]   = React.useState(initialName || '');
  const [phone, setPhone] = React.useState('');
  const [code, setCode]   = React.useState('');
  const [busy, setBusy]   = React.useState(false);
  const [err, setErr]     = React.useState('');
  const [resendIn, setResendIn] = React.useState(0);
  const googleRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) { setMode('phone'); setPhone(''); setCode(''); setErr(''); setBusy(false); setResendIn(0); setName(initialName || ''); }
  }, [open, initialName]);

  React.useEffect(() => {
    if (resendIn <= 0) return;
    const t = setTimeout(() => setResendIn(n => n - 1), 1000);
    return () => clearTimeout(t);
  }, [resendIn]);

  // Google Identity Services button
  React.useEffect(() => {
    if (!open || mode !== 'phone' || intent === 'signup') return;
    const g = window.google && window.google.accounts && window.google.accounts.id;
    if (!g || !GOOGLE_CLIENT_ID || !googleRef.current) return;
    try {
      g.initialize({
        client_id: GOOGLE_CLIENT_ID,
        callback: async (resp) => {
          if (!resp || !resp.credential) return;
          setBusy(true); setErr('');
          try {
            const r = await window.Api.googleLogin(resp.credential);
            onSuccess(r);
          } catch (e) { setErr(e.message || 'ورود با گوگل ناموفق بود'); }
          finally { setBusy(false); }
        },
      });
      googleRef.current.innerHTML = '';
      g.renderButton(googleRef.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'fa' });
    } catch {}
  }, [open, mode, intent]);

  if (!open) return null;

  const faDigits = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
  const toFa = n => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

  const sendOtp = async () => {
    const cleanName = name.trim();
    if (intent === 'signup' && cleanName.length < 2) { setErr('نامت را هم وارد کن'); return; }
    const p = faDigits(phone).replace(/\D/g, '');
    if (!/^09\d{9}$/.test(p)) { setErr('شماره موبایل را درست وارد کن (۰۹...)'); return; }
    setBusy(true); setErr('');
    try {
      const r = await window.Api.requestOtp(p);
      setMode('code'); setResendIn(r.ttl || 120);
    } catch (e) { setErr(e.message || 'ارسال کد ناموفق بود'); }
    finally { setBusy(false); }
  };

  const verify = async () => {
    const c = faDigits(code).replace(/\D/g, '');
    if (c.length < 4) { setErr('کد را کامل وارد کن'); return; }
    setBusy(true); setErr('');
    try {
      const r = await window.Api.verifyOtp(faDigits(phone).replace(/\D/g, ''), c);
      onSuccess(r, { intent, name: name.trim() });
    } catch (e) { setErr(e.message || 'کد نادرست است'); }
    finally { setBusy(false); }
  };

  const inputStyle = {
    width: '100%', boxSizing: 'border-box', background: 'var(--surface)',
    border: '1px solid var(--c-border-sm)', borderRadius: 12, padding: '13px 14px',
    font: "500 17px 'Estedad', sans-serif", color: 'var(--ink)',
    textAlign: 'center', letterSpacing: mode === 'code' ? '0.3em' : 'normal', outline: 'none',
  };
  const primaryBtn = (on) => ({
    width: '100%', padding: '14px', borderRadius: 14, border: 'none', marginTop: 14,
    background: on ? 'var(--firoozeh)' : 'var(--ink-4)', color: '#fff',
    font: "700 15px 'Estedad', sans-serif", cursor: on ? 'pointer' : 'not-allowed',
  });

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', zIndex: 5000, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', direction: 'rtl' }} onClick={onClose}>
      <div style={{ width: '100%', maxWidth: 460, background: 'var(--paper)', borderRadius: '22px 22px 0 0', boxShadow: '0 -8px 32px rgba(0,0,0,0.18)', padding: '0 0 calc(24px + env(safe-area-inset-bottom))' }} onClick={e => e.stopPropagation()}>
        <div style={{ width: 36, height: 4, borderRadius: 999, background: 'var(--c-inactive)', margin: '12px auto 0' }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px 4px' }}>
          <span style={{ font: "700 18px 'Estedad', sans-serif", color: 'var(--ink)' }}>{intent === 'signup' ? 'تأیید ثبت‌نام' : 'ورود'}</span>
          <button aria-label="بستن" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4 }}><Icons.X size={20} /></button>
        </div>

        <div style={{ padding: '8px 22px 4px' }}>
          {mode === 'phone' ? (
            <>
              <div style={{ font: "400 13.5px/1.7 'Estedad', sans-serif", color: 'var(--ink-2)', marginBottom: 14 }}>
                {intent === 'signup'
                  ? 'برای ساخت حساب، نام و شماره موبایلت را وارد کن. ورود به برنامه بعد از تایید کد انجام می‌شود.'
                  : 'شماره موبایلت رو وارد کن تا یک کد تأیید برات بفرستیم.'}
              </div>
              {intent === 'signup' && (
                <input
                  style={{ ...inputStyle, marginBottom: 10, textAlign: 'right', letterSpacing: 0 }}
                  value={name}
                  onChange={e => setName(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && sendOtp()}
                  placeholder="نام تو"
                  maxLength={30}
                  autoFocus
                />
              )}
              <input style={inputStyle} value={phone} onChange={e => setPhone(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && sendOtp()}
                inputMode="numeric" placeholder="۰۹۱۲۳۴۵۶۷۸۹" dir="ltr" maxLength={13} />
              {err && <div style={{ color: '#B23A48', font: "400 12.5px 'Estedad', sans-serif", marginTop: 8 }}>{err}</div>}
              <button style={primaryBtn(!busy)} disabled={busy} onClick={sendOtp}>{busy ? '...' : 'ارسال کد'}</button>

              {intent !== 'signup' && GOOGLE_CLIENT_ID && (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '18px 0 12px' }}>
                    <div style={{ flex: 1, height: 1, background: 'var(--c-border-sm)' }} />
                    <span style={{ font: "400 12px 'Estedad', sans-serif", color: 'var(--ink-3)' }}>یا</span>
                    <div style={{ flex: 1, height: 1, background: 'var(--c-border-sm)' }} />
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'center' }} ref={googleRef} />
                </>
              )}
            </>
          ) : (
            <>
              <div style={{ font: "400 13.5px/1.7 'Estedad', sans-serif", color: 'var(--ink-2)', marginBottom: 14 }}>
                کد تأیید ارسال‌شده به <b dir="ltr">{phone}</b> را وارد کن.
              </div>
              <input style={inputStyle} value={code} onChange={e => setCode(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && verify()}
                inputMode="numeric" placeholder="------" dir="ltr" maxLength={6} autoFocus />
              {err && <div style={{ color: '#B23A48', font: "400 12.5px 'Estedad', sans-serif", marginTop: 8 }}>{err}</div>}
              <button style={primaryBtn(!busy)} disabled={busy} onClick={verify}>{busy ? '...' : 'تأیید و ورود'}</button>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12 }}>
                <button style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', font: "500 12.5px 'Estedad', sans-serif" }}
                  onClick={() => { setMode('phone'); setCode(''); setErr(''); }}>تغییر شماره</button>
                <button style={{ background: 'none', border: 'none', cursor: resendIn > 0 ? 'default' : 'pointer', color: resendIn > 0 ? 'var(--ink-4)' : 'var(--firoozeh-deep)', font: "500 12.5px 'Estedad', sans-serif" }}
                  disabled={resendIn > 0} onClick={sendOtp}>
                  {resendIn > 0 ? `ارسال مجدد تا ${toFa(resendIn)} ثانیه` : 'ارسال مجدد کد'}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.Auth = Auth;
