// AuthScreen — full-viewport auth gate before main app loads
// Restored from commit 7311145 — was removed when AstraReach.html was rewritten

const AuthScreen = ({ onAuth }) => {
  const urlPlan = new URLSearchParams(window.location.search).get('plan');
  const initialTab = urlPlan ? 'create' : 'signin';
  const initialPlan = urlPlan || 'growth';

  const [tab, setTab] = React.useState(initialTab);
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [name, setName] = React.useState('');
  const [plan, setPlan] = React.useState(initialPlan);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [showPassword, setShowPassword] = React.useState(false);
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [showConfirmPassword, setShowConfirmPassword] = React.useState(false);
  const [step, setStep] = React.useState('form'); // 'form' | 'success'
  const [socialInfo, setSocialInfo] = React.useState('');

  const S = {
    overlay: {
      position: 'fixed', inset: 0, background: '#07090F',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start',
      fontFamily: "'Inter', system-ui, sans-serif", zIndex: 9999,
      padding: '20px 16px', minHeight: '100vh', overflowY: 'auto',
    },
    card: {
      width: '100%', maxWidth: 460, background: '#0B0F1A',
      border: '1px solid #232A3B', borderRadius: 16, overflow: 'hidden',
      boxShadow: '0 24px 64px rgba(0,0,0,0.6), 0 0 0 1px rgba(139,92,246,0.06)',
    },
    brandRow: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: '28px 0 22px' },
    logoMark: {
      width: 36, height: 36, borderRadius: 10,
      background: 'linear-gradient(135deg, #8B5CF6 0%, #6D28D9 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 0 0 1px rgba(139,92,246,0.4), 0 4px 16px rgba(139,92,246,0.3)',
    },
    wordmark: { fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em', color: '#F4F6FB' },
    tabStrip: { display: 'flex', borderBottom: '1px solid #232A3B', margin: '0 24px' },
    body: { padding: '24px 24px 20px' },
    label: { display: 'block', fontSize: 11, fontWeight: 600, color: '#A8B0C2', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 },
    inputWrap: { marginBottom: 14 },
    input: { width: '100%', boxSizing: 'border-box', padding: '10px 12px', fontSize: 13, background: '#111827', border: '1px solid #232A3B', borderRadius: 8, color: '#F4F6FB', outline: 'none', fontFamily: 'inherit' },
    inputPw: { width: '100%', boxSizing: 'border-box', padding: '10px 38px 10px 12px', fontSize: 13, background: '#111827', border: '1px solid #232A3B', borderRadius: 8, color: '#F4F6FB', outline: 'none', fontFamily: 'inherit' },
    pwWrap: { position: 'relative' },
    eyeBtn: { position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#6B7489', padding: 2, display: 'flex', alignItems: 'center' },
    btnBase: { width: '100%', padding: '11px 0', fontSize: 13, fontWeight: 600, borderRadius: 8, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontFamily: 'inherit' },
    btnPrimary: { background: 'linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%)', color: '#fff', border: 'none', boxShadow: '0 4px 16px rgba(139,92,246,0.35)' },
    btnDemo: { background: '#111827', color: '#A8B0C2', border: '1px solid #232A3B' },
    orRow: { display: 'flex', alignItems: 'center', gap: 10, margin: '14px 0', fontSize: 11, color: '#6B7489' },
    orLine: { flex: 1, height: 1, background: '#232A3B' },
    errorBox: { padding: '9px 12px', borderRadius: 8, background: 'rgba(244,63,94,0.1)', border: '1px solid rgba(244,63,94,0.3)', color: '#F43F5E', fontSize: 12, marginBottom: 14, lineHeight: 1.5 },
    switchRow: { textAlign: 'center', fontSize: 12, color: '#6B7489', marginTop: 14 },
    switchLink: { color: '#8B5CF6', cursor: 'pointer', textDecoration: 'underline', textDecorationColor: 'rgba(139,92,246,0.4)' },
    demoNote: { textAlign: 'center', fontSize: 11, color: '#6B7489', marginTop: 10, lineHeight: 1.5 },
    planGrid: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 14 },
    planCard: (sel, feat) => ({
      padding: '10px 8px', borderRadius: 10, cursor: 'pointer',
      border: sel ? '2px solid #8B5CF6' : feat ? '1.5px solid rgba(139,92,246,0.35)' : '1.5px solid #232A3B',
      background: sel ? 'rgba(139,92,246,0.12)' : feat ? 'rgba(139,92,246,0.06)' : '#111827',
      textAlign: 'center', position: 'relative', transition: 'border-color .15s, background .15s',
    }),
    planName: { fontSize: 11, fontWeight: 700, color: '#F4F6FB', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 3 },
    popularBadge: { position: 'absolute', top: -9, left: '50%', transform: 'translateX(-50%)', background: '#8B5CF6', color: '#fff', fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', padding: '2px 8px', borderRadius: 20, textTransform: 'uppercase', whiteSpace: 'nowrap' },
    spinner: { width: 15, height: 15, border: '2px solid rgba(255,255,255,0.2)', borderTopColor: '#fff', borderRadius: '50%', animation: 'ar-auth-spin 0.7s linear infinite', flexShrink: 0 },
    successWrap: { textAlign: 'center', padding: '10px 0 6px' },
    successIcon: { width: 52, height: 52, borderRadius: '50%', background: 'rgba(16,185,129,0.15)', border: '1.5px solid rgba(16,185,129,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' },
    successTitle: { fontSize: 18, fontWeight: 700, color: '#F4F6FB', marginBottom: 6 },
    successSub: { fontSize: 13, color: '#A8B0C2', marginBottom: 20, lineHeight: 1.55 },
    cardFooter: { textAlign: 'center', padding: '10px 0 14px', fontSize: 10, color: '#3A4155' },
  };

  React.useEffect(() => {
    if (document.getElementById('ar-auth-kf')) return;
    const el = document.createElement('style');
    el.id = 'ar-auth-kf';
    el.textContent = '@keyframes ar-auth-spin { to { transform: rotate(360deg); } }';
    document.head.appendChild(el);
  }, []);

  const switchTab = (t) => { setTab(t); setError(''); setStep('form'); setConfirmPassword(''); setPassword(''); setName(''); setSocialInfo(''); };

  const handleSignIn = async () => {
    setError('');
    if (!email.trim()) { setError('Please enter your email address.'); return; }
    if (!password) { setError('Please enter your password.'); return; }
    setLoading(true);
    try {
      const res = await arFetch('/v1/auth/login', { method: 'POST', body: JSON.stringify({ email: email.trim(), password }) });
      const token = res && (res.token || res.access_token);
      if (token) localStorage.setItem('ar_token', token);
      onAuth({ email: email.trim() });
    } catch (err) {
      setError('Invalid credentials or server offline.');
    } finally { setLoading(false); }
  };

  const handleCreate = async () => {
    setError('');
    if (!name.trim()) { setError('Please enter your full name.'); return; }
    if (!email.trim()) { setError('Please enter your email address.'); return; }
    if (password.length < 8) { setError('Password must be at least 8 characters.'); return; }
    if (confirmPassword !== password) { setError('Passwords do not match.'); return; }
    setLoading(true);
    try {
      await arFetch('/v1/auth/register', { method: 'POST', body: JSON.stringify({ name: name.trim(), email: email.trim(), password, plan }) });
    } catch (_) { /* Demo/offline: proceed anyway */ }
    finally { setLoading(false); }
    setStep('success');
    setTimeout(() => onAuth({ email: email.trim(), plan }), 2400);
  };

  const Spinner = () => <div style={S.spinner} />;

  const EyeIcon = ({ open }) => (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      {open
        ? React.createElement(React.Fragment, null,
            React.createElement('path', { d: 'M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z' }),
            React.createElement('circle', { cx: '12', cy: '12', r: '3' }))
        : React.createElement(React.Fragment, null,
            React.createElement('path', { d: 'M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94' }),
            React.createElement('path', { d: 'M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19' }),
            React.createElement('line', { x1: '1', y1: '1', x2: '23', y2: '23' }))}
    </svg>
  );

  const OrDivider = () => <div style={S.orRow}><div style={S.orLine} /><span>or</span><div style={S.orLine} /></div>;

  const DemoButton = () => (
    <button style={{ ...S.btnBase, ...S.btnDemo }} onClick={() => { localStorage.setItem('ar_demo', '1'); onAuth({ email: 'demo' }); }} disabled={loading}>
      Continue as Demo
    </button>
  );

  const PLANS = [
    { key: 'starter',    label: 'Starter',    price: '$0',           featured: false },
    { key: 'teams',      label: 'Teams',      price: '$600/mo',      featured: false },
    { key: 'growth',     label: 'Growth',     price: '$1,200/mo',    featured: true  },
    { key: 'enterprise', label: 'Enterprise', price: 'Contact sales', featured: false },
  ];

  const PlanSelector = () => (
    <div>
      <label style={S.label}>Plan</label>
      <div style={S.planGrid}>
        {PLANS.map(p => (
          <div key={p.key} style={S.planCard(plan === p.key, p.featured)} onClick={() => setPlan(p.key)}>
            {p.featured && <div style={S.popularBadge}>Popular</div>}
            <div style={S.planName}>{p.label}</div>
            <div style={{ fontSize: 12, fontWeight: 600, color: plan === p.key ? '#c4b5fd' : '#A8B0C2', marginTop: 2 }}>{p.price}</div>
          </div>
        ))}
      </div>
    </div>
  );

  const TabButton = ({ id, label }) => (
    <button onClick={() => switchTab(id)} style={{ flex: 1, padding: '10px 0', fontSize: 13, fontWeight: 500, color: tab === id ? '#F4F6FB' : '#6B7489', borderBottom: tab === id ? '2px solid #8B5CF6' : '2px solid transparent', marginBottom: -1, background: 'transparent', border: 'none', cursor: 'pointer' }}>
      {label}
    </button>
  );

  const socialProviders = [
    { key: 'google', label: 'Google',      bg: '#fff',    fg: '#1a1a1a', icon: '🔵' },
    { key: 'github', label: 'GitHub',      bg: '#24292e', fg: '#fff',    icon: '⚫' },
    { key: 'x',      label: 'X / Twitter', bg: '#000',    fg: '#fff',    icon: '✖' },
  ];

  const SocialButtons = () => (
    <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
      {socialProviders.map(p => (
        <button key={p.key} disabled title="OAuth integration coming soon" style={{ flex: 1, padding: '9px 0', fontSize: 12, fontWeight: 500, background: p.bg, color: p.fg, border: '1px solid #232A3B', borderRadius: 8, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontFamily: 'inherit' }}
          onClick={() => setSocialInfo(`${p.label} OAuth: configure credentials in Settings → Developer`)}>
          {p.icon} {p.label}
        </button>
      ))}
    </div>
  );

  return (
    <div style={S.overlay}>
      <div style={{ position: 'fixed', top: '30%', left: '50%', transform: 'translateX(-50%)', width: 500, height: 500, pointerEvents: 'none', zIndex: -1, background: 'radial-gradient(ellipse at center, rgba(139,92,246,0.09) 0%, transparent 68%)' }} />
      <div style={S.card}>
        <div style={S.brandRow}>
          <div style={S.logoMark}>
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none">
              <path d="M12 2L3 7l9 5 9-5-9-5z" fill="rgba(255,255,255,0.92)" />
              <path d="M3 12l9 5 9-5" stroke="rgba(255,255,255,0.55)" strokeWidth="1.5" fill="none" strokeLinecap="round" />
              <path d="M3 17l9 5 9-5" stroke="rgba(255,255,255,0.28)" strokeWidth="1.5" fill="none" strokeLinecap="round" />
            </svg>
          </div>
          <span style={S.wordmark}>AstraReach</span>
        </div>

        <div style={S.tabStrip}>
          <TabButton id="signin" label="Sign in" />
          <TabButton id="create" label="Create account" />
        </div>

        <div style={S.body}>
          {tab === 'signin' ? (
            <div>
              {error && <div style={S.errorBox}>{error}</div>}
              <div style={S.inputWrap}>
                <label style={S.label}>Email</label>
                <input type="email" placeholder="you@company.com" value={email} onChange={e => { setEmail(e.target.value); setError(''); }} onKeyDown={e => e.key === 'Enter' && !loading && handleSignIn()} style={S.input} autoComplete="email" autoFocus />
              </div>
              <div style={S.inputWrap}>
                <label style={S.label}>Password</label>
                <div style={S.pwWrap}>
                  <input type={showPassword ? 'text' : 'password'} placeholder="••••••••" value={password} onChange={e => { setPassword(e.target.value); setError(''); }} onKeyDown={e => e.key === 'Enter' && !loading && handleSignIn()} style={S.inputPw} autoComplete="current-password" />
                  <button style={S.eyeBtn} onClick={() => setShowPassword(v => !v)} type="button" tabIndex={-1}><EyeIcon open={showPassword} /></button>
                </div>
              </div>
              <button style={{ ...S.btnBase, ...S.btnPrimary, marginTop: 4, opacity: loading ? 0.72 : 1, cursor: loading ? 'not-allowed' : 'pointer' }} onClick={handleSignIn} disabled={loading}>
                {loading && <Spinner />}{loading ? 'Signing in…' : 'Sign in with Supabase'}
              </button>
              <OrDivider />
              <SocialButtons />
              {socialInfo && (
                <div style={{fontSize:11,color:'var(--text-3)',background:'var(--bg-3)',
                  border:'1px solid var(--border)',borderRadius:6,padding:'8px 10px',
                  marginTop:8,lineHeight:1.5}}>
                  {socialInfo}
                </div>
              )}
              <DemoButton />
              <div style={S.demoNote}>Demo mode gives you full read access to all features with sample data.</div>
              <div style={S.switchRow}>Don't have an account?{' '}<span style={S.switchLink} onClick={() => switchTab('create')}>Create one →</span></div>
            </div>
          ) : (
            <div>
              {step === 'success' ? (
                <div style={S.successWrap}>
                  <div style={S.successIcon}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                  </div>
                  <div style={S.successTitle}>Account created!</div>
                  <div style={S.successSub}>Welcome to AstraReach. Setting up your workspace on the <span style={{ color: '#c4b5fd', fontWeight: 600 }}>{(PLANS.find(p => p.key === plan) || {}).label || plan}</span> plan — launching now…</div>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <div style={{ width: 18, height: 18, border: '2px solid rgba(16,185,129,0.25)', borderTopColor: '#10B981', borderRadius: '50%', animation: 'ar-auth-spin 0.7s linear infinite' }} />
                  </div>
                </div>
              ) : (
                <div>
                  {error && <div style={S.errorBox}>{error}</div>}
                  <div style={S.inputWrap}>
                    <label style={S.label}>Full Name</label>
                    <input type="text" placeholder="Alex Johnson" value={name} onChange={e => { setName(e.target.value); setError(''); }} style={S.input} autoComplete="name" />
                  </div>
                  <div style={S.inputWrap}>
                    <label style={S.label}>Email</label>
                    <input type="email" placeholder="you@company.com" value={email} onChange={e => { setEmail(e.target.value); setError(''); }} style={S.input} autoComplete="email" />
                  </div>
                  <div style={S.inputWrap}>
                    <label style={S.label}>Password</label>
                    <div style={S.pwWrap}>
                      <input type={showPassword ? 'text' : 'password'} placeholder="Min 8 characters" value={password} onChange={e => { setPassword(e.target.value); setError(''); }} style={S.inputPw} autoComplete="new-password" />
                      <button style={S.eyeBtn} onClick={() => setShowPassword(v => !v)} type="button" tabIndex={-1}><EyeIcon open={showPassword} /></button>
                    </div>
                    {password.length > 0 && password.length < 8 && <div style={{ fontSize: 11, color: '#F59E0B', marginTop: 5 }}>{8 - password.length} more character{8 - password.length !== 1 ? 's' : ''} required</div>}
                    {password.length >= 8 && <div style={{ fontSize: 11, color: '#10B981', marginTop: 5 }}>Password strength looks good</div>}
                  </div>
                  <div style={{ ...S.inputWrap, marginBottom: 18 }}>
                    <label style={S.label}>Confirm Password</label>
                    <div style={S.pwWrap}>
                      <input type={showConfirmPassword ? 'text' : 'password'} placeholder="Re-enter your password" value={confirmPassword} onChange={e => { setConfirmPassword(e.target.value); setError(''); }} onKeyDown={e => e.key === 'Enter' && !loading && handleCreate()} style={S.inputPw} autoComplete="new-password" />
                      <button style={S.eyeBtn} onClick={() => setShowConfirmPassword(v => !v)} type="button" tabIndex={-1}><EyeIcon open={showConfirmPassword} /></button>
                    </div>
                    {confirmPassword.length > 0 && confirmPassword !== password && <div style={{ fontSize: 11, color: '#F43F5E', marginTop: 5 }}>Passwords do not match</div>}
                    {confirmPassword.length > 0 && confirmPassword === password && password.length >= 8 && <div style={{ fontSize: 11, color: '#10B981', marginTop: 5 }}>Passwords match ✓</div>}
                  </div>
                  <PlanSelector />
                  <button style={{ ...S.btnBase, ...S.btnPrimary, opacity: loading ? 0.72 : 1, cursor: loading ? 'not-allowed' : 'pointer' }} onClick={handleCreate} disabled={loading}>
                    {loading && <Spinner />}{loading ? 'Creating account…' : 'Create account + start trial'}
                  </button>
                  <OrDivider />
                  <SocialButtons />
                  {socialInfo && (
                    <div style={{fontSize:11,color:'var(--text-3)',background:'var(--bg-3)',
                      border:'1px solid var(--border)',borderRadius:6,padding:'8px 10px',
                      marginTop:8,lineHeight:1.5}}>
                      {socialInfo}
                    </div>
                  )}
                  <DemoButton />
                  <div style={S.switchRow}>Already have an account?{' '}<span style={S.switchLink} onClick={() => switchTab('signin')}>Sign in →</span></div>
                </div>
              )}
            </div>
          )}
        </div>
        <div style={S.cardFooter}>By continuing you agree to our Terms of Service and Privacy Policy.</div>
      </div>
    </div>
  );
};

window.AuthScreen = AuthScreen;
