
// ── Auth Page (Login / Sign Up) ──────────────────────────────────────────────
const AuthPage = ({ onAuth }) => {
  const [tab, setTab] = React.useState('login');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [name, setName] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState('');

  const inputStyle = (err) => ({
    width: '100%', boxSizing: 'border-box',
    fontFamily: 'Inter, sans-serif', fontSize: '15px',
    padding: '13px 16px', borderRadius: '8px',
    border: `1.5px solid ${err ? '#E53E3E' : '#E2E8F0'}`,
    color: '#1B2A4A', background: '#fff', outline: 'none',
    transition: 'border-color 0.2s',
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(''); setSuccess('');
    if (!email || !password) { setError('Email and password are required.'); return; }
    if (password.length < 6) { setError('Password must be at least 6 characters.'); return; }
    setLoading(true);

    if (!SUPABASE_CONFIGURED) {
      // Demo mode — mock auth
      await new Promise(r => setTimeout(r, 800));
      const mockUser = {
        id: tab === 'login' && email.includes('admin') ? 'admin-mock' : 'client-mock',
        email,
        is_admin: email.includes('admin'),
        full_name: name || email.split('@')[0],
      };
      localStorage.setItem('sss_mock_user', JSON.stringify(mockUser));
      onAuth(mockUser);
      setLoading(false);
      return;
    }

    try {
      if (tab === 'signup') {
        const res = await supa.signUp(email, password);
        if (res.error) { setError(res.error.message); setLoading(false); return; }
        // Update name in profile
        if (res.user && name) {
          await supa.update('profiles', { full_name: name }, `id=eq.${res.user.id}`);
        }
        setSuccess('Account created! Check your email to confirm, then log in.');
        setTab('login');
      } else {
        const res = await supa.signIn(email, password);
        if (res.error) { setError(res.error.message); setLoading(false); return; }
        try {
          await supa.claimCustomerRecords();
        } catch {}
        const profile = await supa.getProfile(res.user.id);
        onAuth({ ...res.user, ...profile });
      }
    } catch (err) {
      setError('Something went wrong. Please try again.');
    }
    setLoading(false);
  };

  return (
    <div style={{
      minHeight: '100vh', background: 'linear-gradient(160deg, #0F1D33 0%, #1B2A4A 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '32px 16px', fontFamily: 'Inter, sans-serif',
    }}>
      {/* Background texture */}
      {Array.from({ length: 12 }).map((_, i) => (
        <div key={i} style={{
          position: 'fixed', top: 0, bottom: 0, left: `${i * 8.5}%`, width: '1px',
          background: 'rgba(74,159,212,0.05)', pointerEvents: 'none',
        }} />
      ))}

      <div style={{ width: '100%', maxWidth: '440px', position: 'relative', zIndex: 1 }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: '32px' }}>
          <img src="uploads/logo-7179fe62.png" alt="Sea Steel Storage"
            style={{ height: '48px', margin: '0 auto', display: 'block', objectFit: 'contain' }} />
          <p style={{ color: 'rgba(255,255,255,0.45)', fontSize: '13px', marginTop: '10px' }}>
            {SUPABASE_CONFIGURED ? 'Sign in to your account' : '⚠ Demo mode — Supabase not configured'}
          </p>
        </div>

        <div style={{
          background: '#fff', borderRadius: '16px', overflow: 'hidden',
          boxShadow: '0 24px 64px rgba(0,0,0,0.4)',
        }}>
          {/* Tabs */}
          <div style={{ display: 'flex', borderBottom: '1px solid #EEF2F7' }}>
            {[['login', 'Sign In'], ['signup', 'Create Account']].map(([val, label]) => (
              <button key={val} onClick={() => { setTab(val); setError(''); setSuccess(''); }} style={{
                flex: 1, padding: '18px', border: 'none', cursor: 'pointer',
                fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600',
                background: tab === val ? '#fff' : '#F9FAFB',
                color: tab === val ? '#1B2A4A' : '#9AAAB8',
                borderBottom: tab === val ? '2px solid #4A9FD4' : '2px solid transparent',
                transition: 'all 0.2s',
              }}>
                {label}
              </button>
            ))}
          </div>

          <form onSubmit={handleSubmit} style={{ padding: '32px' }}>
            {!SUPABASE_CONFIGURED && (
              <div style={{
                background: '#FFF8E1', border: '1px solid #FFE082', borderRadius: '8px',
                padding: '12px 14px', marginBottom: '20px',
                fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#856404', lineHeight: '1.5',
              }}>
                <strong>Demo mode active.</strong> Use any email/password. Use "admin@..." to preview the Admin dashboard.
              </div>
            )}

            {success && (
              <div style={{ background: '#F0FFF4', border: '1px solid #9AE6B4', borderRadius: '8px', padding: '12px 14px', marginBottom: '20px', fontSize: '13px', color: '#276749' }}>
                ✓ {success}
              </div>
            )}

            {error && (
              <div style={{ background: '#FFF5F5', border: '1px solid #FEB2B2', borderRadius: '8px', padding: '12px 14px', marginBottom: '20px', fontSize: '13px', color: '#C53030' }}>
                {error}
              </div>
            )}

            {tab === 'signup' && (
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Full Name</label>
                <input type="text" placeholder="Jane Smith" value={name}
                  onChange={e => setName(e.target.value)} style={inputStyle(false)}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                />
              </div>
            )}

            <div style={{ marginBottom: '16px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Email Address</label>
              <input type="email" placeholder="you@example.com" value={email}
                onChange={e => setEmail(e.target.value)} style={inputStyle(false)}
                onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                onBlur={e => e.target.style.borderColor = '#E2E8F0'}
              />
            </div>

            <div style={{ marginBottom: '24px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Password</label>
              <input type="password" placeholder={tab === 'signup' ? 'Min. 6 characters' : '••••••••'} value={password}
                onChange={e => setPassword(e.target.value)} style={inputStyle(false)}
                onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                onBlur={e => e.target.style.borderColor = '#E2E8F0'}
              />
            </div>

            <button type="submit" disabled={loading} style={{
              width: '100%', padding: '14px', background: loading ? '#9AAAB8' : '#1B2A4A',
              color: '#fff', border: 'none', borderRadius: '8px', cursor: loading ? 'not-allowed' : 'pointer',
              fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700',
              transition: 'background 0.2s', letterSpacing: '0.01em',
            }}
            onMouseEnter={e => { if (!loading) e.target.style.background = '#4A9FD4'; }}
            onMouseLeave={e => { if (!loading) e.target.style.background = '#1B2A4A'; }}
            >
              {loading ? 'Please wait…' : tab === 'login' ? 'Sign In →' : 'Create Account →'}
            </button>

            {tab === 'login' && (
              <p style={{ textAlign: 'center', marginTop: '16px', fontSize: '13px', color: '#9AAAB8' }}>
                Don't have an account?{' '}
                <button onClick={() => setTab('signup')} style={{ background: 'none', border: 'none', color: '#4A9FD4', fontWeight: '600', cursor: 'pointer', fontSize: '13px', padding: 0 }}>
                  Sign up free
                </button>
              </p>
            )}
          </form>
        </div>

        <p style={{ textAlign: 'center', marginTop: '20px', fontSize: '12px', color: 'rgba(255,255,255,0.3)' }}>
          Sea Steel Storage · Secure portal
        </p>
      </div>
    </div>
  );
};

Object.assign(window, { AuthPage });
