// 1Radar — Auth screen (Login / Register) — EUSpy-inspired split layout

const API_BASE = (window.APP_CONFIG && window.APP_CONFIG.API_BASE) || 'http://localhost:3001/api';

const OnboardingV3 = ({ mode = 'register', onAuth, onSwitchMode }) => {
  const [showPw, setShowPw] = React.useState(false);
  const [slideIdx, setSlideIdx] = React.useState(0);

  const [fields, setFields] = React.useState({ name: '', email: '', password: '' });
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const slides = [
    { title: 'See every ad your competitors run', sub: 'Spy on millions of Meta, TikTok & YouTube ads from top European brands.' },
    { title: 'Track budgets, reach & performance', sub: 'See estimated daily spend, reach, and how long winning ads have been running.' },
    { title: 'Save references, steal hooks — ethically', sub: 'Build your swipe file with one click. Filter by niche, format, or CTA.' },
  ];

  React.useEffect(() => {
    const t = setInterval(() => setSlideIdx(i => (i + 1) % slides.length), 4000);
    return () => clearInterval(t);
  }, []);

  const isRegister = mode === 'register';

  const switchMode = (m) => {
    setShowPw(false);
    setError('');
    setFields({ name: '', email: '', password: '' });
    if (onSwitchMode) onSwitchMode(m);
  };

  const setField = (key) => (e) => setFields(f => ({ ...f, [key]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const endpoint = isRegister ? '/auth/register' : '/auth/login';
      const body = isRegister
        ? { name: fields.name, email: fields.email, password: fields.password }
        : { email: fields.email, password: fields.password };

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

      const data = await res.json();

      if (!res.ok) {
        const msg = data.errors ? data.errors[0].msg : (data.error || 'Something went wrong');
        setError(msg);
        return;
      }

      localStorage.setItem('1radar_token', data.token);
      localStorage.setItem('1radar_user', JSON.stringify(data.user));
      onAuth(data.user);
    } catch {
      setError('Cannot reach server. Make sure the backend is running.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ display: 'flex', flex: 1, alignSelf: 'stretch', background: 'var(--bg-surface)', overflow: 'hidden' }}>

      {/* ─── Left: Form panel ─── */}
      <div style={{
        flex: 1,
        background: 'var(--bg-surface)',
        display: 'flex', flexDirection: 'column',
        borderRight: '1px solid var(--border)',
      }}>

        {/* Top nav */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          height: 64, padding: '0 40px', flexShrink: 0,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 7,
              background: 'var(--accent)', display: 'grid', placeItems: 'center',
              color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14,
            }}>1</div>
            <span className="font-display" style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>1Radar</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-muted)' }}>
            {isRegister
              ? <>Already have an account?{' '}
                  <button className="btn btn-stroke btn-sm" onClick={() => switchMode('login')}>Login</button>
                </>
              : <>Don't have an account?{' '}
                  <button className="btn btn-stroke btn-sm" onClick={() => switchMode('register')}>Register</button>
                </>
            }
          </div>
        </div>

        {/* Form body */}
        <form
          onSubmit={handleSubmit}
          style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '32px 56px 60px', maxWidth: 600, width: '100%', margin: '0 auto' }}
        >

          {/* Register icon */}
          {isRegister && (
            <div style={{
              width: 54, height: 54, borderRadius: '50%',
              background: 'var(--bg-soft)', border: '1px solid var(--border)',
              display: 'grid', placeItems: 'center', marginBottom: 20,
              alignSelf: 'center',
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="10" cy="8" r="4"/><path d="M2 21c0-4 3.6-7 8-7"/><path d="M19 11v6M16 14h6"/>
              </svg>
            </div>
          )}

          <div className="font-display" style={{ fontSize: 24, fontWeight: 600, color: 'var(--text)', lineHeight: 1.2, textAlign: 'center' }}>
            {isRegister ? 'Create a new account' : 'Login to your account'}
          </div>
          <div style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.5, textAlign: 'center' }}>
            {isRegister ? 'Enter your details to register.' : 'Enter your details to login.'}
          </div>

          {/* Google SSO */}
          <button type="button" className="btn btn-stroke" style={{ height: 42, justifyContent: 'center', marginTop: 24, borderRadius: 10, gap: 8, fontSize: 14 }}>
            <Icon name="google" size={18}/> Continue with Google
          </button>

          {/* OR divider */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '18px 0', color: 'var(--text-faint)', fontSize: 11, letterSpacing: '0.06em' }}>
            <span style={{ flex: 1, height: 1, background: 'var(--border)' }}/>
            OR
            <span style={{ flex: 1, height: 1, background: 'var(--border)' }}/>
          </div>

          {/* Error banner */}
          {error && (
            <div style={{
              background: 'color-mix(in srgb, var(--danger) 12%, transparent)',
              border: '1px solid color-mix(in srgb, var(--danger) 30%, transparent)',
              borderRadius: 10, padding: '10px 14px', marginBottom: 14,
              fontSize: 13, color: 'var(--danger)', lineHeight: 1.4,
            }}>
              {error}
            </div>
          )}

          {/* Fields */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

            {isRegister && (
              <div>
                <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-2)' }}>
                  Full Name <span style={{ color: 'var(--danger)' }}>*</span>
                </label>
                <div className="fld" style={{ height: 42, marginTop: 6, width: '100%', borderRadius: 10 }}>
                  <Icon name="user" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                  <input
                    placeholder="James Brown"
                    value={fields.name}
                    onChange={setField('name')}
                    required
                  />
                </div>
              </div>
            )}

            <div>
              <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-2)' }}>
                Email Address <span style={{ color: 'var(--danger)' }}>*</span>
              </label>
              <div className="fld" style={{ height: 42, marginTop: 6, width: '100%', borderRadius: 10 }}>
                <Icon name="mail" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                <input
                  type="email"
                  placeholder={isRegister ? 'ange@monarchparis.com' : 'ange@euspy.app'}
                  value={fields.email}
                  onChange={setField('email')}
                  required
                />
              </div>
            </div>

            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-2)' }}>
                  Password <span style={{ color: 'var(--danger)' }}>*</span>
                </label>
                {!isRegister && (
                  <a style={{ fontSize: 12, color: 'var(--text-subtle)', cursor: 'pointer', textDecoration: 'underline' }}>
                    Forgot password?
                  </a>
                )}
              </div>
              <div className="fld" style={{ height: 42, width: '100%', borderRadius: 10 }}>
                <Icon name="lock" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                <input
                  type={showPw ? 'text' : 'password'}
                  placeholder="••••••••••"
                  value={fields.password}
                  onChange={setField('password')}
                  required
                />
                <button
                  type="button"
                  style={{ display: 'flex', alignItems: 'center', color: 'var(--text-faint)', flexShrink: 0 }}
                  onClick={() => setShowPw(v => !v)}
                >
                  <Icon name={showPw ? 'eye-off' : 'eye'} size={15}/>
                </button>
              </div>
              {isRegister && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 7, color: 'var(--text-faint)', fontSize: 12 }}>
                  <Icon name="info" size={12}/>
                  Must contain 1 uppercase letter, 1 number, min. 8 characters.
                </div>
              )}
            </div>
          </div>

          {/* CTA button */}
          <button
            type="submit"
            className="btn btn-primary"
            disabled={loading}
            style={{ height: 44, justifyContent: 'center', marginTop: 20, borderRadius: 10, fontSize: 14, fontWeight: 600, width: '100%', opacity: loading ? 0.7 : 1 }}
          >
            {loading ? (isRegister ? 'Creating account…' : 'Logging in…') : (isRegister ? 'Register' : 'Login')}
          </button>

          {/* Terms */}
          <div style={{ marginTop: 20, fontSize: 12, color: 'var(--text-faint)', textAlign: 'center', lineHeight: 1.7 }}>
            By continuing, you agree to our{' '}
            <a style={{ color: 'var(--text-subtle)', textDecoration: 'underline', cursor: 'pointer' }}>Terms of Service</a>
            {' '}·{' '}
            <a style={{ color: 'var(--text-subtle)', textDecoration: 'underline', cursor: 'pointer' }}>Privacy Policy</a>
          </div>
        </form>
      </div>

      {/* ─── Right: Real AdCards showcase ─── */}
      <div style={{
        flex: 1,
        background: 'var(--bg-soft)',
        position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>

        {/* Scrolling cards — non-interactive */}
        <div style={{
          flex: 1, overflow: 'hidden',
          padding: '24px 24px 0',
          pointerEvents: 'none', userSelect: 'none',
        }}>
          <div style={{
            columns: 2, columnGap: 12,
          }}>
            {(window.ADS_V3 || []).slice(0, 8).map((ad, i) => (
              <div key={ad.id} style={{ breakInside: 'avoid', marginBottom: 12 }}>
                <AdCard ad={ad} rank={i + 1} fields={AD_CARD_FIELDS_DEFAULT}/>
              </div>
            ))}
          </div>
        </div>

        {/* Top fade */}
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: 40, zIndex: 2,
          background: 'linear-gradient(to bottom, var(--bg-soft), transparent)',
          pointerEvents: 'none',
        }}/>

        {/* Bottom fade + text */}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 2,
          background: 'linear-gradient(to top, var(--bg-soft) 75%, transparent)',
          padding: '100px 32px 32px',
          display: 'flex', flexDirection: 'column', alignItems: 'center',
        }}>
          <div className="font-display" style={{ fontSize: 20, fontWeight: 600, color: 'var(--text)', lineHeight: 1.35, textAlign: 'center' }}>
            {slides[slideIdx].title}
          </div>
          <div style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.6, textAlign: 'center', maxWidth: 360 }}>
            {slides[slideIdx].sub}
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
            {slides.map((_, i) => (
              <div
                key={i}
                onClick={() => setSlideIdx(i)}
                style={{
                  width: i === slideIdx ? 22 : 6, height: 6, borderRadius: 999,
                  background: i === slideIdx ? 'var(--accent)' : 'var(--border)',
                  cursor: 'pointer', transition: 'all .3s ease',
                  pointerEvents: 'all',
                }}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { OnboardingV3 });
