// Auth screens — Login + Google OAuth (real API)
const AuthScreen = ({ onLogin }) => {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await api.auth.login(username, password);
      api.setToken(res.token);
      onLogin(res.user);
    } catch (err) {
      setError(err.status === 401 ? 'Invalid username or password.' : (err.message || 'Login failed.'));
      setLoading(false);
    }
  };

  const handleGoogleLogin = () => {
    window.location.href = api.auth.googleLoginUrl(window.location.pathname);
  };

  return (
    <div style={authStyles.backdrop}>
      <div style={authStyles.panel}>
        {/* Logo */}
        <div style={authStyles.logoArea}>
          <div style={authStyles.logoIcon}>⚔</div>
          <div style={authStyles.logoText}>KAMIA</div>
          <div style={authStyles.logoSub}>Campaign Registry</div>
        </div>

        <form onSubmit={handleLogin} style={authStyles.form}>
          <label style={authStyles.label}>Username</label>
          <input
            style={authStyles.input}
            value={username}
            onChange={e => setUsername(e.target.value)}
            placeholder="Enter your username"
            autoComplete="username"
          />
          <label style={authStyles.label}>Password</label>
          <input
            style={authStyles.input}
            type="password"
            value={password}
            onChange={e => setPassword(e.target.value)}
            placeholder="Enter your password"
            autoComplete="current-password"
          />
          {error && <div style={authStyles.error}>{error}</div>}
          <button style={authStyles.btnPrimary} type="submit" disabled={loading}>
            {loading ? 'Signing in…' : 'Sign In'}
          </button>
        </form>
        <div style={authStyles.divider}><span>or</span></div>
        <button style={authStyles.btnGoogle} onClick={handleGoogleLogin}>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{marginRight:8}}>
            <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
            <path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z" fill="#34A853"/>
            <path d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/>
            <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
          </svg>
          Continue with Google
        </button>
        <div style={authStyles.hint}>
          <strong>Demo:</strong> username <code style={authStyles.code}>marek</code> / <code style={authStyles.code}>syra</code> / <code style={authStyles.code}>liora</code> — password <code style={authStyles.code}>admin123</code> or <code style={authStyles.code}>player123</code> or <code style={authStyles.code}>dm123</code>
        </div>
      </div>
    </div>
  );
};

// Avatar-tint helper. Accepts either a string role ('Admin','DM','Co-DM','Player')
// or a user/member object (we sniff isAdmin or .role). Returns a hex color.
// Roles are now per-campaign — pass member-shape objects from campaign.members
// for player-row tints; pass the user object for the system-admin tint.
function roleColor(arg) {
  let r = '';
  if (typeof arg === 'string') r = arg;
  else if (arg && typeof arg === 'object') {
    if ('isAdmin' in arg) return arg.isAdmin ? '#7c3aed' : '#3a5c7a';
    if (arg.role) r = arg.role;
  }
  const k = (r || '').toLowerCase();
  if (k === 'admin')  return '#7c3aed';
  if (k === 'dm')     return '#c53030';
  if (k === 'co-dm')  return '#b45309';
  if (k === 'player') return '#1e6b3c';
  return '#374151';
}

const authStyles = {
  backdrop: {
    minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: 'radial-gradient(ellipse at 50% 0%, #2a0a0a 0%, #0f0f14 60%)',
    fontFamily: "'Nunito', sans-serif",
  },
  panel: {
    background: '#1c1c22', border: '1px solid #3a3a42', borderRadius: 12,
    padding: '40px 36px', width: 380, boxShadow: '0 24px 64px rgba(0,0,0,0.6)',
  },
  logoArea: { textAlign: 'center', marginBottom: 32 },
  logoIcon: { fontSize: 32, marginBottom: 4 },
  logoText: {
    fontFamily: "'Cinzel', serif", fontSize: 28, fontWeight: 700,
    color: '#c9a227', letterSpacing: '0.15em',
  },
  logoSub: { fontSize: 12, color: '#6b6966', letterSpacing: '0.2em', textTransform: 'uppercase', marginTop: 2 },
  form: { display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 16 },
  label: { fontSize: 12, color: '#9a9793', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' },
  input: {
    background: '#111116', border: '1px solid #3a3a42', borderRadius: 6,
    color: '#e8e6e3', padding: '10px 14px', fontSize: 14, outline: 'none',
    fontFamily: "'Nunito', sans-serif",
  },
  error: { color: '#f87171', fontSize: 13, padding: '8px 12px', background: 'rgba(239,68,68,0.1)', borderRadius: 6 },
  btnPrimary: {
    background: '#c53030', color: '#fff', border: 'none', borderRadius: 6,
    padding: '12px 0', fontWeight: 700, fontSize: 14, cursor: 'pointer',
    fontFamily: "'Nunito', sans-serif", marginTop: 4,
  },
  btnGoogle: {
    width: '100%', background: '#1c1c22', border: '1px solid #3a3a42', borderRadius: 6,
    color: '#e8e6e3', padding: '11px 0', fontWeight: 600, fontSize: 14, cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: "'Nunito', sans-serif",
  },
  divider: {
    textAlign: 'center', color: '#4a4a52', fontSize: 12, margin: '16px 0',
    borderTop: '1px solid #2a2a32', paddingTop: 16, position: 'relative',
  },
  hint: {
    marginTop: 20, padding: 12, background: 'rgba(201,162,39,0.08)', borderRadius: 6,
    fontSize: 12, color: '#9a9793', lineHeight: 1.6,
  },
  code: { background: '#111116', padding: '1px 5px', borderRadius: 3, color: '#c9a227', fontFamily: 'monospace' },
  googlePickerTitle: { fontSize: 16, fontWeight: 700, color: '#e8e6e3', marginBottom: 16 },
  googleUserRow: {
    width: '100%', display: 'flex', alignItems: 'center', gap: 12,
    background: 'none', border: '1px solid transparent', borderRadius: 8,
    padding: '10px 12px', cursor: 'pointer', marginBottom: 6, textAlign: 'left',
    transition: 'background 0.15s, border-color 0.15s',
  },
  avatar: {
    width: 36, height: 36, borderRadius: '50%', display: 'flex',
    alignItems: 'center', justifyContent: 'center', fontSize: 12,
    fontWeight: 700, color: '#fff', flexShrink: 0,
  },
};

Object.assign(window, { AuthScreen, roleColor });
